原标题:基于Python的文本情感分类
前言
在上一期《【干货】--手把手教你完成文本情感分类》中我们使用了R语言对酒店评论数据做了情感分类,基于网友的需求,这里再使用Python做一下复现。关于步骤、理论部分这里就不再赘述了,感兴趣的可以前往上面提到的文章查看。下面给出Python的具体代码。
Python代码 # 导入第三包
importjieba
fromsklearn.feature_extraction.text importTfidfVectorizer
fromsklearn.naive_bayes importGaussianNB
fromsklearn.ensemble importRandomForestClassifier
fromsklearn.cross_validation importtrain_test_split fromsklearn importmetrics
importpandas aspd
importmatplotlib.pyplot asplt
# 读入评论数据
evaluation = pd.read_excel( 'Hotel Evaluation.xlsx',sheetname= 1)
# 展示数据前5行
evaluation.head()
# 读入自定义词
withopen( 'all_words.txt', encoding= 'UTF-8') aswords: my_words = [i.strip() fori inwords.readlines()]
# 将自定义词加入到jieba分词器中
forword inmy_words: jieba.add_word(word)
# 读入停止词
withopen( 'mystopwords.txt', encoding= 'UTF-8') aswords: stop_words = [i.strip() fori inwords.readlines()]
# 基于切词函数,构造自定义函数
defcut_word(sentence):words = [i fori injieba.cut(sentence) ifi notinstop_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)
使用TFIDF权重构造文档词条矩阵,注意,这里根据词频选择了最高频的20个词,作为矩阵的列数。
# 朴素贝叶斯模型
nb = GaussianNB()
# 建模
fit = nb.fit(X_train,y_train)
# 预测
pred = fit.predict(X_test)
# 测试集上的准确率
accuracy = metrics.accuracy_score(y_test,pred)print(accuracy)
通过构建朴素贝叶斯模型,得到的样本测试集准确率约为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, 'k-')
# 绘制参考线
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, 'k-')
# 绘制参考线
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完成情感分类的实战我们就分享到这里,大家注意,上面的方法是通过构造TFIDF权重的文档词条矩阵(词袋法)。如果你的文本非常大的话,使用这种方法会导致“词汇鸿沟”,即形成非常庞大的矩阵(而且还是稀疏矩阵),就会吃掉电脑的很多内存。而且这种方法还不能考虑到词与词之间的逻辑顺序。为了克服这个问题,科学家想出了词向量、文档向量等方法,后期我也会把这部分内容的理论和实战给大家做一个分享。如果你有任何问题,欢迎在公众号的留言区域表达你的疑问。同时,也欢迎各位朋友继续转发与分享文中的内容,让更多的人学习和进步。返回搜狐,查看更多
责任编辑: