1. 需求分析
根据评论语,判断评论是好评还是差评
2. 数据说明
书籍评价数据:
| 内容 | 评价 |
| 从编程小白的角度看,入门极佳。 | 好评 |
| 很好的入门书,简洁全面,适合小白。 | 好评 |
| 讲解全面,许多小细节都有顾及,三个小项目受益匪浅。 | 好评 |
| 前半部分讲概念深入浅出,要言不烦,很赞 | 好评 |
| 看了一遍还是不会写,有个概念而已 | 差评 |
| 中规中矩的教科书,零基础的看了依旧看不懂 | 差评 |
| 内容太浅显,个人认为不适合有其它语言编程基础的人 | 差评 |
| 破书一本 | 差评 |
| 适合完完全全的小白读,有其他语言经验的可以去看别的书 | 差评 |
| 基础知识写的挺好的! | 好评 |
| 太基础 | 差评 |
| 略_嗦。。适合完全没有编程经验的小白 | 差评 |
| 真的真的不建议买 | 差评 |
停用词数据:
3. 建模
import jieba
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import classification_report, roc_curve, auc
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
3.1 加载数据
# 1. 加载书籍
# 1.1 书籍评价数据
data = pd.read_csv('./data/书籍评价.csv', encoding='gbk', index_col=0)
data.head()
# 1.2 停用词列表
with open('./data/stopwords.txt', 'r', encoding='utf-8') as f:
stop_words_list = f.readlines() # 读取所有行
stop_words_list = [line.strip() for line in stop_words_list] # 去除换行符
stop_words_list = list(set(stop_words_list)) # 去重
stop_words_list[:10]
3.2 数据预处理
# 2. 数据预处理
# 2.1 评价标签转换
data['label'] = data['评价'].map({'好评': 1, '差评': 0})
y = data['label']
# 2.2 jieba分词
comment_list = [','.join(jieba.lcut(line)) for line in data['内容'].values]
comment_list[:5]
# 2.3 剔除停用词
transfer = CountVectorizer(stop_words=stop_words_list)
x = transfer.fit_transform(comment_list).toarray() # 每条评论的切词分布,有就是1,没有就是0,每条转换后以列表形式保存
print(x[0])
print(len(transfer.get_feature_names_out())) # 解释:词袋模型中,最终有多少个词
# 2.4 划分数据集
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0, stratify=y)
# len(x_train)
3.3 特征工程(不需要)
3.4 模型训练
# 4. 模型训练
estimator = MultinomialNB() # 多项式贝叶斯
estimator.fit(x_train, y_train)
y_pre = estimator.predict(x_test)
3.5 模型评估
# 5. 模型评估
print('分类报告:', classification_report(y_test, y_pre))
# 可视化
fpr, tpr, thresholds = roc_curve(y_test, estimator.predict_proba(x_test)[:,1])
auc_value = auc(fpr, tpr)
plt.figure(figsize=(3,3))
plt.plot(fpr, tpr, label='AUC = %.2f' % auc_value)
plt.plot([0,1], [0,1], 'r–')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend()
plt.show()
网硕互联帮助中心


评论前必须登录!
注册