首页 > 解决方案 > OneHotEncoder categorical_features 已弃用,如何转换特定列

问题描述

我需要将独立字段从字符串转换为算术符号。我正在使用 OneHotEncoder 进行转换。我的数据集有许多独立的列,其中一些是:

Country     |    Age       
--------------------------
Germany     |    23
Spain       |    25
Germany     |    24
Italy       |    30 

我必须对 Country 列进行编码,例如

0     |    1     |     2     |       3
--------------------------------------
1     |    0     |     0     |      23
0     |    1     |     0     |      25
1     |    0     |     0     |      24 
0     |    0     |     1     |      30

我成功通过使用 OneHotEncoder 作为

#Encoding the categorical data
from sklearn.preprocessing import LabelEncoder

labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])

#we are dummy encoding as the machine learning algorithms will be
#confused with the values like Spain > Germany > France
from sklearn.preprocessing import OneHotEncoder

onehotencoder = OneHotEncoder(categorical_features=[0])
X = onehotencoder.fit_transform(X).toarray()

现在我收到要使用的折旧消息categories='auto'。如果我这样做,将对所有独立列(如国家、年龄、工资等)进行转换。

如何仅在数据集第 0 列上实现转换?

标签: pythonmachine-learningcategorical-dataone-hot-encoding

解决方案


实际上有2个警告:

FutureWarning:整数数据的处理将在 0.22 版本中发生变化。目前,类别是根据范围 [0, max(values)] 确定的,而将来它们将根据唯一值确定。如果您想要未来的行为并消除此警告,您可以指定“categories='auto'”。如果您在此 OneHotEncoder 之前使用 LabelEncoder 将类别转换为整数,那么您现在可以直接使用 OneHotEncoder。

第二个:

'categorical_features' 关键字在 0.20 版中已弃用,并将在 0.22 版中删除。您可以改用 ColumnTransformer。
“改用 ColumnTransformer。”,弃用警告)

以后不要直接在 OneHotEncoder 中定义列,除非你想使用“categories='auto'”。第一条消息还告诉您直接使用 OneHotEncoder,而不是先使用 LabelEncoder。最后,第二条消息告诉您使用 ColumnTransformer,它类似于用于列转换的管道。

这是您案例的等效代码:

from sklearn.compose import ColumnTransformer 
ct = ColumnTransformer([("Name_Of_Your_Step", OneHotEncoder(),[0])], remainder="passthrough")) # The last arg ([0]) is the list of columns you want to transform in this step
ct.fit_transform(X)    

另请参阅:ColumnTransformer 文档

对于上面的例子;

编码分类数据(基本上将文本更改为数字数据,即国家名称)

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
#Encode Country Column
labelencoder_X = LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])
ct = ColumnTransformer([("Country", OneHotEncoder(), [0])], remainder = 'passthrough')
X = ct.fit_transform(X)

推荐阅读