一个热编码“得到意外的关键字参数'category'u features'”

2024-04-25 00:10:14 发布

您现在位置:Python中文网/ 问答频道 /正文

[categories[0] does not seem to be working [1]

0th column is what I'm trying to one hot encode

error : oneHot = OneHotEncoder(categorical_features = [0]) TypeError: init() got an unexpected keyword argument 'categorical_features'.

我正设法对第一列进行编码 下面是我的代码示例:

from sklearn.preprocessing import LabelEncoder,OneHotEncoder 
labelen_x = LabelEncoder() # string to numeric encoding object
x[:,0]= labelen_x.fit_transform(x[:,0]) # replaces the string labels with numerics for ML algorithm to be able to work with it
oneHot = OneHotEncoder(categorical_features = [0])
x = oneHot.fit_transform(x).toarray()

Tags: tostringinitwithtransformerrorfitfeatures
3条回答

初始化OHE类时不应传递任何obejct,只需执行以下操作:

from sklearn.preprocessing import OneHotEncoder 

# sample data
df = pd.DataFrame({'col': [0,1,2,3,0,1,2]})
colnames = ['col'] # modify this for your df

oneHot = OneHotEncoder()
x_ohe = oneHot.fit_transform(df[colnames].values.reshape(-1,1))

要检查一个热编码数据的外观(请参见矩阵),只需执行以下操作:

^{pr2}$

使用scikit learn版本0.21.3我可以获得正确的一个热编码,如下所示:

enter image description here

正如您在警告中看到的,参数categorical_features将在sklearn版本0.22之后贬值。所以,您需要使用ColumnTransformerHere是{}的文档

相关问题 更多 >