记录一下独热编码,如果需要用到的话,只需改变Train_Y,其为1维数组
注:以下实验基于jupyter notebook编辑器
# 实验1
先试一组顺序数组 [0, 1 ,2 , 3, 4, 5]
from sklearn import preprocessing #导入包
Train_Y = [0, 1, 2, 3, 4, 5] #换成你想要的数组
Train_Y = np.array(Train_Y).reshape([-1, 1])
Encoder = preprocessing.OneHotEncoder()
Encoder.fit(Train_Y)
Train_Y = Encoder.transform(Train_Y).toarray()
Train_Y = np.asarray(Train_Y, dtype=np.int32)
>>>Train_Y
array([[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1]])
# 实验2
0和4有两个,且在0-2处缺个1,不是连续的
Train_Y = [0, 2, 0, 3, 4, 5, 4]
Train_Y = np.array(Train_Y).reshape([-1, 1])
Encoder = preprocessing.OneHotEncoder()
Encoder.fit(Train_Y)
Train_Y = Encoder.transform(Train_Y).toarray()
Train_Y = np.asarray(Train_Y, dtype=np.int32)
print(Train_Y)
print(Train_Y.shape)
>>>输出结果
[[1 0 0 0 0]
[0 1 0 0 0]
[1 0 0 0 0]
[0 0 1 0 0]
[0 0 0 1 0]
[0 0 0 0 1]
[0 0 0 1 0]]
(7, 5)
从结果可以看出,
独热编码,是给几个数就转码几个数;
# 实验3
5在4和3前面
Train_Y = [0, 2, 0, 5, 4, 3]
Train_Y = np.array(Train_Y).reshape([-1, 1])
Encoder = preprocessing.OneHotEncoder()
Encoder.fit(Train_Y)
Train_Y = Encoder.transform(Train_Y).toarray()
Train_Y = np.asarray(Train_Y, dtype=np.int32)
print(Train_Y)
print(Train_Y.shape)
>>>输出结果
[[1 0 0 0 0]
[0 1 0 0 0]
[1 0 0 0 0]
[0 0 0 0 1]
[0 0 0 1 0]
[0 0 1 0 0]]
(6, 5)
从结果来看,独热编码是先排序,再进行编码。而不是按照出现的顺序来编码