为下面这段代码的预测结果加上可视化功能,要能够看到每个预测数据的结果的准确度:from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB import jieba from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt good_comments = [] bad_comments = [] with open('D:\PyCharmProjects\爬虫测试\好评.txt', 'r', encoding='gbk') as f: for line in f.readlines(): good_comments.append(line.strip('\n')) with open('D:\PyCharmProjects\爬虫测试\差评.txt', 'r', encoding='gbk') as f: for line in f.readlines(): bad_comments.append(line.strip('\n')) with open('StopWords.txt', 'r', encoding='utf-8') as f: stopwords = f.read().splitlines() good_words = [] for line in good_comments: words = jieba.cut(line, cut_all=False) words = [w for w in words if w not in stopwords] good_words.append(' '.join(words)) bad_words = [] for line in bad_comments: words = jieba.cut(line, cut_all=False) words = [w for w in words if w not in stopwords] bad_words.append(' '.join(words)) # 将文本转换为向量 vectorizer = CountVectorizer() X = vectorizer.fit_transform(good_words + bad_words) y = [1] * len(good_words) + [0] * len(bad_words) # 将数据分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) # 训练模型 clf = MultinomialNB() clf.fit(X_train, y_train) # 测试模型并计算准确率 pred = clf.predict(X_test) accuracy = sum(pred == y_test) / len(y_test) print('准确率:{:.2%}'.format(accuracy)) # 预测新数据的类别 with open('测试评论.txt', 'r', encoding='utf-8') as f: count = 0 for line in f.readlines(): count += 1 test_text = line.strip('\n') test_words = ' '.join(jieba.cut(test_text, cut_all=False)) test_vec = vectorizer.transform([test_words]) pred = clf.predict(test_vec) if pred[0] == 1: print(count, '好评') else: print(count, '差评')
时间: 2024-02-01 20:02:23 浏览: 86
以下是加上可视化功能的代码,通过图表的形式展示每个预测数据的结果的准确度:
```python
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
import jieba
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
# 读取数据
good_comments = []
bad_comments = []
with open('D:\PyCharmProjects\爬虫测试\好评.txt', 'r', encoding='gbk') as f:
for line in f.readlines():
good_comments.append(line.strip('\n'))
with open('D:\PyCharmProjects\爬虫测试\差评.txt', 'r', encoding='gbk') as f:
for line in f.readlines():
bad_comments.append(line.strip('\n'))
# 加载停用词
with open('StopWords.txt', 'r', encoding='utf-8') as f:
stopwords = f.read().splitlines()
# 对评论进行分词
good_words = []
for line in good_comments:
words = jieba.cut(line, cut_all=False)
words = [w for w in words if w not in stopwords]
good_words.append(' '.join(words))
bad_words = []
for line in bad_comments:
words = jieba.cut(line, cut_all=False)
words = [w for w in words if w not in stopwords]
bad_words.append(' '.join(words))
# 将文本转换为向量
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(good_words + bad_words)
y = [1] * len(good_words) + [0] * len(bad_words)
# 将数据分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# 训练模型
clf = MultinomialNB()
clf.fit(X_train, y_train)
# 测试模型并计算准确率
pred = clf.predict(X_test)
accuracy = sum(pred == y_test) / len(y_test)
print('准确率:{:.2%}'.format(accuracy))
# 预测新数据的类别
with open('测试评论.txt', 'r', encoding='utf-8') as f:
count = 0
results = []
for line in f.readlines():
count += 1
test_text = line.strip('\n')
test_words = ' '.join(jieba.cut(test_text, cut_all=False))
test_vec = vectorizer.transform([test_words])
pred = clf.predict(test_vec)
if pred[0] == 1:
results.append(('好评', 1))
else:
results.append(('差评', 0))
# 可视化预测结果准确度
y_test = np.array(y_test)
pred = np.array(pred)
fig, ax = plt.subplots()
ax.scatter(np.arange(len(y_test)), y_test, label='True Label')
ax.scatter(np.arange(len(pred)), pred, label='Predicted Label')
ax.set_xlabel('Sample Index')
ax.set_ylabel('Label')
ax.legend()
plt.show()
```
运行后,会展示出一个图表,其中横坐标表示样本的索引,纵坐标表示样本的标签。绿色点表示预测结果,蓝色点表示真实结果。可以通过比较两者的位置和颜色,来判断预测的准确率和错误率。
阅读全文