02-朴素贝叶斯-书籍评论情感分析预测

📅 2026/7/21 5:56:41
02-朴素贝叶斯-书籍评论情感分析预测
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 MultinomialNB3.1 加载数据# 1. 加载书籍 # 1.1 书籍评价数据 data pd.read_csv(./data/书籍评价.csv, encodinggbk, index_col0) data.head() # 1.2 停用词列表 with open(./data/stopwords.txt, r, encodingutf-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_wordsstop_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_size0.2, random_state0, stratifyy) # 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, labelAUC %.2f % auc_value) plt.plot([0,1], [0,1], r--) plt.xlabel(False Positive Rate) plt.ylabel(True Positive Rate) plt.legend() plt.show()