Bag-of-words

Python 情感分析

Violeta Misheva

Data Scientist

What is a bag-of-words (BOW) ?

 

  • 描述單一文件或文件集合(語料庫)中的詞彙出現情況

  • 建立詞彙表並量化其出現程度

Python 情感分析

Amazon 產品評論

Amazon 產品評論資料集前 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...