为下面这段代码的预测结果加上可视化功能,要能够看到预测结果的准确度: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 14:02:18 浏览: 78
Transformer模型实现长期预测并可视化结果(附代码+数据集+原理介绍)
5星 · 资源好评率100%
以下是加上可视化功能的代码,可以通过准确率的条形图来观察预测结果的准确度:
```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))
# 可视化准确率结果
fig, ax = plt.subplots()
ax.bar(['Accuracy'], [accuracy])
ax.set_ylim([0, 1])
ax.set_ylabel('Accuracy')
ax.set_title('Prediction Accuracy')
plt.show()
# 预测新数据的类别
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, '差评')
```
运行以上代码,可以得到一个显示准确率的条形图。如果准确率很高,则条形图的高度会接近 $1$,反之则会较低。
阅读全文