forked from sheldonresearch/chinese_text_classification
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNBayes_Predict.py
45 lines (33 loc) · 1.41 KB
/
NBayes_Predict.py
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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@version: python3.6
@author: XiangguoSun
@contact: [email protected]
@file: NBayes_Predict.py
@time: 2018/1/23 16:12
@software: PyCharm
"""
from sklearn.naive_bayes import MultinomialNB # 导入多项式贝叶斯算法
from sklearn import metrics
from Tools import readbunchobj
# 导入训练集
trainpath = "train_word_bag/tfdifspace.dat"
train_set = readbunchobj(trainpath)
# 导入测试集
testpath = "test_word_bag/testspace.dat"
test_set = readbunchobj(testpath)
# 训练分类器:输入词袋向量和分类标签,alpha:0.001 alpha越小,迭代次数越多,精度越高
clf = MultinomialNB(alpha=0.001).fit(train_set.tdm, train_set.label)
# 预测分类结果
predicted = clf.predict(test_set.tdm)
for flabel, file_name, expct_cate in zip(test_set.label, test_set.filenames, predicted):
if flabel != expct_cate:
print(file_name, ": 实际类别:", flabel, " -->预测类别:", expct_cate)
print("预测完毕!!!")
# 计算分类精度:
def metrics_result(actual, predict):
print('精度:{0:.3f}'.format(metrics.precision_score(actual, predict, average='weighted')))
print('召回:{0:0.3f}'.format(metrics.recall_score(actual, predict, average='weighted')))
print('f1-score:{0:.3f}'.format(metrics.f1_score(actual, predict, average='weighted')))
metrics_result(test_set.label, predicted)