CountVectorizer
该类是将文本词转换为词频矩阵的形式。比如“I am a teacher”文本共包含四个单词,它们对应单词的词频均为1,“I”、“am”、“a”、“teacher”分别出现一次。CountVectorizer将生成一个矩阵 a[M][N],共M个文本语料,N个单词,比如a[i][j]表示单词j在i类文本下的词频。再调用fit_transform()函数计算各个词语出现的次数,get_feature_names()函数获取词库中的所有文本关键词。
P
r
e
c
i
s
i
o
n
=
正
确
被
预
测
的
总
数
预
测
出
的
分
类
总
数
P
r
e
c
i
s
i
o
n
=
预
测
出
的
分
类
总
数
正
确
被
预
测
的
总
数
R
e
c
a
l
l
=
正
确
被
预
测
的
总
数
测
试
集
中
存
在
的
分
类
总
数
R
e
c
a
l
l
=
测
试
集
中
存
在
的
分
类
总
数
正
确
被
预
测
的
总
数
F
−
m
e
a
s
u
r
e
=
2
∗
P
r
e
c
i
s
i
o
n
∗
R
e
c
a
l
l
(
P
r
e
c
i
s
i
o
n
+
R
e
c
a
l
l
)
F
−
m
e
a
s
u
r
e
=
(
P
r
e
c
i
s
i
o
n
+
R
e
c
a
l
l
)
2
∗
P
r
e
c
i
s
i
o
n
∗
R
e
c
a
l
l
由于本文主要针对2分类问题,其实验评估主要分为0和1两类,完整代码如下:
# -*- coding:utf-8 -*-import csv
import pandas as pd
import numpy as np
import jieba
import jieba.analyse
from scipy.sparse import coo_matrix
from sklearn import feature_extraction
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn import svm
from sklearn import neighbors
from sklearn.naive_bayes import MultinomialNB
#----------------------------------第一步 读取文件--------------------------------withopen('fenci_data.csv','r', encoding='UTF-8')as f:
reader = csv.DictReader(f)
labels =[]
contents =[]for row in reader:
labels.append(row['label'])#0-好评 1-差评
contents.append(row['content'])print(labels[:5])print(contents[:5])#----------------------------------第二步 数据预处理--------------------------------#将文本中的词语转换为词频矩阵 矩阵元素a[i][j] 表示j词在i类文本下的词频
vectorizer = CountVectorizer(min_df=5)#该类会统计每个词语的tf-idf权值
transformer = TfidfTransformer()#第一个fit_transform是计算tf-idf 第二个fit_transform是将文本转为词频矩阵
tfidf = transformer.fit_transform(vectorizer.fit_transform(contents))for n in tfidf[:5]:print(n)print(type(tfidf))# 获取词袋模型中的所有词语
word = vectorizer.get_feature_names()for n in word[:10]:print(n)print("单词数量:",len(word))#将tf-idf矩阵抽取出来,元素w[i][j]表示j词在i类文本中的tf-idf权重#X = tfidf.toarray()
X = coo_matrix(tfidf, dtype=np.float32).toarray()#稀疏矩阵 注意floatprint(X.shape)print(X[:10])#----------------------------------第三步 数据划分--------------------------------#使用 train_test_split 分割 X y 列表
X_train, X_test, y_train, y_test = train_test_split(X,
labels,
test_size=0.3,
random_state=1)#--------------------------------第四步 机器学习分类--------------------------------# 逻辑回归分类方法模型
LR = LogisticRegression(solver='liblinear')
LR.fit(X_train, y_train)print('模型的准确度:{}'.format(LR.score(X_test, y_test)))
pre = LR.predict(X_test)print("逻辑回归分类")print(len(pre),len(y_test))print(classification_report(y_test, pre))#----------------------------------第五步 评价结果--------------------------------defclassification_pj(name, y_test, pre):print("算法评价:", name)# 正确率 Precision = 正确识别的个体总数 / 识别出的个体总数# 召回率 Recall = 正确识别的个体总数 / 测试集中存在的个体总数# F值 F-measure = 正确率 * 召回率 * 2 / (正确率 + 召回率)
YC_B, YC_G =0,0#预测 bad good
ZQ_B, ZQ_G =0,0#正确
CZ_B, CZ_G =0,0#存在#0-good 1-bad 同时计算防止类标变化
i =0while i<len(pre):
z =int(y_test[i])#真实
y =int(pre[i])#预测if z==0:
CZ_G +=1else:
CZ_B +=1if y==0:
YC_G +=1else:
YC_B +=1if z==y and z==0and y==0:
ZQ_G +=1elif z==y and z==1and y==1:
ZQ_B +=1
i = i +1print(ZQ_B, ZQ_G, YC_B, YC_G, CZ_B, CZ_G)print("")# 结果输出
P_G = ZQ_G *1.0/ YC_G
P_B = ZQ_B *1.0/ YC_B
print("Precision Good 0:", P_G)print("Precision Bad 1:", P_B)
R_G = ZQ_G *1.0/ CZ_G
R_B = ZQ_B *1.0/ CZ_B
print("Recall Good 0:", R_G)print("Recall Bad 1:", R_B)
F_G =2* P_G * R_G /(P_G + R_G)
F_B =2* P_B * R_B /(P_B + R_B)print("F-measure Good 0:", F_G)print("F-measure Bad 1:", F_B)#函数调用
classification_pj("LogisticRegression", y_test, pre)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
输出结果如下:
逻辑回归分类
18231823
precision recall f1-score support
00.940.990.97152010.930.700.80303
accuracy 0.941823
macro avg 0.940.850.881823
weighted avg 0.940.940.941823
算法评价: LogisticRegression
213150422915943031520
Precision Good 0:0.9435382685069009
Precision Bad 1:0.9301310043668122
Recall Good 0:0.9894736842105263
Recall Bad 1:0.7029702970297029
F-measure Good 0:0.9659601798330122
F-measure Bad 1:0.800751879699248