我想对该列表进行一次热编码:
[0 0 1 1 1 2 2 2 4 4]
当我这样做时,一键编码器将我的4转换为3。也就是说,我得到了:
(0, 0) 1.0
(1, 0) 1.0
(2, 0) 1.0
(3, 1) 1.0
(4, 1) 1.0
(5, 1) 1.0
(6, 2) 1.0
(7, 2) 1.0
(8, 2) 1.0
(9, 3) 1.0
我想要这个(注意最后一行已更改):
(0, 0) 1.0
(1, 0) 1.0
(2, 0) 1.0
(3, 1) 1.0
(4, 1) 1.0
(5, 1) 1.0
(6, 2) 1.0
(7, 2) 1.0
(8, 2) 1.0
(9, 4) 1.0
完整的MWE:
import numpy as np
from sklearn.preprocessing import OneHotEncoder
idvals = [0, 0, 0, 1, 1, 1, 2, 2, 2, 4]
hot = OneHotEncoder()
h1 = hot.fit_transform(np.asarray(idvals).reshape(10, 1))
print(np.asarray(h1))
使用Python 2.7.14 | Anaconda自定义(64位)| (默认值,2017年12月7日,17:05:42)
如何获得最后一行是(9,4)而不是(9,3)?
3
不是值,只是坐标:
h1.todense()
matrix([[1., 0., 0., 0.],
[1., 0., 0., 0.],
[1., 0., 0., 0.],
[0., 1., 0., 0.],
[0., 1., 0., 0.],
[0., 1., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 1., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]])
h1
是稀疏矩阵:
<10x4 sparse matrix of type '<class 'numpy.float64'>'
with 10 stored elements in Compressed Sparse Row format>
并且在打印时,会同时获得以坐标指定的值的索引和值