《python machine learning》 chapter 8 Applying Machine Learning to Sentiment Analysis

git源码:https://github.com/xuman-Amy/sentimental-analysis

项目说明:根据Internet Movie Database (IMDb)上获取的50000个影评,预测影评是积极的还是消极的。

(1)清洗 准备文本数据

(2)从数据集中构建特征向量

(3)训练模型区分影评的positive 和 negative

(4)out-of-core处理大数据集

(5)从文本分类中推断主题

【1、 准备数据】

数据说明:影评集为50000的大数据集,每条影评被标记为positive 和 negative,positive表示电影获得六星及以上的好评;negative表示六星以下。

【获取数据】

import pandas as pd
df = pd.read_csv("G:\Machine Learning\python machine learning\python machine learning code\code\ch08\movie_data.csv")
df.head()

【bag-of-words】

利用bag-of-words将文本数据转换为数值型特征向量。

bag-of-words的基本思想:

(1)创建一个具有唯一token的单词表,例如来自整个文档的单词

(2)在每个文档中创建一个特征向量——特征向量包含每个单词在特定文档中出现的频率。

【sklearn 实现bag-of-words】

将单词转换为特征向量

利用

#bag-of-words
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer()
doc = np.array([ 'The sun is shining','The weather is sweet','The sun is shining, the weather is sweet, and one and one is two'])
bag = count.fit_transform(doc)
print(count.vocabulary_)

将CountVectorizer将每个单词存储在字典中,与之相映射的是字典的数字索引。

特征向量中,0-9列与字典的索引相对应,特征向量如下:

print(bag.toarray())

(and, is, one, shining, sun, sweet, the, two, weather)

向量中的值也叫做原词的频率(raw term frequencies) tf(t,d)即term t 出现在词典d中的频率。

【tf-idf 】

term frequency-inverse document frequency:词频-逆向文件频率

如果某个词或短语在一篇文章中出现的频率TF高,并且在其他文章中很少出现,则认为此词或者短语具有很好的类别区分能力,适合用来分类。

文档总个数,文档d包含term t 的个数。加1 是为了确保分母不为0,log是为了保证较低的df不会占有太大权重。

【sklearn 实现tf-idf】

from sklearn.feature_extraction.text import TfidfTransformer
tfidf = TfidfTransformer(use_idf = True, norm = 'l2', smooth_idf = True)
tfidf.fit_transform(count.fit_transform(docs))
np.set_printoptions(precision = 2)
print(tfidf.fit_transform(count.fit_transform(docs)).toarray())

图表分析:

对比tf 和 tf-idf 表格发现,在tf表格中,单词‘is’在第三个文档中出现频率最高(3), 但是在tf-idf中频率偏低(0.45),这是因为is同样出现在了第一个和第二个文档中,所以判断is不像是包含有用判别信息的单词。

说明:

在sklearn中计算tf-idf的公式与上述公式稍有不同,在sklearn中计算公式为:

最后将tf-idf进行规范化,公式如下:

sklearn直接对数据进行了规范化处理,norm =’l2‘,返回一个长度为1的向量,其计算公式为

【清洗数据】

在进行bag-of-words等上述文档处理步骤前,首先要进行清洗数据,将不必要的信息条带化。

调用python的regular expression(regex)(正则表达式) 库,re, 进行数据清洗工作。

import re
def preprocessor(text):text = re.sub('<[^>]*>','', text)emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text)                           text = (re.sub('[\W]+', ' ', text.lower()) +' '.join(emoticons).replace('-', ''))return text
df['review'] = df['review'].apply(preprocessor)

【将文档处理成tokens】

(1)在空白字符处对清洗过的文档进行分割

def tokenizer(text):return text.split()
tokenizer('runners like running and thus they run')

(2)运用Porter stemmer algorithm返回单词的词干

#  word stemming 词干
from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()
def tokenizer_porter(text):return [porter.stem(word) for word in text.split()]
tokenizer_porter('runners like running and thus they run')

【去除stop-words】

stop-words在所有文档中都极其常见,且基本不包含便于区分类别的有用信息

可以从NLTK中直接加载127个英语中的stop-words。

#removing stop-words
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords
stop = stopwords.words('english')
[w for w in tokenizer_porter('runners like running and thus they run')[-10:] if w not in stop]

【训练文本分类的逻辑回归模型】

【将前25000划分为训练集,后25000划分为测试集】

#training LR model
#split train and test dataset
X_train = df.loc[:25000, 'review'].values
y_train = df.loc[:25000, 'sentiment'].values
X_test =  df.loc[25000:, 'review'].values
y_test =  df.loc[25000:, 'sentiment'].values

【运用grid search 寻找5-hold的LR模型的最佳参数集】

# train LR  mmodel
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import GridSearchCVtfidf = TfidfVectorizer(strip_accents=None,lowercase=False,preprocessor=None)param_grid = [{'vect__ngram_range': [(1, 1)],'vect__stop_words': [stop, None],'vect__tokenizer': [tokenizer, tokenizer_porter],'clf__penalty': ['l1', 'l2'],'clf__C': [1.0, 10.0, 100.0]},{'vect__ngram_range': [(1, 1)],'vect__stop_words': [stop, None],'vect__tokenizer': [tokenizer, tokenizer_porter],'vect__use_idf':[False],'vect__norm':[None],'clf__penalty': ['l1', 'l2'],'clf__C': [1.0, 10.0, 100.0]},]lr_tfidf = Pipeline([('vect', tfidf),('clf', LogisticRegression(random_state=0))])gs_lr_tfidf = GridSearchCV(lr_tfidf, param_grid,scoring='accuracy',cv=5,verbose=1,n_jobs=-1)
gs_lr_tfidf.fit(X_train, y_train)
print('Best parameter set: %s ' % gs_lr_tfidf.best_params_)
print('CV Accuracy: %.3f' % gs_lr_tfidf.best_score_)
clf = gs_lr_tfidf.best_estimator_
print('Test Accuracy: %.3f' % clf.score(X_test, y_test))

【out-of-core 处理大数据集】

定义tokenizer进行数据清洗以及分离单词token

# construct word tokens
import numpy as np
import re
from nltk.corpus import stopwordsdef tokenizer(text):text = re.sub('<[^>]*>', '', text)emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text.lower())text = re.sub('[\W]+', ' ', text.lower()) +\' '.join(emoticons).replace('-', '')tokenized = [w for w in text.split() if w not in stop]return tokenized#read in and return documents at a time
def stream_docs(path):with open(path, 'r', encoding='utf-8') as csv:next(csv)  # skip headerfor line in csv:text, label = line[:-3], int(line[-2])yield text, label

获取指定长度的文本

#  take a document stream from the stream_docs function
#  and return a particular number of documents specified by the size parameter
def get_minibatch(doc_stream, size):docs, y = [], []try:for _ in range(size):text, label = next(doc_stream)docs.apped(text)y.append(label)except StopIteration:return None, Nonereturn docs, y

运用HashingVectorizer进行文本预处理

from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier
vect = HashingVectorizer(decode_error = 'ignore', n_features = 2 ** 21,preprocessor = None,tokenizer = tokenizer)
clf = SGDClassifier(loss = 'log', random_state = 1, n_iter = 1)
doc_stream = stream_docs(path ='G:\Machine Learning\python machine learning\python machine learning code\code\ch08\movie_data.csv')

【进行out-of-core】

分批次加载训练集数据,每次加载1000条,共45*1000

import pyprind
pbar = pyprind.ProgBar(45)
classes = np.array([0,1])
for _ in range(45):X_train, y_train = get_minibatch(doc_stream, size=1000)  if not X_train:breakX_train  = vect.transform(X_train)clf.partial_fit(X_train, y_train, classes = classes)pbar.update()

加载5000条测试集

X_test, y_test = get_minibatch(doc_stream, size=5000)
X_test = vect.transform(X_test)
print('Accuracy: %.3f' % clf.score(X_test, y_test))

【Topic modeling with Latent Dirichlet Allocation (LDA)】

主题建模:将主题分配给未标记文本的广泛任务。

采用Latent Dirichlet Allocation (LDA)  隐狄利赫雷分布进行主题建模。

【LDA基本思想】

LDA是一种生成概率模型,试图找到在不同文档中高频出现的单词组,这些单词组能够反映文档主题。

输入为bag-of-words矩阵,输出为LDA将其分解为两个新的矩阵:与主题矩阵对应的文档;与主题矩阵对应的单词

主题个数为LDA的超参数,必须事先设置好。

【sklearn实现LDA】

利用LDA分解影评数据集,并对影评进行不同主题的分类。

【1. 读入数据】

import pandas as pd
df = pd.read_csv("G:\Machine Learning\python machine learning\python machine learning code\code\ch08\movie_data.csv",encoding = 'utf-8')
df.head()

【2. 创建bag-of-words 输入】

from sklearn.feature_extraction.text import CountVectorizer
# max_df = .1,max document frequency 最高文档频率占总文本的10%,
count = CountVectorizer(stop_words = 'english',max_df = .1,max_features = 5000)
X = count.fit_transform(df['review'].values)

【3. LDA】

#LDA modeling
from sklearn.decomposition import LatentDirichletAllocation
lda = LatentDirichletAllocation(n_topics = 10,random_state = 123,learning_method = 'batch')
X_topics = lda.fit_transform(X)

找出top5的单词

