《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高,并且在其他文章中很少出现,则认为此词或者短语具有很好的类别区分能力,适合用来分类。