1. 文本特征抽取
CountVectorizer()函数用来统计词语出现的次数。下面看一个例子
原文地址
from sklearn.feature_extraction.text import CountVectorizer
texts=["dog cat fish","dog cat cat","fish bird", 'bird'] # “dog cat fish” 为输入列表元素,即代表一个文章的字符串
cv = CountVectorizer()#创建词袋数据结构
cv_fit=cv.fit_transform(texts)
#上述代码等价于下面两行
#cv.fit(texts)
#cv_fit=cv.transform(texts)
print(cv.get_feature_names()) #['bird', 'cat', 'dog', 'fish'] 列表形式呈现文章生成的词典
print(cv.vocabulary_ ) # {‘dog’:2,'cat':1,'fish':3,'bird':0} 字典形式呈现,key:词,value:词频
print(cv_fit)
# (0,3) 1 第0个列表元素,**词典中索引为3的元素**, 词频
#(0,1)1
#(0,2)1
#(1,1)2
#(1,2)1
#(2,0)1
#(2,3)1
#(3,0)1
print(cv_fit.toarray()) #.toarray() 是将结果转化为稀疏矩阵矩阵的表示方式;
#[[0 1 1 1]
# [0 2 1 0]
# [1 0 0 1]
# [1 0 0 0]]
print(cv_fit.toarray().sum(axis=0)) #每个词在所有文档中的词频
#[2 3 2 2]
TfidfVectorizer()基于tf-idf算法。此算法包括两部分tf和idf,两者相乘得到tf-idf算法。下面看一个例子
原文地址
from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer
texts=["orange banana apple grape","banana apple apple","grape", 'orange apple']
cv = TfidfVectorizer()
cv_fit=cv.fit_transform(texts)
print(cv.vocabulary_)
print(cv_fit)
print(cv_fit.toarray())
'''
输出如下:
{'orange': 3, 'banana': 1, 'apple': 0, 'grape': 2}
(0, 3) 0.5230350301866413
(0, 1) 0.5230350301866413
(0, 0) 0.423441934145613
(0, 2) 0.5230350301866413
(1, 1) 0.5254635733493682
(1, 0) 0.8508160982744233
(2, 2) 1.0
(3, 3) 0.7772211620785797
(3, 0) 0.6292275146695526
[[0.42344193 0.52303503 0.52303503 0.52303503]
[0.8508161 0.52546357 0. 0. ]
[0. 0. 1. 0. ]
[0.62922751 0. 0. 0.77722116]]
'''
需要注意的是,在处理中文文本的时候,需要先使用jieba库进行分词处理,具体操作可参考jieba库详解
2. 字典特征抽取
from sklearn.feature_extraction import DictVectorizer
'''
字典特征提取器:
将字典数据结构抽和向量化
类别类型特征借助原型特征名称采用0 1 二值方式进行向量化
数值类型特征保持不变
'''
# 定义一个字典列表 用来表示多个数据样本
measurements = [
{"city": "Dubai", "temperature": 33.0},
{"city": "London", "temperature": 12.0},
{"city": "San Fransisco", "temperature": 18.0},
]
# 初始化字典特征抽取器
vec = DictVectorizer()
data = vec.fit_transform(measurements).toarray()
# 查看提取后的特征值
print(data)
'''
[[ 1. 0. 0. 33.]
[ 0. 1. 0. 12.]
[ 0. 0. 1. 18.]]
'''
# 查看提取后特征的含义
print(vec.get_feature_names())
'''
['city=Dubai', 'city=London', 'city=San Fransisco', 'temperature']
'''