『Sklearn』特征向量化处理
『Kaggle』分类任务_决策树&集成模型&DataFrame向量化操作
1
2
3
4
5
6
7
8
9
|
'''特征提取器''' from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer(sparse = False ) print (X_train.to_dict(orient = 'record' )) X_train = vec.fit_transform(X_train.to_dict(orient = 'record' )) print (X_train) print (vec.feature_names_) X_test = vec.transform(X_test.to_dict(orient = 'record' )) |
涉及两个操作,
- DataFrame字典化
- 字典向量化
1.DataFrame字典化
1
2
3
4
5
6
7
8
9
10
|
import numpy as np import pandas as pd index = [ 'x' , 'y' ] columns = [ 'a' , 'b' , 'c' ] dtype = [( 'a' , 'int32' ), ( 'b' , 'float32' ), ( 'c' , 'float32' )] values = np.zeros( 2 , dtype = dtype) df = pd.DataFrame(values, index = index) df.to_dict(orient = 'record' ) |
2.字典向量化
DictVectorizer: 将dict类型的list数据,转换成numpy array,具有属性vec.feature_names_,查看提取后的特征名。
具体效果如下,
>>> from sklearn.feature_extraction import DictVectorizer
>>> v = DictVectorizer(sparse=False)
>>> D = [{'foo': 1, 'bar': 2}, {'foo': 3, 'baz': 1}]
>>> X = v.fit_transform(D)
>>> X
array([[ 2., 0., 1.],
[ 0., 1., 3.]])
>>> v.transform({'foo': 4, 'unseen_feature': 3})
array([[ 0., 0., 4.]])
数字的特征不变,没有该特征的项给赋0,对于未参与训练的特征不予考虑。
对应到本程序,
print(X_train.to_dict(orient='record')):
[{'sex': 'male', 'pclass': '3rd', 'age': 31.19418104265403},
...... ....... ....... ......
{'sex': 'female', 'pclass': '1st', 'age': 31.19418104265403}]
提取特征,
X_train = vec.fit_transform(X_train.to_dict(orient='record'))
print(X_train):[[ 31.19418104 0. 0. 1. 0. 1. ]
[ 31.19418104 1. 0. 0. 1. 0. ]
[ 31.19418104 0. 0. 1. 0. 1. ]
...,
[ 12. 0. 1. 0. 1. 0. ]
[ 18. 0. 1. 0. 0. 1. ]
[ 31.19418104 0. 0. 1. 1. 0. ]]
数字的年龄没有改变,其他obj特征变成了onehot编码的特征,各列意义可以查看的,
print(vec.feature_names_):
['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male']
一个直观例子:
v = DictVectorizer(sparse=False)
v.fit_transform([{'a':1},{'a':2},{'a':3}])
Out[7]:
array([[ 1.],
[ 2.],
[ 3.]])
v.feature_names_
Out[8]:
['a']
v.fit_transform([{'a':'1'},{'a':'2'},{'a':'3'}])
Out[9]:
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
v.feature_names_
Out[10]:
['a=1', 'a=2', 'a=3']
注意,v.feature_names_输出顺序和v.fit_transform()生成顺序是一一对应的,
v.fit_transform([{'a':'2q'},{'a':'1v'},{'a':'3t'},{'a':'3t'}])
Out[17]:
array([[ 0., 1., 0.],
[ 1., 0., 0.],
[ 0., 0., 1.],
[ 0., 0., 1.]])
v.feature_names_
Out[18]:
['a=1v', 'a=2q', 'a=3t']然后,
np.argmax(np.array([[ 0., 1., 0.],
[ 1., 0., 0.],
[ 0., 0., 1.],
[ 0., 0., 1.]]),axis=1)
Out[19]:
array([1, 0, 2, 2])
进一步的,也就是说v.feature_names_输出顺序对应于v.fit_transform()的非onehot排序。