赞
踩
本案例提供了一个13条商品评价的小型数据集,通过对商品评价内容的分析,判断该评论是好评还是差评。
获取数据集:https://pan.baidu.com/s/1zbHsjpzusmyT5QkNWOu2gw?pwd=aune
首先需要导入本案例需要的包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import jieba
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
data = pd.read_csv("./Data/EmotionAnalysis/书籍评价.csv",encoding="gbk")
data.head()
(1)将目标值转换为数字
data.loc[:,"评价"]=="好评"
# df.loc[:,新列名]=值,添加新列
data.loc[data.loc[:,"评价"]=="好评","评论标号"]=1
data.loc[data.loc[:,"评价"]=="差评","评论标号"]=0
data.head()
(2)加载停用词表
stopwords=[]
with open("./Data/EmotionAnalysis/stopwords.txt",encoding="utf-8") as f:
lines = f.readlines()
# print(lines)
for i in lines:
line = i.strip()
# print(line)
stopwords.append(line)
# 对停用词列表去重
stopwords = list(set(stopwords))
(3) 把“内容”列处理,转化成标准格式
content = data["内容"]
comment_list = []
for i in content:
# print(i)
seg_list = jieba.cut(i)
# print(seg_list)
seg_str = ','.join(seg_list)
# print(seg_str)
comment_list.append(seg_str)
print(comment_list)
(4)统计词的个数
con = CountVectorizer(stop_words=stopwords)
# 通过 fit_transform 函数计算各个词语出现的次数
X = con.fit_transform(comment_list)
# 通过 get_feature_names()可获取词袋中所有文本的关键字
name = con.get_feature_names()
print(X.toarray()) # 通过 toarray()可看到词频矩阵的结果
print(name)
(5)准备训练集和测试集
# 准备训练集 这里将文本前10行当做训练集 后3行当做测试集
x_train = X.toarray()[:10, :]
y_train = data["评价"][:10]
# 准备测试集
x_text = X.toarray()[10:, :]
y_text = data["评价"][10:]
# 构建贝叶斯算法分类器
mb = MultinomialNB(alpha=1) # alpha 为可选项,默认 1.0,添加拉普拉修/Lidstone 平滑参数
# 训练数据
mb.fit(x_train, y_train)
# 预测数据
y_predict = mb.predict(x_text)
#预测值与真实值展示
print('预测值:',y_predict)
print('真实值:',y_text)
mb.score(x_text, y_text) # 1.0
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。