词袋模型(Bag-of-words)

Python 中的情感分析

Violeta Misheva

Data Scientist

什么是词袋模型(BOW)?

 

  • 描述单个文档或文档集合(语料库)中的词出现情况

  • 构建词汇表并度量其出现频次

Python 中的情感分析

亚马逊商品评论

亚马逊商品评论数据集的前 10 行

Python 中的情感分析

用 BOW 进行情感分析:示例

这是我读过最棒的书。我非常喜欢这本书,强烈推荐!!!

{'This': 1, 'is': 1, 'the': 2 , 'best': 1 , 'book': 2, 
'ever': 1, 'I':1 , 'loved':1 , 'and': 1  , 'highly': 1,
'recommend': 1 , 'it': 1 }
  • 会丢失词序和语法规则!
Python 中的情感分析

BOW 最终结果

  • 输出类似如下:

数据集前 5 行,展示 BOW 输出

Python 中的情感分析

CountVectorizer 函数

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer(max_features=1000) 
vect.fit(data.review)
X = vect.transform(data.review)
Python 中的情感分析

CountVectorizer 输出

X
<10000x1000 sparse matrix of type '<class 'numpy.int64'>' 
  with 406668 stored elements in Compressed Sparse Row format>

Python 中的情感分析

向量化器的转换

# Transform to an array
my_array = X.toarray()
# Transform back to a DataFrame, assign column names
X_df = pd.DataFrame(my_array, columns=vect.get_feature_names())
Python 中的情感分析

让我们练习吧!

Python 中的情感分析

Preparing Video For Download...