1、基于词袋模型的逻辑回归情感分类

# coding: utf-8
import re
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import itertools###########################词袋模型特征############################################
#重组为新的句子
def clean_text(text):"""去掉html标签、移除标点、切分成词/token、去掉停用词、重组为新的句子:param text::return:"""print(text)text = BeautifulSoup(text, 'html.parser').get_text()text = re.sub(r'[^a-zA-Z]', ' ', text)words = text.lower().split()stopwords = {}.fromkeys([line.rstrip() for line in open('../stopwords/stopwords_english.txt')])eng_stopwords = set(stopwords)print(eng_stopwords)words = [w for w in words if w not in eng_stopwords]print(words)return ' '.join(words)#混淆矩阵
def plot_confusion_matrix(cm, classes,title='Confusion matrix',cmap=plt.cm.Blues):"""This function prints and plots the confusion matrix."""plt.imshow(cm, interpolation='nearest', cmap=cmap)plt.title(title)plt.colorbar()tick_marks = np.arange(len(classes))plt.xticks(tick_marks, classes, rotation=0)plt.yticks(tick_marks, classes)thresh = cm.max() / 2.for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):plt.text(j, i, cm[i, j],horizontalalignment="center",color="white" if cm[i, j] > thresh else "black")plt.tight_layout()plt.ylabel('True label')plt.xlabel('Predicted label')if __name__=='__main__':#读取数据df = pd.read_csv('../data/labeledTrainData.tsv', sep='\t', escapechar='\\')print(df.head(5))#数据清洗,对df中的每一个Serial进行清洗df['clean_review'] = df.review.apply(clean_text)print(df['clean_review'])#抽取bag of words特征(用sklearn的CountVectorizer)vectorizer = CountVectorizer(max_features=5000)train_data_features = vectorizer.fit_transform(df.clean_review).toarray()print(train_data_features)# 数据切分X_train, X_test, y_train, y_test = train_test_split(train_data_features, df.sentiment, test_size=0.2,random_state=0)print(X_train,X_test,y_train,y_test)# ### 训练分类器LR_model = LogisticRegression()LR_model = LR_model.fit(X_train, y_train)y_pred = LR_model.predict(X_test)cnf_matrix = confusion_matrix(y_test, y_pred)print("Recall metric in the testing dataset: ", cnf_matrix[1, 1] / (cnf_matrix[1, 0] + cnf_matrix[1, 1]))print("accuracy metric in the testing dataset: ", (cnf_matrix[1, 1] + cnf_matrix[0, 0]) / (cnf_matrix[0, 0] + cnf_matrix[1, 1] + cnf_matrix[1, 0] + cnf_matrix[0, 1]))# Plot non-normalized confusion matrixclass_names = [0, 1]plt.figure()plot_confusion_matrix(cnf_matrix, classes=class_names, title='Confusion matrix')plt.show()

2、基于word2vec词向量模型的逻辑回归情感分类

