您的位置:首页 > 其它

sklearn preprocessing 数据预处理(OneHotEncoder)

2017-06-28 16:51 429 查看


1. one hot encoder

sklearn.preprocessing.OneHotEncoder

one hot encoder 不仅对 label 可以进行编码,还可对 categorical feature 进行编码:
>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder()

>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])

>>> enc.n_values_
array([2, 3, 4])

>>> enc.feature_indices_
array([0, 2, 5, 9])

>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])
1
2
3
4
5
6
7
8
9
10
11
12
13
1
2
3
4
5
6
7
8
9
10
11
12
13

为 OneHotEncoder 类传递进来的数据集:
[[0, 0, 3],
[1, 1, 0],
[0, 2, 1],
[1, 0, 2]]
1
2
3
4
1
2
3
4

每一列代表一个属性,fit 操作之后:
对象
enc
n_values_
成员变量,记录着每一个属性的最大取值数目,如本例第一个属性:
0,
1, 0, 1
 ⇒ 2,
0, 1, 2, 0
 ⇒ 3,
3,
0, 1, 2
 ⇒ 
4
; 
即各个属性(feature)在 one hot 编码下占据的位数;

对象 
enc
 的 
feature_indices_
,则记录着属性在新
One hot 编码下的索引位置, 
feature_indices_ 是对 n_values_ 的累积值,不过 feature_indices 的首位是 0;

进一步通过 fit 好的 one hot encoder 对新来的特征向量进行编码:
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])
1
2
1
2
前 2 位 1, 0,对 0 进行编码
中间 3 位 0, 1, 0 对 1 进行编码;
末尾 4 位 0, 1, 0, 0 对 1 进行编码;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: