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 matrix
class_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 words def 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 sentences def to_review_vector(review):
global word_vec
review = 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())) #word2vec
num_features = 300 # Word vector dimensionality
min_word_count = 40 # Minimum word count
num_workers = 4 # Number of threads to run in parallel
context = 10 # Context window size
model_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 matrix
class_names = [0, 1]
plt.figure()
plot_confusion_matrix(cnf_matrix , classes=class_names, title='Confusion matrix')
plt.show()

NLP之电影评分数据的情感分析的更多相关文章

  1. NLP之中文自然语言处理工具库:SnowNLP(情感分析/分词/自动摘要)

    一 安装与介绍 1.1 概述 SnowNLP是一个python写的类库,可以方便的处理中文文本内容,是受到了TextBlob的启发而写的,由于现在大部分的自然语言处理库基本都是针对英文的,于是写了一个 ...

  2. 情感分析的现代方法(包含word2vec Doc2Vec)

    英文原文地址:https://districtdatalabs.silvrback.com/modern-methods-for-sentiment-analysis 转载文章地址:http://da ...

  3. 使用Spark MLlib进行情感分析

    使用Spark MLlib进行情感分析             使用Spark MLlib进行情感分析 一.实验说明 在当今这个互联网时代,人们对于各种事情的舆论观点都散布在各种社交网络平台或新闻提要 ...

  4. Stanford NLP学习笔记:7. 情感分析(Sentiment)

    1. 什么是情感分析(别名:观点提取,主题分析,情感挖掘...) 应用: 1)正面VS负面的影评(影片分类问题) 2)产品/品牌评价: Google产品搜索 3)twitter情感预测股票市场行情/消 ...

  5. 【项目实战】Kaggle电影评论情感分析

    前言 这几天持续摆烂了几天,原因是我自己对于Kaggle电影评论情感分析的这个赛题敲出来的代码无论如何没办法运行,其中数据变换的维度我无法把握好,所以总是在函数中传错数据.今天痛定思痛,重新写了一遍代 ...

  6. Java豆瓣电影爬虫——使用Word2Vec分析电影短评数据

    在上篇实现了电影详情和短评数据的抓取.到目前为止,已经抓了2000多部电影电视以及20000多的短评数据. 数据本身没有规律和价值,需要通过分析提炼成知识才有意义.抱着试试玩的想法,准备做一个有关情感 ...

  7. NLP入门(十)使用LSTM进行文本情感分析

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

  8. 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作

    目录 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作 前言 NLP相关的文本预处理 浅谈NLP 文本分类/情感分析 任务中的文本预处理工作 前言 之所以心血来潮想写这篇博客,是因为最近在关注N ...

  9. 爬虫再探实战(五)———爬取APP数据——超级课程表【四】——情感分析

    仔细看的话,会发现之前的词频分析并没有什么卵用...文本分析真正的大哥是NLP,不过,这个坑太大,小白不大敢跳...不过还是忍不住在坑边上往下瞅瞅2333. 言归正传,今天刚了解到boson公司有py ...

随机推荐

  1. Docker镜像拉取失败或超时的解决办法:添加国内镜像

    $ docker pull php:7.1-fpm-alpine Error response from daemon: Get https://registry-1.docker.io/v2/: n ...

  2. Airflow安装异常:ERROR: flask-appbuilder 1.12.3 has requirement Flask<2,>=0.12, but you'll have flask 0.11.1 which is incompatible.

    1 详细异常: ERROR: flask-appbuilder 1.12.3 has requirement Flask<2,>=0.12, but you'll have flask 0 ...

  3. 牛客练习赛51 C 勾股定理 (数学,结论)

    链接:https://ac.nowcoder.com/acm/contest/1083/C来源:牛客网 题目描述 给出直角三角形其中一条边的长度n,你的任务是构造剩下的两条边,使这三条边能构成一个直角 ...

  4. php 常用正则运算

    $regx = "/^[0-9]*$/"; var_dump(preg_match($regx, $phone)); 常用的正则运算: •验证数字:^[0-9]*$ •验证n位的数 ...

  5. tensorflow 更新出现HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.

    pip install --upgrade tensorflow --default-timeout=1000

  6. 题解 [CF332C] Students' Revenge

    题面 解析 辣鸡题面毁我青春 因为翻译的题面中写了一句\(剩下的n−k个不会完成\). 所以就以为剩下的\(n-k\)个都会算上不满意值. (然而事实是只有\(p-k\)个...) 首先根据主席的规则 ...

  7. 题解 [BZOJ4886] 叠塔游戏

    题面 解析 这是个有趣的建图题啊. 首先我们可以发现,宽度严格递增是没什么用的. 因为实际上我们在旋转完以后, 矩形的顺序是可以随便排的. 因此只要保证宽度互不相同就行了. 然后,我们对长和宽离散化, ...

  8. Java项目出现的问题02----学习

    1 框架配置无.java 在框架配置中当需要写类名是,注意是没有后面.java的 2 类中找不到main方法请将main方法定义为public static void main. 否则 JavaFX ...

  9. PHP mysqli_ping() 函数

    定义和用法 mysqli_ping() 函数进行一个服务器连接,如果连接已断开则尝试重新连接. <?php // 假定数据库用户名:root,密码:123456,数据库:RUNOOB $con= ...

  10. Qbxt 模拟赛 Day4 T2 gcd(矩阵乘法快速幂)

    /* 矩阵乘法+快速幂. 一开始迷之题意.. 这个gcd有个规律. a b b c=a*x+b(x为常数). 然后要使b+c最小的话. 那x就等于1咯. 那么问题转化为求 a b b a+b 就是斐波 ...