import re
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import nltk
import warnings
from gensim.models.word2vec import Word2Vec
from nltk.corpus import stopwords
import matplotlib.pyplot as plt
import itertools
warnings.filterwarnings("ignore")def clean_text(text, remove_stopwords=False):text = BeautifulSoup(text, 'html.parser').get_text()text = re.sub(r'[^a-zA-Z]', ' ', text)words = text.lower().split()eng_stopwords = set(stopwords.words('english'))if remove_stopwords:words = [w for w in words if w not in eng_stopwords]return wordsdef split_sentences(review):#print(type(review))raw_sentences=tokenizer.tokenize(str(review).strip())sentences = [clean_text(s) for s in raw_sentences if s]return sentencesdef to_review_vector(review):global word_vecreview = clean_text(review, remove_stopwords=True)# print (review)# words = nltk.word_tokenize(review)word_vec = np.zeros((1, 300))for word in review:# word_vec = np.zeros((1,300))if word in model:word_vec += np.array([model[word]])# print (word_vec.mean(axis = 0))return pd.Series(word_vec.mean(axis=0))def plot_confusion_matrix(cm, classes,title='Confusion matrix',cmap=plt.cm.Blues):"""This function prints and plots the confusion matrix."""plt.imshow(cm, interpolation='nearest', cmap=cmap)plt.title(title)plt.colorbar()tick_marks = np.arange(len(classes))plt.xticks(tick_marks, classes, rotation=0)plt.yticks(tick_marks, classes)thresh = cm.max() / 2.for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):plt.text(j, i, cm[i, j],horizontalalignment="center",color="white" if cm[i, j] > thresh else "black")plt.tight_layout()plt.ylabel('True label')plt.xlabel('Predicted label')if __name__ == '__main__':#读取数据df = pd.read_csv('../data/labeledTrainData.tsv', sep='\t', escapechar='\\')#数据清洗df['clean_review'] = df.review.apply(clean_text)review_part = df['clean_review']#nltk库分词tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')sentences = sum(review_part.apply(split_sentences), [])sentences_list = []for line in sentences:sentences_list.append(nltk.word_tokenize(str(line).strip()))#word2vecnum_features = 300  # Word vector dimensionalitymin_word_count = 40  # Minimum word countnum_workers = 4  # Number of threads to run in parallelcontext = 10  # Context window sizemodel_name = '{}features_{}minwords_{}context.model'.format(num_features, min_word_count, context)model = Word2Vec(sentences_list, workers=num_workers, size=num_features, min_count=min_word_count, window=context)model.init_sims(replace=True)model.save('word2vec.models')train_data_features = df.review.apply(to_review_vector)X_train, X_test, y_train, y_test = train_test_split(train_data_features, df.sentiment, test_size=0.2, random_state=0)LR_model = LogisticRegression()LR_model = LR_model.fit(X_train, y_train)y_pred = LR_model.predict(X_test)cnf_matrix = confusion_matrix(y_test, y_pred)print("Recall metric in the testing dataset: ", cnf_matrix[1, 1] / (cnf_matrix[1, 0] + cnf_matrix[1, 1]))print("accuracy metric in the testing dataset: ", (cnf_matrix[1, 1] + cnf_matrix[0, 0]) / (cnf_matrix[0, 0] + cnf_matrix[1, 1] + cnf_matrix[1, 0] + cnf_matrix[0, 1]))# Plot non-normalized confusion matrixclass_names = [0, 1]plt.figure()plot_confusion_matrix(cnf_matrix , classes=class_names, title='Confusion matrix')plt.show()

转载于:https://www.cnblogs.com/ywjfx/p/11119175.html

