赞
踩
前言
本模块将使用IMDB情绪分析数据集,数据集包含100,000条正面和负面的多段电影评论。利用NLP技术来预测电影评论是正向情绪还是负面情绪。
NLP(自然语言处理)是一种用于解决文本问题的技术。本模块将会用word2vec进行加载和清理IMDB电影评论,用模型预测是赞成还是反对。
模块分为三部分:
基本自然语言处理:Bag of Words面向初学者,介绍了基本自然语言处理技术。
用于文本理解的深度学习:在第2部分和第3部分中,深入研究如何使用Word2Vec训练模型以及如何将所得的词向量用于情感分析。
01
第一部分
读取数据集
- import pandas as pd
- import numpy as np
- from bs4 import BeautifulSoup
- import re
- # 载入数据集
- train = pd.read_csv('labeledTrainData.tsv',
- header=0,
- delimiter="\t",
- quoting=3)
调用get_text()得到没有标签或标记的评论文本。
BeautifulSoup是一个非常强大的库。这里用正则表达式删除标记并不是很好,最好还是使用BeautifulSoup之类的包。
在考虑如何清除文本时,应该考虑我们要解决的是什么数据问题。对于许多问题,删除标点符号是有意义的。但我们正在解决情感分析问题,并且可能“ !!!” 或“ :-(”可能带有情感,应将其视为单词。在本模块中,为简单起见,我完全删除了标点符号,但是您可以自己使用它。
- # 定义方法来清理文本数据:去掉停用词、标点符号
- # 把句子转成单词列表
- def review_to_words(raw_review):
- # 去除html标签
- review_text = BeautifulSoup(raw_review,
- 'html.parser').get_text()
- # 剔除非单词字符,并用空格替换
- letters_only = re.sub("[^a-zA-Z]", " " , review_text)
- # 转为为小写字母,并切分成单词
- words = letters_only.lower().split()
- # 剔除停用词
- stops = set(stopwords.words("english"))
- meaningful_words = [w for w in words if not w in stops]
- return " ".join(meaningful_words)
注释,将停用词列表转换为set是为了提高速度;由于我们将要调用该函数数万次,因此它需要快速运行,并且在Python中搜索集合比搜索列表要快得多。
OK,准备工作都做完了,现在可以循环清理所有训练集:
- num_reviews = train['review'].size
- clean_train_reviews = []
- for i in range(num_reviews):
- if (i + 1) % 1000 == 0:
- print("Review %d of %d\n" % (i+1, num_reviews))
- clean_train_reviews.append(review_to_words(train['review'][i]))
使用Bag of Words构造特征
两个句子:
Sentence 1: "The cat sat on the hat"
Sentence 2: "The dog ate the cat and the hat"
根据这两句话可以得到词集合如下:
{ the, cat, sat, on, hat, dog, ate, and }
bags of words:计算每个单词在句子中出现的次数。
Sentence 1, "the" 出现两次, "cat", "sat", "on", "hat" 各出现一次, 所以第一句话的特征词:
{ the, cat, sat, on, hat, dog, ate, and }
对应的特征向量是:
Sentence 1: { 2, 1, 1, 1, 1, 0, 0, 0 }
同样的,可以得到:
Sentence 1: { 3, 1, 0, 0, 1, 1, 1, 1}
下面用python实现上面的功能:「scikit-learn」
- # Bag of Words构造特征
- from sklearn.feature_extraction.text import CountVectorizer
- # 初始化CountVectorizer对象
- vectorizer = CountVectorizer(analyzer='word',
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。