阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
In this project, we use unsupervised learning models to cluster unlabeled documents into different groups, visualize the results and identify their latent topics/structures.
Things need to know
- 对于0基础的同学,以了解为主
- 不需要可以从0把code写出来
- 这部分code与算法课程code的思维不一样
- 需要下课自己去跑一下code,尽量去理解
- 工具终归是辅助我们的,先尽力学会一个
- 逐步掌握python code debug能力
Contents
- Part 1: Load Data(见本篇目录)
- Part 2: Tokenizing and Stemming(见本篇目录)
- Part 3: TF-IDF(见本篇目录)
- Part 4: K-means clustering(见本篇目录)
- Part 5: Topic Modeling - Latent Dirichlet Allocation(见本篇目录)
Part 0: Setup Google Drive Environment
# !pip install -U -q PyDrive
# from pydrive.auth import GoogleAuth
# from pydrive.drive import GoogleDrive
# from google.colab import auth
# from oauth2client.client import GoogleCredentials
# auth.authenticate_user()
# gauth = GoogleAuth()
# gauth.credentials = GoogleCredentials.get_application_default()
# drive = GoogleDrive(gauth)# file = drive.CreateFile({'id':'192JMR7SIqoa14vrs7Z9BXO3iK89pimJL'}) # replace the id with id of file you want to access
# file.GetContentFile('data.tsv') # tab-separatedPart 1: Load Data
import numpy as np
import pandas as pd
import nltk
# import gensim
from sklearn.feature_extraction.text import TfidfVectorizer
import matplotlib.pyplot as plt
nltk.download('punkt') # 标点符号
nltk.download('stopwords') # 语气助词等无意义的词[nltk_data] Downloading package punkt to
[nltk_data] C:\Users\[USER]\AppData\Roaming\nltk_data...
[nltk_data] Package punkt is already up-to-date!
[nltk_data] Downloading package stopwords to
[nltk_data] C:\Users\[USER]\AppData\Roaming\nltk_data...
[nltk_data] Package stopwords is already up-to-date!
True
tsv文件:tab-separated
# Load data into dataframe
df = pd.read_csv('watch_reviews.tsv', sep='\t', error_bad_lines=False)b'Skipping line 8704: expected 15 fields, saw 22\nSkipping line 16933: expected 15 fields, saw 22\nSkipping line 23726: expected 15 fields, saw 22\n'
b'Skipping line 85637: expected 15 fields, saw 22\n'
b'Skipping line 132136: expected 15 fields, saw 22\nSkipping line 158070: expected 15 fields, saw 22\nSkipping line 166007: expected 15 fields, saw 22\nSkipping line 171877: expected 15 fields, saw 22\nSkipping line 177756: expected 15 fields, saw 22\nSkipping line 181773: expected 15 fields, saw 22\nSkipping line 191085: expected 15 fields, saw 22\nSkipping line 196273: expected 15 fields, saw 22\nSkipping line 196331: expected 15 fields, saw 22\n'
b'Skipping line 197000: expected 15 fields, saw 22\nSkipping line 197011: expected 15 fields, saw 22\nSkipping line 197432: expected 15 fields, saw 22\nSkipping line 208016: expected 15 fields, saw 22\nSkipping line 214110: expected 15 fields, saw 22\nSkipping line 244328: expected 15 fields, saw 22\nSkipping line 248519: expected 15 fields, saw 22\nSkipping line 254936: expected 15 fields, saw 22\n'
b'Skipping line 272057: expected 15 fields, saw 22\nSkipping line 293214: expected 15 fields, saw 22\nSkipping line 310507: expected 15 fields, saw 22\nSkipping line 312306: expected 15 fields, saw 22\nSkipping line 316296: expected 15 fields, saw 22\n'
b'Skipping line 336028: expected 15 fields, saw 22\nSkipping line 344885: expected 15 fields, saw 22\nSkipping line 352551: expected 15 fields, saw 22\n'
b'Skipping line 408773: expected 15 fields, saw 22\nSkipping line 434535: expected 15 fields, saw 22\n'
b'Skipping line 581593: expected 15 fields, saw 22\n'
b'Skipping line 652409: expected 15 fields, saw 22\n'
整理注: 原pandas的error_bad_lines已弃用,新版对应on_bad_lines;跳过坏行应记录损失,不能默默把不完整数据当成全量。
df.head() marketplace customer_id review_id product_id product_parent \
0 US [ID] [REVIEW_ID] B00FALQ1ZC 937001370
1 US [ID] [REVIEW_ID] B00D3RGO20 484010722
2 US [ID] [REVIEW_ID] B00DKYC7TK 361166390
3 US [ID] [REVIEW_ID] B000EQS1JW 958035625
4 US [ID] [REVIEW_ID] B00A6GFD7S 765328221
product_title product_category \
0 Invicta Women's 15150 "Angel" 18k Yellow Gold ... Watches
1 Kenneth Cole New York Women's KC4944 Automatic... Watches
2 Ritche 22mm Black Stainless Steel Bracelet Wat... Watches
3 Citizen Men's BM8180-03E Eco-Drive Stainless S... Watches
4 Orient ER27009B Men's Symphony Automatic Stain... Watches
star_rating helpful_votes total_votes vine verified_purchase \
0 5 0 0 N Y
1 5 0 0 N Y
2 2 1 1 N Y
3 5 0 0 N Y
4 4 0 0 N Y
review_headline \
0 Five Stars
1 I love thiswatch it keeps time wonderfully
2 Two Stars
3 Five Stars
4 Beautiful face, but cheap sounding links
review_body review_date
0 Absolutely love this watch! Get compliments al... 2015-08-31
1 I love this watch it keeps time wonderfully. 2015-08-31
2 Scratches 2015-08-31
3 It works well on me. However, I found cheaper ... 2015-08-31
4 Beautiful watch face. The band looks nice all... 2015-08-31
# Remove missing value
df.dropna(subset=['review_body'],inplace=True)df.reset_index(inplace=True, drop=True)df.info()<class 'pandas.core.frame.DataFrame'>
RangeIndex: 960056 entries, 0 to 960055
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 marketplace 960056 non-null object
1 customer_id 960056 non-null int64
2 review_id 960056 non-null object
3 product_id 960056 non-null object
4 product_parent 960056 non-null int64
5 product_title 960054 non-null object
6 product_category 960056 non-null object
7 star_rating 960056 non-null int64
8 helpful_votes 960056 non-null int64
9 total_votes 960056 non-null int64
10 vine 960056 non-null object
11 verified_purchase 960056 non-null object
12 review_headline 960049 non-null object
13 review_body 960056 non-null object
14 review_date 960052 non-null object
dtypes: int64(5), object(10)
memory usage: 109.9+ MB
# use the first 1000 data as our training data
data = df.loc[:999, 'review_body'].tolist()dataPart 2: Tokenizing and Stemming
Load stopwords and stemmer function from NLTK library. Stop words are words like “a”, “the”, or “in” which don’t convey significant meaning. Stemming is the process of breaking a word down into its root.
# Use nltk's English stopwords.
stopwords = nltk.corpus.stopwords.words('english') #stopwords.append("n't")
stopwords.append("'s")
stopwords.append("'m")
stopwords.append("br") #html <br>
stopwords.append("watch") # 产品本身,出现次数太多无意义
print ("We use " + str(len(stopwords)) + " stop-words from nltk library.")
print (stopwords[:10])We use 183 stop-words from nltk library.
['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're"]
Use our defined functions to analyze (i.e. tokenize, stem) our reviews.
from nltk.stem.snowball import SnowballStemmer
# from nltk.stem import WordNetLemmatizer
stemmer = SnowballStemmer("english")
# tokenization and stemming
def tokenization_and_stemming(text):
tokens = []
# exclude stop words and tokenize the document, generate a list of string
for word in nltk.word_tokenize(text):
if word.lower() not in stopwords:
tokens.append(word.lower())
filtered_tokens = []
# filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
for token in tokens:
if token.isalpha():
filtered_tokens.append(token)
# stemming
stems = [stemmer.stem(t) for t in filtered_tokens]
return stemstokenization_and_stemming(data[0])['absolut',
'love',
'get',
'compliment',
'almost',
'everi',
'time',
'wear',
'dainti']
data[0]'Absolutely love this watch! Get compliments almost every time I wear it. Dainty.'
Part 3: TF-IDF
TF: Term Frequency
IDF: Inverse Document Frequency
from sklearn.feature_extraction.text import TfidfVectorizer
# define vectorizer parameters
# TfidfVectorizer will help us to create tf-idf matrix
# max_df : maximum document frequency for the given word
# min_df : minimum document frequency for the given word
# max_features: maximum number of words
# use_idf: if not true, we only calculate tf
# stop_words : built-in stop words
# tokenizer: how to tokenize the document
# ngram_range: (min_value, max_value), eg. (1, 3) means the result will include 1-gram, 2-gram, 3-gram
tfidf_model = TfidfVectorizer(max_df=0.99, max_features=1000,
min_df=0.01, stop_words='english',
use_idf=True, tokenizer=tokenization_and_stemming, ngram_range=(1,1))
tfidf_matrix = tfidf_model.fit_transform(data) #fit the vectorizer to synopses
print ("In total, there are " + str(tfidf_matrix.shape[0]) + \
" reviews and " + str(tfidf_matrix.shape[1]) + " terms.")C:\Users\[USER]\Anaconda3\envs\myenv\lib\site-packages\sklearn\feature_extraction\text.py:388: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['afterward', 'alon', 'alreadi', 'alway', 'anoth', 'anyon', 'anyth', 'anywher', 'becam', 'becom', 'besid', 'cri', 'describ', 'els', 'elsewher', 'empti', 'everi', 'everyon', 'everyth', 'everywher', 'fifti', 'forti', 'henc', 'hereaft', 'herebi', 'howev', 'hundr', 'inde', 'mani', 'meanwhil', 'moreov', 'nobodi', 'noon', 'noth', 'nowher', 'otherwis', 'perhap', 'pleas', 'sever', 'sinc', 'sincer', 'sixti', 'someon', 'someth', 'sometim', 'somewher', 'thenc', 'thereaft', 'therebi', 'therefor', 'togeth', 'twelv', 'twenti', 'whatev', 'whenc', 'whenev', 'wherea', 'whereaft', 'wherebi', 'wherev'] not in stop_words.
warnings.warn('Your stop_words may be inconsistent with '
In total, there are 1000 reviews and 239 terms.
tfidf_matrix<1000x239 sparse matrix of type '<class 'numpy.float64'>'
with 6891 stored elements in Compressed Sparse Row format>
tfidf_matrix.toarray() #todense()array([[0. , 0.5125863, 0. , ..., 0. , 0. ,
0. ],
[0. , 0. , 0. , ..., 0. , 0. ,
0. ],
[0. , 0. , 0. , ..., 0. , 0. ,
0. ],
...,
[0. , 0. , 0. , ..., 0. , 0. ,
0. ],
[0. , 0. , 0. , ..., 0. , 0. ,
0. ],
[0. , 0. , 0. , ..., 0. , 0. ,
0. ]])
tfidf_matrix.todense()matrix([[0. , 0.5125863, 0. , ..., 0. , 0. ,
0. ],
[0. , 0. , 0. , ..., 0. , 0. ,
0. ],
[0. , 0. , 0. , ..., 0. , 0. ,
0. ],
...,
[0. , 0. , 0. , ..., 0. , 0. ,
0. ],
[0. , 0. , 0. , ..., 0. , 0. ,
0. ],
[0. , 0. , 0. , ..., 0. , 0. ,
0. ]])
print(type(tfidf_matrix.toarray()))<class 'numpy.ndarray'>
print(type(tfidf_matrix.todense()))<class 'numpy.matrix'>
Save the terms identified by TF-IDF.
# words
tf_selected_words = tfidf_model.get_feature_names()# print out words
tf_selected_wordsPart 4: K-means clustering
# k-means clustering
from sklearn.cluster import KMeans
num_clusters = 5
# number of clusters
km = KMeans(n_clusters=num_clusters)
km.fit(tfidf_matrix)
clusters = km.labels_.tolist()4.1. Analyze K-means Result
# create DataFrame films from all of the input files.
product = { 'review': df[:1000].review_body, 'cluster': clusters}
frame = pd.DataFrame(product, columns = ['review', 'cluster'])frame.head(10) review cluster
0 Absolutely love this watch! Get compliments al... 3
1 I love this watch it keeps time wonderfully. 3
2 Scratches 4
3 It works well on me. However, I found cheaper ... 4
4 Beautiful watch face. The band looks nice all... 4
5 i love this watch for my purpose, about the pe... 3
6 for my wife and she loved it, looks great and ... 2
7 I was about to buy this thinking it was a Swis... 4
8 Watch is perfect. Rugged with the metal "B... 2
9 Great quality and build.<br />The motors are r... 4
print ("Number of reviews included in each cluster:")
frame['cluster'].value_counts().to_frame()Number of reviews included in each cluster:
cluster
4 665
3 108
2 88
0 77
1 62
km.cluster_centers_
# 239数的list -> cluster 0的中心点的tf-idf值
#-> assumption: 中心点的值可以代表这个cluster
#-> tf-idf值越大,对应的词越能代表这个document
#-> 选出了tf-idf最大的6个值对应的词来代表这个clusterarray([[0. , 0. , 0. , ..., 0. , 0.00851693,
0. ],
[0. , 0. , 0. , ..., 0. , 0.00784247,
0. ],
[0.00366467, 0. , 0. , ..., 0.00253264, 0. ,
0.01759334],
[0. , 0.04240567, 0. , ..., 0.01256107, 0.01765257,
0.00411372],
[0.00567344, 0.00438489, 0.00384023, ..., 0.00655072, 0.01806447,
0.01444302]])
km.cluster_centers_.shape(5, 239)
print ("<Document clustering result by K-means>")
#km.cluster_centers_ denotes the importances of each items in centroid.
#We need to sort it in decreasing-order and get the top k items.
order_centroids = km.cluster_centers_.argsort()[:, ::-1]
Cluster_keywords_summary = {}
for i in range(num_clusters):
print ("Cluster " + str(i) + " words:", end='')
Cluster_keywords_summary[i] = []
for ind in order_centroids[i, :6]: #replace 6 with n words per cluster
Cluster_keywords_summary[i].append(tf_selected_words[ind])
print (tf_selected_words[ind] + ",", end='')
print ()
cluster_reviews = frame[frame.cluster==i].review.tolist()
print ("Cluster " + str(i) + " reviews (" + str(len(cluster_reviews)) + " reviews): ")
# print (", ".join(cluster_reviews))
print ()<Document clustering result by K-means>
Cluster 0 words:good,product,qualiti,seller,price,love,
Cluster 0 reviews (77 reviews):
Cluster 1 words:nice,price,look,realli,simpl,good,
Cluster 1 reviews (62 reviews):
Cluster 2 words:great,look,price,work,comfort,product,
Cluster 2 reviews (88 reviews):
Cluster 3 words:love,wife,look,husband,beauti,absolut,
Cluster 3 reviews (108 reviews):
Cluster 4 words:look,like,work,band,time,beauti,
Cluster 4 reviews (665 reviews):
Part 5: Topic Modeling - Latent Dirichlet Allocation
# Use LDA for clustering
from sklearn.decomposition import LatentDirichletAllocation
lda = LatentDirichletAllocation(n_components=5)# document topic matrix for tfidf_matrix_lda
lda_output = lda.fit_transform(tfidf_matrix)
print(lda_output.shape)
print(lda_output)(1000, 5)
[[0.42969945 0.06141085 0.38946887 0.05978799 0.05963283]
[0.6634173 0.08437772 0.08482679 0.0839065 0.08347169]
[0.2 0.2 0.2 0.2 0.2 ]
...
[0.10000044 0.10013149 0.59966467 0.10002656 0.10017685]
[0.06674351 0.06846176 0.07261963 0.0683832 0.7237919 ]
[0.0672338 0.72805036 0.06933692 0.06767192 0.067707 ]]
整理注: 多项式LDA的生成解释以非负词频计数为输入;将TF-IDF当作伪计数是启发式,下面结果只作历史演示。严格实现应单独使用CountVectorizer构造计数矩阵。
# topics and words matrix
topic_word = lda.components_
print(topic_word.shape)
print(topic_word)(5, 239)
[[ 1.13920813 7.6710011 0.20165608 ... 3.64554513 0.20037498
1.10703462]
[ 0.21047875 0.20589301 2.74002393 ... 2.68511826 14.80703464
2.3549041 ]
[ 0.97769353 0.21649087 0.20169363 ... 0.201905 0.20227995
1.12382347]
[ 2.56440489 0.2023387 0.20864737 ... 0.20233214 0.64752384
7.56518096]
[ 0.20354177 0.20003914 0.20173408 ... 0.20079677 0.20417438
0.4461623 ]]
# column names
topic_names = ["Topic" + str(i) for i in range(lda.n_components)]
# index names
doc_names = ["Doc" + str(i) for i in range(len(data))]
df_document_topic = pd.DataFrame(np.round(lda_output, 2), columns=topic_names, index=doc_names)
# get dominant topic for each document
topic = np.argmax(df_document_topic.values, axis=1)
df_document_topic['topic'] = topic
df_document_topic.head(10) Topic0 Topic1 Topic2 Topic3 Topic4 topic
Doc0 0.43 0.06 0.39 0.06 0.06 0
Doc1 0.66 0.08 0.08 0.08 0.08 0
Doc2 0.20 0.20 0.20 0.20 0.20 0
Doc3 0.06 0.06 0.06 0.65 0.17 3
Doc4 0.04 0.45 0.43 0.04 0.04 1
Doc5 0.70 0.08 0.07 0.08 0.07 0
Doc6 0.41 0.06 0.06 0.06 0.39 0
Doc7 0.06 0.06 0.06 0.75 0.06 3
Doc8 0.05 0.05 0.05 0.82 0.05 3
Doc9 0.06 0.06 0.77 0.06 0.06 2
df_document_topic['topic'].value_counts().to_frame() topic
1 248
2 205
3 185
4 182
0 180
# topic word matrix
print(lda.components_)
# topic-word matrix
df_topic_words = pd.DataFrame(lda.components_)
# column and index
df_topic_words.columns = tfidf_model.get_feature_names()
df_topic_words.index = topic_names
df_topic_words.head()[[ 1.13920813 7.6710011 0.20165608 ... 3.64554513 0.20037498
1.10703462]
[ 0.21047875 0.20589301 2.74002393 ... 2.68511826 14.80703464
2.3549041 ]
[ 0.97769353 0.21649087 0.20169363 ... 0.201905 0.20227995
1.12382347]
[ 2.56440489 0.2023387 0.20864737 ... 0.20233214 0.64752384
7.56518096]
[ 0.20354177 0.20003914 0.20173408 ... 0.20079677 0.20417438
0.4461623 ]]
abl absolut accur actual adjust alarm alreadi \
Topic0 1.139208 7.671001 0.201656 0.200167 0.200879 0.200122 0.200976
Topic1 0.210479 0.205893 2.740024 5.001628 0.260939 0.201684 0.205563
Topic2 0.977694 0.216491 0.201694 0.201089 4.818173 0.487879 0.201867
Topic3 2.564405 0.202339 0.208647 0.252881 0.208815 2.275105 0.422232
Topic4 0.203542 0.200039 0.201734 0.200632 0.804365 2.775621 4.732731
alway amaz amazon ... weight went wife \
Topic0 0.200398 0.208290 0.202082 ... 0.200929 0.294798 11.833745
Topic1 0.203320 1.513278 0.852624 ... 4.276803 1.216873 0.202111
Topic2 3.474769 8.644823 3.019221 ... 0.201126 0.333560 0.202103
Topic3 0.759903 0.201576 2.528182 ... 0.839280 1.660421 0.203188
Topic4 0.201613 0.200868 0.200432 ... 0.200225 0.211523 0.201251
wind wish work worn worth wrist year
Topic0 0.202422 0.200119 12.357221 0.200533 3.645545 0.200375 1.107035
Topic1 1.586641 0.200581 0.203176 2.143129 2.685118 14.807035 2.354904
Topic2 1.537265 0.201630 12.185301 1.454484 0.201905 0.202280 1.123823
Topic3 0.204073 3.767683 7.330740 0.204782 0.202332 0.647524 7.565181
Topic4 0.703308 0.200496 8.985230 0.200165 0.200797 0.204174 0.446162
[5 rows x 239 columns]
# print top n keywords for each topic
def print_topic_words(tfidf_model, lda_model, n_words):
words = np.array(tfidf_model.get_feature_names())
topic_words = []
# for each topic, we have words weight
for topic_words_weights in lda_model.components_:
top_words = topic_words_weights.argsort()[::-1][:n_words]
topic_words.append(words.take(top_words))
return topic_words
topic_keywords = print_topic_words(tfidf_model=tfidf_model, lda_model=lda, n_words=15)
df_topic_words = pd.DataFrame(topic_keywords)
df_topic_words.columns = ['Word '+str(i) for i in range(df_topic_words.shape[1])]
df_topic_words.index = ['Topic '+str(i) for i in range(df_topic_words.shape[0])]
df_topic_words Word 0 Word 1 Word 2 Word 3 Word 4 Word 5 Word 6 Word 7 \
Topic 0 love excel perfect work wife gift thank husband
Topic 1 band look big wrist love like face size
Topic 2 good like beauti work qualiti time product pretti
Topic 3 awesom day color hand strap light look great
Topic 4 nice great look price expect exact recommend work
Word 8 Word 9 Word 10 Word 11 Word 12 Word 13 Word 14
Topic 0 absolut beauti bought great deal time invicta
Topic 1 time larg small nice pictur comfort read
Topic 2 wear month look amaz realli want dial
Topic 3 use water batteri replac year work second
Topic 4 band deliveri high use product clock fine