NLP之电影评分数据的情感分析相关推荐

  1. IMBD影评数据的情感分析

    IMBD影评数据的情感分析 问题情况 SemEval往年的任务:情感分析(Sentiment Analysis,SA). 采用的某博客推荐的一个数据集,IMBD影评数据,给出5W条标注数据,每条数据包 ...

  2. 【NLP】从整体视角了解情感分析、文本分类!

    作者:太子长琴,算法工程师,Datawhale成员 文本分类是自然语言处理(NLP)最基础核心的任务,或者换句话说,几乎所有NLP任务都是「分类」任务,或者涉及到「分类」概念.比如分词.词性标注.命名 ...

  3. 利用python分析电商_基于Word2Vec+SVM对电商的评论数据进行情感分析

    Word2Vec-sentiment 基于Word2Vec+SVM对电商的评论数据进行情感分析 首先是利用word2vec对正负评论数据进行词向量训练,然后利用SVM分类器对语料进行分类,具体的过程如 ...

  4. NLP实战之–螺蛳粉评论情感分析和建模分类

    NLP实战之–螺蛳粉评论情感分析和建模分类 写在前面: 本文首发于我的微信公众号.新文章首发都会在微信公众号上. 自然语言处理(Natural Language Processing)是目前人工智能的 ...

  5. Hadoop 电影评分数据统计分析实验

    Hadoop Hadoop分布式计算基础是什么? 1.存储 2.计算 ==电影评分数据统计分析实验== ==[项目目标]== 1)掌握Hive的查询语句的使用 2)掌握R的可视化分析 ==[实验原理] ...

  6. 项目三:近10年来中国电影票房数据爬取分析

    近10年来中国电影票房数据爬取分析 前言 数据采集与存储 数据清洗和简单分析 引入库,导入数据 近10年top 年度top5 每年电影数 每年总票房 结论 二八原则 end 点击跳转到总目录 前言 这 ...

  7. 用Python做数据商品情感分析(商品评论数据情感分析)

    用Python做数据商品情感分析(商品评论数据情感分析) 现在,我们得到了一些关于XX商品的评论信息的数据,我们需要对这些评论信息的数据进行情感分析: 分析步骤 机械压缩去词 短句过滤 情感分析 分词 ...

  8. 机器学习-文本处理之电影评论多分类情感分析

    一.背景 文本处理是许多ML应用程序中最常见的任务之一.以下是此类应用的一些示例 语言翻译:将句子从一种语言翻译成另一种语言 情绪分析:从文本语料库中确定对任何主题或产品等的情绪是积极的.消极的还是中 ...

  9. 自然语言处理(NLP)之使用LSTM进行文本情感分析

    情感分析简介 文本情感分析(Sentiment Analysis)是自然语言处理(NLP)方法中常见的应用,也是一个有趣的基本任务,尤其是以提炼文本情绪内容为目的的分类.它是对带有情感色彩的主观性文本 ...

  10. 豆瓣电影评论爬取+情感分析+词云

    基于b站up主的视频 https://www.bilibili.com/video/BV18C4y1H7mr?t=1444 进行了优化 整合到一个main.py文件中函数式运行 自动化数据清洗 提供了 ...

最新文章

  1. Linux系统守护进程详解
  2. 算法导论之图的最小生成树
  3. linux下shell命令别名(alias)设置
  4. 动态与代理AOP--01【代理的作用与概念】【动态代理与AOP】
  5. Fatal error: Class 'ZipArchive' not found的解决办法
  6. CSDN总部落户长沙,共建中国开发者产业中心城市!
  7. 安阳学院有几次计算机考试,安阳:2017年上半年全国计算机等级考试顺利结束...
  8. java代码生成Excel文件3000条自定义属性的的域账户名
  9. ios 合并图片显示
  10. Ubuntu桌面图标无法打开终端的解决过程
  11. Python数据分析之智联招聘职位分析完整项目(数据爬取,数据分析,数据可视化)
  12. 51单片机LED流水灯、走马灯的实现
  13. 第十周项目2——贮存班长信息的学生类
  14. 远程桌面访问计算机的步骤,如何开启远程桌面连接功能
  15. 专访探索AGI的孤勇者,传奇工程师John Carmack:惊讶看不到如我这样的人
  16. Gingko Framework:Ant管理工程
  17. 华雨欢:副图指标强势买入开启上行走势关注阻力突破情况
  18. Qt入门教程-Qt介绍-01
  19. 为什么只有义乌个体户可以无限制结汇美金,什么原因
  20. 公众号推送模板消息,跳转小程序报错INVALID WEAPP PAGEPATH

热门文章

  1. java redis3.0_Java + Redis(第三章)
  2. python验证身份证最后一位数字代表什么_身份证尾数带X的人,是有什么特殊身份吗?看完涨知识了...
  3. 华为ebgp_华为路由器BGP邻居详解
  4. DevOps使用教程 华为云(17)git 比较2个分支版本的差异 某个具体文件的差异
  5. C++ std::pair<,> 是什么怎么用
  6. FISCO BCOS Solidity 智能合约 返回多个值
  7. java双向链表结构_【Java数据结构】2.3双向链表的迭代实现
  8. oracle怎么同步时间设置,【oracle数据库获取当前时间】
  9. python中英文混输对不齐_python如何处理中英文混排最长公共前缀问题
  10. java电器类代码_阅读下列说明和Java代码,将应填入(n)处的字句写在对应栏内。...