程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

python面试题(7)

python杂谈(0)

标签  

python面试题(7)

python电子书(56)

日期归档  

机器学习-情感分析小案例

发布于2019-08-22 17:45     阅读(344)     评论(0)     点赞(19)     收藏(5)


对发帖情感进行分析。

字段说明: Announce_ID字段代表用户ID,User_Name字段代表用户名,topic字段代表发帖主题,body字段代表发帖内容,post_type字段代表发帖话题是否与工作相关,sentiment字段表明发帖情感色彩,IP字段代表用户IP地址。

关于classify.xls文件 提取码:fkwq

相关代码

import pandas as pd
import jieba
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn import model_selection, metrics
from sklearn.naive_bayes import BernoulliNB
#  读入classify文件,Sheetname设为classify
df = pd.read_excel('classify.xls', sheet_name='classify')
# print(df)
# 	对post_type特征做频数统计
# print(df['post_type'].value_counts())
# 	删去User_Name、post_type、IP特征
df.drop(columns=['User_Name', 'post_type', 'IP'], inplace=True)
# print(df)
# 	对Body特征进行中文分词处理
df['Body'] = df['Body'].map(lambda x:jieba.lcut(x))
# print(df['Body'].head())
# 	读取停用词表,剔除停用词
s = ''
with open('stopwords.txt', 'r', encoding='utf8') as r:
    for i in r.readlines():
        s += i.strip()

df['Body'] = df['Body'].map(lambda x:[i for i in x if(i not in s) and (len(i) > 1)])
# print(df['Body'].head())
# 	将剔除停用词后的Body特征转换为矩阵向量
list1 = df['Body'].map(lambda line:' '.join(line))
cv = CountVectorizer()
w = cv.fit_transform(list1)
# 	降维处理得到特征X
svd = TruncatedSVD(50)
X = svd.fit_transform(w)
# 	切片sentiment特征作为目标标签Y
Y = df['sentiment']
# 	按照8:2划分数据集
train_x, test_x, train_y, test_y = model_selection.train_test_split(X, Y, test_size=0.2, random_state=0)
# 	建立朴素贝叶斯分类模型
model = BernoulliNB()
model.fit(train_x, train_y)
# 	进行模型训练和预测
h = model.predict(test_x)
# 	打印混淆矩阵和分类报告
print('classification_report:\n', metrics.classification_report(test_y, h))
print('confusion_matrix:\n', metrics.confusion_matrix(test_y, h))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44


所属网站分类: 技术文章 > 博客

作者:熊猫烧香

链接:https://www.pythonheidong.com/blog/article/53270/e0ed74447d490fb72cbc/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

19 0
收藏该文
已收藏

评论内容:(最多支持255个字符)