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.
说明: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}
文件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']