Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python机器学习中的一个热编码错误_Python_Machine Learning_One Hot Encoding - Fatal编程技术网

python机器学习中的一个热编码错误

python机器学习中的一个热编码错误,python,machine-learning,one-hot-encoding,Python,Machine Learning,One Hot Encoding,我在机器学习中使用分类变量。以下是我的数据示例: age,gender,height,class,label 25,m,43,A,0 35,f,45,B,1 12,m,36,C,0 14,f,42,A,0 有两个分类变量性别和身高。我使用了标签编码技术 age,gender,height,class,label 25,m,43,A,0 35,f,45,B,1 12,m,36,C,0 14,f,42,A,0 我的代码: age,gender,height,class,label 25,m,43

我在机器学习中使用分类变量。以下是我的数据示例:

age,gender,height,class,label
25,m,43,A,0
35,f,45,B,1
12,m,36,C,0
14,f,42,A,0
有两个分类变量性别和身高。我使用了标签编码技术

age,gender,height,class,label
25,m,43,A,0
35,f,45,B,1
12,m,36,C,0
14,f,42,A,0
我的代码:

age,gender,height,class,label
25,m,43,A,0
35,f,45,B,1
12,m,36,C,0
14,f,42,A,0
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder,OneHotEncoder

df=pd.read_csv('test.csv')

X=df.drop(['label'],1)
y=np.array(df['label'])

data=X.iloc[:,:].values

lben = LabelEncoder()
data[:,1] = lben.fit_transform(data[:,1])
data[:,3] = lben.fit_transform(data[:,3])

onehotencoder = OneHotEncoder(categorical_features=[1])
data = onehotencoder.fit_transform(data).toarray()

onehotencoder = OneHotEncoder(categorical_features=[3])
data = onehotencoder.fit_transform(data).toarray()

print(data.shape)

np.savetxt('data.csv',data,fmt='%s')    
data.csv如下所示:

age,gender,height,class,label
25,m,43,A,0
35,f,45,B,1
12,m,36,C,0
14,f,42,A,0
0.0 0.0 1.0 0.0 0.0 1.0 25.0 0.0
0.0 0.0 0.0 1.0 1.0 0.0 35.0 1.0
1.0 0.0 0.0 0.0 0.0 1.0 12.0 2.0
0.0 1.0 0.0 0.0 1.0 0.0 14.0 0.0

我无法理解为什么列是这样的,即“height”列的值在哪里。此外,data.shape是(4,8)而不是(4,7),即(性别由2列表示,class由3表示,以及“age”和“height”特征。

您确定需要使用
LabelEncoder+OneHotEncoder
吗?有一种更简单的方法(这不允许进行高级程序,但到目前为止,您似乎在进行基础工作):

age,gender,height,class,label
25,m,43,A,0
35,f,45,B,1
12,m,36,C,0
14,f,42,A,0

当前代码的问题是,在完成第一个OHE之后:

age,gender,height,class,label
25,m,43,A,0
35,f,45,B,1
12,m,36,C,0
14,f,42,A,0
onehotencoder = OneHotEncoder(categorical_features=[1])
data = onehotencoder.fit_transform(data).toarray()
列被移动,列3实际上是原始的
高度
列,而不是标签编码的
列。因此,将第二列更改为使用列4,您将获得所需的内容

age,gender,height,class,label
25,m,43,A,0
35,f,45,B,1
12,m,36,C,0
14,f,42,A,0