python 评论分析_python分析评论内容是积极的还是消极的(应用朴素做分词处理及情感识别)...

【实例简介】

1.应用朴素贝叶斯算法,对Content 数据集进行分类

1)对数据进行清洗

2)基于给定的词库和停止词,进行文本切词

3)建立NB模型

【实例截图】

python 评论分析_python分析评论内容是积极的还是消极的(应用朴素做分词处理及情感识别)..._第1张图片

python 评论分析_python分析评论内容是积极的还是消极的(应用朴素做分词处理及情感识别)..._第2张图片

python 评论分析_python分析评论内容是积极的还是消极的(应用朴素做分词处理及情感识别)..._第3张图片

【核心代码】

import pandas as pd

# 读入评论数据

evaluation = pd.read_excel(r'Contents.xlsx')

# 查看数据前10行

print(evaluation.head(10))

# 运用正则表达式,将评论中的数字和英文去除

evaluation.Content = evaluation.Content.str.replace('[0-9a-zA-Z]','')

evaluation.head()

# 导入第三方包

import jieba

# 加载自定义词库

jieba.load_userdict(r'all_words.txt')

# 读入停止词

with open(r'mystopwords.txt', encoding='UTF-8') as words:

stop_words = [i.strip() for i in words.readlines()]

# 构造切词的自定义函数,并在切词过程中删除停止词

def cut_word(sentence):

words = [i for i in jieba.lcut(sentence) if i not in stop_words]

# 切完的词用空格隔开

result = ' '.join(words)

return(result)

# 对评论内容进行批量切词

words = evaluation.Content.apply(cut_word)

# 前5行内容的切词效果

words[:5]

# 导入第三方包

from sklearn.feature_extraction.text import CountVectorizer

# 计算每个词在各评论内容中的次数,并将稀疏度为99%以上的词删除

counts = CountVectorizer(min_df = 0.01)

# 文档词条矩阵

dtm_counts = counts.fit_transform(words).toarray()

# 矩阵的列名称

columns = counts.get_feature_names()

# 将矩阵转换为数据框--即X变量

X = pd.DataFrame(dtm_counts, columns=columns)

# 情感标签变量

y = evaluation.Type

X.head()

from sklearn import model_selection

from sklearn import naive_bayes

from sklearn import metrics

import matplotlib.pyplot as plt

import seaborn as sns

# 将数据集拆分为训练集和测试集

X_train,X_test,y_train,y_test = model_selection.train_test_split(X,y,test_size = 0.25, random_state=1)

# 构建伯努利贝叶斯分类器

bnb = naive_bayes.BernoulliNB()

# 模型在训练数据集上的拟合

bnb.fit(X_train,y_train)

# 模型在测试数据集上的预测

bnb_pred = bnb.predict(X_test)

# 构建混淆矩阵

cm = pd.crosstab(bnb_pred,y_test)

# 绘制混淆矩阵图

sns.heatmap(cm, annot = True, cmap = 'GnBu', fmt = 'd')

# 去除x轴和y轴标签

plt.xlabel('Real')

plt.ylabel('Predict')

# 显示图形

plt.show()

# 模型的预测准确率

print('模型的准确率为:\n',metrics.accuracy_score(y_test, bnb_pred))

print('模型的评估报告:\n',metrics.classification_report(y_test, bnb_pred))

# 计算正例Positive所对应的概率,用于生成ROC曲线的数据

y_score = bnb.predict_proba(X_test)[:,1]

fpr,tpr,threshold = metrics.roc_curve(y_test.map({'Negative':0,'Positive':1}), y_score)

# 计算AUC的值

roc_auc = metrics.auc(fpr,tpr)

# 绘制面积图

plt.stackplot(fpr, tpr, color='steelblue', alpha = 0.5, edgecolor = 'black')

# 添加边际线

plt.plot(fpr, tpr, color='black', lw = 1)

# 添加对角线

plt.plot([0,1],[0,1], color = 'red', linestyle = '--')

# 添加文本信息

plt.text(0.5,0.3,'ROC curve (area = %0.2f)' % roc_auc)

# 添加x轴与y轴标签

plt.xlabel('1-Specificity')

plt.ylabel('Sensitivity')

# 显示图形

plt.show()

你可能感兴趣的:(python,评论分析)