深度阅读

How to convert categorical data to numeric data in scikit-learn?

作者
作者
2023年08月22日
更新时间
17.37 分钟
阅读时间
0
阅读量

To convert categorical data to numerical data in scikit-learn, you can use several techniques, including Label Encoding and One-Hot Encoding.

  1. Label Encoding: Label Encoding is a technique that assigns a unique integer to each category in the feature. Scikit-learn provides LabelEncoder class for this purpose. Here’s an example:

from sklearn.preprocessing import LabelEncoder
import numpy as np

create sample data

data = np.array([‘apple’, ‘banana’, ‘pear’, ‘pear’, ‘banana’])

label encode the data

encoder = LabelEncoder()
encoded_data = encoder.fit_transform(data)

print(encoded_data)

In this example, we are using `LabelEncoder` to convert categories to integers. The fit_transform method fits the encoder on the data and labels each category with a unique integer.

2. One-Hot Encoding: One-Hot Encoding is a technique that creates a binary column for each category in the feature. Scikit-learn provides `OneHotEncoder` class for this purpose. Here's an example:

from sklearn.preprocessing import OneHotEncoder
import numpy as np

create sample data

data = np.array([[‘red’, ‘S’], [‘blue’, ‘M’], [‘green’, ‘L’], [‘blue’, ‘XL’]])

one-hot encode the data

encoder = OneHotEncoder(handle_unknown=’ignore’)
encoded_data = encoder.fit_transform(data)

print(encoded_data.toarray())



In this example, we are using `OneHotEncoder` to create binary columns for each category. The `toarray()` method converts the sparse matrix to a dense matrix.

By using these techniques, you can convert categorical data to numerical data in scikit-learn and prepare it for use in machine learning models.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。