機器學習-Sklearn之DictVectorizer函數學習
函數介紹
sklearn.featture_extraction.DictVectorizer:
將特徵與值的映射字典組成的列表轉換成向量。
DictVectorizer通過使用scikit-learn的estimators,將特徵名稱與特徵值組成的映射字典構成的列表轉換成Numpy數組或者Scipy.sparse矩陣。
當特徵的值是字符串時,這個轉換器將進行一個二進制One-hot編碼。One-hot編碼是將特徵所有可能的字符串值構造成布爾型值。例如: 特徵f有一個值ham,一個值spam,轉換後會變成兩個特徵f=ham和f=spam。
注意,轉換器只會將字符串形式的特徵值轉換成One-hot編碼,數值型的不會轉換。
一個字典中樣本沒有的特徵在結果矩陣中的值是0.
例子1
說明:DictVectorizer的處理對象是符號化(非數字化)的但是具有一定結構的特徵數據,如字典等,將符號轉成數字0/1表示
# 定義一組字典列表,用來表示多個數據樣本(每個字典代表一個數據樣本)
measurements = [{'city': 'Beijing', 'temperature': 33.}, {'city': 'London', 'temperature': 12.},
{'city': 'San Fransisco', 'temperature': 18.}]
vec = sklearn.feature_extraction.DictVectorizer(sparse=False)
# 輸出轉化後的特徵矩陣
array = vec.fit_transform(measurements)
print(type(array))
print(array)
# 輸出各個維度的特徵含義
print(vec.get_feature_names())
print(vec.vocabulary_)
執行結果
<class 'numpy.ndarray'>
[[ 1. 0. 0. 33.]
[ 0. 1. 0. 12.]
[ 0. 0. 1. 18.]]
['city=Beijing', 'city=London', 'city=San Fransisco', 'temperature']
{'city=Beijing': 0, 'temperature': 3, 'city=London': 1, 'city=San Fransisco': 2}
原表形式
轉換後形式
例子2 - 文件中讀數據
文件data/laic.csv
spring,no,breeze,yes
winter,no,no wind,yes
autumn,yes,breeze,yes
winter,no,no wind,yes
summer,no,breeze,yes
winter,yes,breeze,yes
winter,no,gale,yes
winter,no,no wind,yes
spring,yes,no wind,no
summer,yes,gale,no
summer,no,gale,no
autumn,yes,breeze,no
說明 : 真正在實踐上的時候大部分都是load文件,然後轉換成特徵。下面就是這個例子。
從文件中讀數據,轉換特徵
import pandas as pd
from sklearn import tree
from sklearn.model_selection import train_test_split
# pandas 讀取 csv 文件,header = None 表示不將首行作爲列
data = pd.read_csv('data/laic.csv', header=None)
# 指定列
data.columns = ['season', 'after 8', 'wind', 'lay bed']
# sparse=False意思是不產生稀疏矩陣
vec = sklearn.feature_extraction.DictVectorizer(sparse=False)
# 先用 pandas 對每行生成字典,然後進行向量化
feature = data[['season', 'after 8', 'wind']]
X_train = vec.fit_transform(feature.to_dict(orient='record'))
# 打印各個變量
print('show feature\n', feature)
print('show vector\n', X_train)
print('show vector name\n', vec.get_feature_names())
執行結果
show feature
season after 8 wind
0 spring no breeze
1 winter no no wind
2 autumn yes breeze
3 winter no no wind
4 summer no breeze
5 winter yes breeze
6 winter no gale
7 winter no no wind
8 spring yes no wind
9 summer yes gale
10 summer no gale
11 autumn yes breeze
show vector
[[1. 0. 0. 1. 0. 0. 1. 0. 0.]
[1. 0. 0. 0. 0. 1. 0. 0. 1.]
[0. 1. 1. 0. 0. 0. 1. 0. 0.]
[1. 0. 0. 0. 0. 1. 0. 0. 1.]
[1. 0. 0. 0. 1. 0. 1. 0. 0.]
[0. 1. 0. 0. 0. 1. 1. 0. 0.]
[1. 0. 0. 0. 0. 1. 0. 1. 0.]
[1. 0. 0. 0. 0. 1. 0. 0. 1.]
[0. 1. 0. 1. 0. 0. 0. 0. 1.]
[0. 1. 0. 0. 1. 0. 0. 1. 0.]
[1. 0. 0. 0. 1. 0. 0. 1. 0.]
[0. 1. 1. 0. 0. 0. 1. 0. 0.]]
show vector name
['after 8=no', 'after 8=yes', 'season=autumn', 'season=spring', 'season=summer', 'season=winter', 'wind=breeze', 'wind=gale', 'wind=no wind']