#five most important words for each of the 10 topics.
n_top_words = 5
feature_names = count.get_feature_names()
for topic_idx, topic in enumerate(lda.components_):print('Topic %d :' % (topic_idx + 1))print(" ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1 :-1]]))

推测电影类别

根据内容验证一下推测

horror = X_topics[:,5].argsort()[:: -1]
for iter_idx, movie_idx in enumerate(horror[:3]):print('\nHorror movie #%d:' % (iter_idx + 1))print(df['review'][movie_idx][:300], '...')

机器学习——情感分析相关推荐

  1. 机器学习-情感分析-入门实战案例

    前言 情感分析属于自然语言处理的一部分,其任务是,给定一个文本,判断这个文本所表达的情感是正面的,中立的,还是负面的.这被广泛用于: 1. 商品好评度自动检测. 2. 微博推特等平台用户发言是开心赞美 ...

  2. AI实战!开源一个机器学习/情感分析实战项目(附源码/教程)|湾区人工智能...

    分享一个在公司做的机器学习文本分类项目的demo,该分类项目是一个通用的文本分类项目,这里的数据集我酒店用户评价数据,分类模型为二分类,正面评价和负面评价,这里所说的通用,就是你可以根据你自己的数据, ...

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

    对发帖情感进行分析. 字段说明: Announce_ID字段代表用户ID,User_Name字段代表用户名,topic字段代表发帖主题,body字段代表发帖内容,post_type字段代表发帖话题是否 ...

  4. 机器学习基于语义特征的情感分析

    基于语义特征的情感分析先人已有研究,可以通过情感词典匹配来做,但是应用机器学习在这方面会使精确度更高些. 以本人参与的一个项目为主,总结下相关技术点. 背景是:分析用户评论感情色彩是积极还是消极,即是 ...

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

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

  6. 用机器学习实现情感分析

    更多文章欢迎来我的小博客 教程链接:https://www.bilibili.com/video/av19178430/?spm_id_from=333.23.home_video_list.1 知识 ...

  7. 文本情感分析-机器学习实验三

    情感分析-机器学习实验三 实验目的: 通过实验,掌握文本分析的整体流程,了解文本分类.情感分析.自动摘要等内容 通过给定的文本内容,完成分词.文本向量化.文本分类.情感分析等相关实验 实验可从文本分类 ...

  8. Python 基于机器学习的微博情感分析与研究

    源码下载地址 中文微博情感分类语料库 "情感分析"是我本科的毕业设计, 也是我入门并爱上NLP的项目hhh, 当时网上相关语料库的质量都太低了, 索性就自己写了个爬虫, 一边标注一 ...

  9. 基于机器学习的人民日报和微博等与疫情有关话题数据两极情感分析

    全套资料下载地址:https://download.csdn.net/download/sheziqiong/85584594?spm=1001.2014.3001.5503 目录 1.中文分词 Ch ...

最新文章

  1. jQuery中getJSON跨域原理详解
  2. R语言KNN模型数据分类实战
  3. 理解 Delphi 的类(十) - 深入方法[28] - 递归函数实例: 搜索当前目录下的所有嵌套目录...
  4. 如何用Transformer来做目标检测?一文简述DERT及其变体
  5. Files.newDirectoryStream扫描/过滤目录文件
  6. CSS-10-内边距
  7. 用ul li实现边框重合并附带鼠标经过效果
  8. Java Apple_GitHub - izhaorui/AppleLogin-java: 苹果登录 Sign in with Apple 服务端校验
  9. nginx服务器防sql注入/溢出***/spam及禁User-agents
  10. webstorm 破解方法(100%好使)
  11. wordpress炫酷主题Salient最新版13.0.5 汉化版免费下载
  12. FFmpeg系列-2-命令行工具之FFmpeg
  13. VSCode Workspace使用,以及file.exclude、search.exclude的使用模板
  14. 【5G核心网】 NGAP 消息
  15. MBR生活污水处理设备常见参数的具体作用
  16. 学生计算机屏幕坏了怎么办,电脑自己检查自己修,如果显示器坏掉我们该怎么办?...
  17. 建设工程施工劳务分包合同
  18. KSQL:Apache Kafka的流式SQL
  19. 软件设计师中级复习小总结
  20. vue + svg 绘制水波纹、波浪动画效果

热门文章

  1. JQuery 三元运算
  2. 【NodeJS】如何安装淘宝cnpm
  3. 加速成长有什么原则呢?
  4. C语言字符串截取函数strtok和strtok_r
  5. 移动CRM客户管理系统有哪些优势?
  6. Jmeter 参数化——用户参数
  7. java 编写的mp3 2
  8. [Visio] 如何导出Visio中的高清矢量图
  9. 国内常用dns服务器
  10. uniapp封装日历组件