『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排序。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM