【干货】--基于Python的文本情感分类
感谢关注天善智能,走好数据之路↑↑↑
欢迎关注天善智能,我们是专注于商业智能BI,人工智能AI,大数据分析与挖掘领域的垂直社区,学习,问答、求职一站式搞定!
本文作者:天善智能社区专家刘顺祥
天善智能社区地址:https://www.hellobi.com/
前言
在上一期《【干货】--手把手教你完成文本情感分类》中我们使用了R语言对酒店评论数据做了情感分类,基于网友的需求,这里再使用Python做一下复现。关于步骤、理论部分这里就不再赘述了,感兴趣的可以前往上面提到的文章查看。下面给出Python的具体代码。
Python代码
# 导入第三包
import jieba
from sklearn.feature_extraction.text importTfidfVectorizer
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble importRandomForestClassifier
from sklearn.cross_validation importtrain_test_split
from sklearn importmetrics
import pandas as pd
import matplotlib.pyplot as plt
# 读入评论数据
evaluation = pd.read_excel('Hotel Evaluation.xlsx',sheetname=1)
# 展示数据前5行
evaluation.head()
# 读入自定义词
with open('all_words.txt', encoding='UTF-8') as words:
my_words = [i.strip()for i in words.readlines()]
# 将自定义词加入到jieba分词器中
for word in my_words:
jieba.add_word(word)
# 读入停止词
witho pen('mystopwords.txt', encoding='UTF-8') as words:
stop_words = [i.strip()foriinwords.readlines()]
# 基于切词函数,构造自定义函数
def cut_word(sentence):
words = [i for i in jieba.cut(sentence) if i not in stop_words]
# 切完的词用空格隔开
result =' '.join(words)
return(result)
上面代码所做的工作是将用户自定义词设置到jieba分词器中,同时,构造切词的自定义函数,添加的附加功能是删除停用词。
# TFIDF权重(根据词频,选出高频的20个词)
tfidf = TfidfVectorizer(max_features=20)
# 文档词条矩阵
dtm = tfidf.fit_transform(words).toarray()
# 矩阵的列名称
columns = tfidf.get_feature_names()
# 将矩阵转换为数据框--即X变量
X = pd.DataFrame(dtm, columns=columns)
# 情感标签变量
y = evaluation.Emotion
# 将数据集拆分为训练集和测试集
X_train,X_test,y_train,y_test = train_test_split(X,y,train_size =0.8, random_state=1)
通过构建朴素贝叶斯模型,得到的样本测试集准确率约为70%。
# 模型优度的可视化展现
fpr, tpr, _ = metrics.roc_curve(y_test, pred,pos_label=2)
auc = metrics.auc(fpr, tpr)
# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] =False
# 设置绘图风格
plt.style.use('ggplot')
# 绘制ROC曲线
plt.plot(fpr, tpr,'')
# 绘制参考线
plt.plot((0,1),(0,1),'r--')
# 添加文本注释
plt.text(0.5,0.5,'ROC=%.2f'%auc)
# 设置坐标轴标签和标题
plt.title('朴素贝叶斯模型的AUC曲线')
plt.xlabel('1-specificity')
plt.ylabel('Sensitivity')
# 去除图形顶部边界和右边界的刻度
plt.tick_params(top='off',right='off')
# 图形显示
plt.show()
# 随机森林模型
rf = RandomForestClassifier()
# 建模
fit2 = rf.fit(X_train,y_train)
# 预测
pred2 = fit2.predict(X_test)
# 测试集上的准确率
accuracy2 = metrics.accuracy_score(y_test,pred2)
print(accuracy2)
# 模型优度的可视化展现
fpr2, tpr2, _ = metrics.roc_curve(y_test, pred2,pos_label=2)
auc2 = metrics.auc(fpr2, tpr2)
# 中文和负号的正常显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] =False
# 设置绘图风格
plt.style.use('ggplot')
# 绘制ROC曲线
plt.plot(fpr2, tpr2,'')
# 绘制参考线
plt.plot((0,1),(0,1),'r--')
# 添加文本注释
plt.text(0.5,0.5,'ROC=%.2f'%auc2)
# 设置坐标轴标签和标题
plt.title('随机森林模型的AUC曲线')
plt.xlabel('1-specificity')
plt.ylabel('Sensitivity')
# 去除图形顶部边界和右边界的刻度
plt.tick_params(top='off', right='off')
# 图形显示
plt.show()
结语
OK,关于使用Python完成情感分类的实战我们就分享到这里,大家注意,上面的方法是通过构造DFIDF权重的文档词条矩阵(词袋法)。如果你的文本非常大的话,使用这种方法会导致“词汇鸿沟”,即形成非常庞大的矩阵(而且还是稀疏矩阵),就会吃掉电脑的很多内存。而且这种方法还不能考虑到词与词之间的逻辑顺序。为了克服这个问题,科学家想出了词向量、文档向量等方法,后期我也会把这部分内容的理论和实战给大家做一个分享。如果你有任何问题,欢迎在留言区域表达你的疑问。同时,也欢迎各位朋友继续转发与分享文中的内容,让更多的人学习和进步。
欢迎关注天善智能www.hellobi.com,我们是专注于商业智能BI,人工智能AI,大数据分析与挖掘领域的垂直社区,学习,问答、求职一站式搞定!