TM07 embedding and clustering#
在做文本聚類(Document Clustering)的時候,即使抽出每個文本的關鍵字,也有可能會有聚類效果不好(群與群之間分不開)的情形。這其中一種可能的原因是文本中有非常多意義相近或類型相近的名詞,但在計算的時候被視為不同的文字。例如在政治類文本中的「小英」或「蔡英文」意指同一個人,但在計算上就是兩個相異詞;又如下列兩個句子,叉燒和豆花都是一種食品,在句子中的位置非常接近,但如果就以抽關鍵字與文字作為特徵向量的方法來做文件比對,這就是兩個完全相異的詞。所以,我們想要找到一種方法,能夠讓「叉燒」和「豆花」這兩個字的表徵「Representation」相近一些。
這家的「叉燒」不好吃
這家的招牌「豆花」令人感到失望
「詞嵌入(Word embeddings)」的想法是,從上面兩句話來看,可以發現「叉燒」與「豆花」兩個字周遭的句法結構是非常接近的,而且主要是「店家+食品+評價」的句法結構。所以,可以嘗試把「叉燒」或「豆花」周遭的文字作為該詞的表徵(除了自己本身以外),這也可以簡單地說是一個詞出現的脈絡。如果可以用這樣的方式表徵「叉燒」與「豆花」,那自然「店家」或「評價」也可以被這樣表徵,同時就克服了「叉燒」與「豆花」周遭的文字也有可能會有意思相近的情形。
詞嵌入:將一個詞周遭一定範圍內的字詞(除了該詞本身)作為該詞的表徵。
Process#
整體過程如下圖:
從一個文本有哪些字中,會建立一出每個字周遭w個字作為其脈絡的矩陣,亦即以周遭文字為特徵的term-term matrix。
之後會將該矩陣轉為一個等長的向量矩陣,每個字的周遭脈絡轉為300維。前兩個步驟為詞嵌入的過程,一般來說會是用word2vec的演算法做,抽取預測下一個字詞的第一層節點的權重來作為向量。
根據每篇文章有哪些詞,挑選(或不挑選)TF-IDF的向量做加總(為向量運算,加總後要除以加總的向量數)。
可得到每篇文章的向量。該向量長度會等於前面的文字向量。
這些向量就是該篇文章的特徵,就類似原本的群集法一樣,把每篇文章有哪些文字當作其特徵。有了這些特徵後,就可以往下做Clustering。
Loading data#
這邊用作範例的資料仍然是在TM06 Clustering所使用的評價留言。之前透過TF-IDF抽取關鍵字在群集的效果並不好,希望這個例子可以有所改善。
# !mkdir ./data
# !wget -P ./data -N https://github.com/p4css/py4css/raw/main/data/sentiment.csv
import pandas as pd
df = pd.read_csv('data/sentiment.csv')
import jieba
df['token_text'] = df['text'].apply(lambda x:list(jieba.cut(x)))
df.head()
Building prefix dict from the default dictionary ...
Loading model from cache /var/folders/4m/shks9p8j0dnbv51nf7cyysfc0000gn/T/jieba.cache
Loading model cost 0.280 seconds.
Prefix dict has been built successfully.
tag | text | token_text | |
---|---|---|---|
0 | P | 店家很給力,快遞也是相當快,第三次光顧啦 | [店家, 很, 給力, ,, 快遞, 也, 是, 相當快, ,, 第三次, 光顧, 啦] |
1 | N | 這樣的配置用Vista系統還是有點卡。 指紋收集器。 沒送原裝滑鼠還需要自己買,不太好。 | [這樣, 的, 配置, 用, Vista, 系統, 還是, 有點, 卡, 。, , 指紋,... |
2 | P | 不錯,在同等檔次酒店中應該是值得推薦的! | [不錯, ,, 在, 同等, 檔次, 酒店, 中應, 該, 是, 值得, 推薦, 的, !] |
3 | N | 哎! 不會是蒙牛乾的吧 嚴懲真凶! | [哎, !, , 不會, 是, 蒙牛, 乾, 的, 吧, , 嚴懲, 真凶, !] |
4 | N | 空尤其是三立電視臺女主播做的序尤其無趣像是硬湊那麼多字 | [空, 尤其, 是, 三立, 電視, 臺, 女主播, 做, 的, 序, 尤其, 無趣, 像是... |
Term frequency#
Loading stopwords#
# !wget https://raw.githubusercontent.com/p4css/py4css/main/data/sentiment.csv -O stopwords_zh-tw.txt
# !wget https://raw.githubusercontent.com/p4css/py4css/main/data/sentiment.csv -P data/
with open("data/stopwords_zh-tw.txt", encoding="utf-8") as fin:
stopwords = fin.read().split("\n")[1:]
print("stop words: ", stopwords[:100])
print(len(stopwords))
def remove_stopWords(words):
out = []
for word in words:
if word not in stopwords:
out.append(word)
return out
import unicodedata # for removing Chinese puctuation
def remove_punc_by_unicode(words):
out = []
for word in words:
if word != " " and not unicodedata.category(word[0]).startswith('P'):
out.append(word)
return out
df['cleaned'] = df['token_text'].apply(remove_stopWords)
df['cleaned'] = df['cleaned'].apply(remove_punc_by_unicode)
# for i in range(df.shape[0]):
# if len(df['cleaned'][i]) == 0:
# df['cleaned'][i] = df['token_text'][i]
df.head()
stop words: ['?', '、', '。', '“', '”', '《', '》', '!', '「', '」', '『', '』', ',', ':', ';', '?', '人民', '末##末', '啊', '阿', '哎', '哎呀', '哎喲', '唉', '我', '我們', '按', '按照', '依照', '吧', '吧噠', '把', '罷了', '被', '本', '本著', '比', '比方', '比如', '鄙人', '彼', '彼此', '邊', '別', '別的', '別說', '並', '並且', '不比', '不成', '不單', '不但', '不獨', '不管', '不光', '不過', '不僅', '不拘', '不論', '不怕', '不然', '不如', '不特', '不惟', '不問', '不只', '朝', '朝著', '趁', '趁著', '乘', '沖', '除', '除此之外', '除非', '除了', '此', '此間', '此外', '從', '從而', '打', '待', '但', '但是', '當', '當著', '到', '得', '的', '的話', '等', '等等', '地', '第', '叮咚', '對', '對於', '多', '多少']
1212
tag | text | token_text | cleaned | |
---|---|---|---|---|
0 | P | 店家很給力,快遞也是相當快,第三次光顧啦 | [店家, 很, 給力, ,, 快遞, 也, 是, 相當快, ,, 第三次, 光顧, 啦] | [店家, 給力, 快遞, 相當快, 第三次, 光顧] |
1 | N | 這樣的配置用Vista系統還是有點卡。 指紋收集器。 沒送原裝滑鼠還需要自己買,不太好。 | [這樣, 的, 配置, 用, Vista, 系統, 還是, 有點, 卡, 。, , 指紋,... | [配置, Vista, 系統, 有點, 卡, 指紋, 收集器, 沒送, 原裝, 滑鼠, 需要... |
2 | P | 不錯,在同等檔次酒店中應該是值得推薦的! | [不錯, ,, 在, 同等, 檔次, 酒店, 中應, 該, 是, 值得, 推薦, 的, !] | [不錯, 同等, 檔次, 酒店, 中應, 值得, 推薦] |
3 | N | 哎! 不會是蒙牛乾的吧 嚴懲真凶! | [哎, !, , 不會, 是, 蒙牛, 乾, 的, 吧, , 嚴懲, 真凶, !] | [蒙牛, 乾, 嚴懲, 真凶] |
4 | N | 空尤其是三立電視臺女主播做的序尤其無趣像是硬湊那麼多字 | [空, 尤其, 是, 三立, 電視, 臺, 女主播, 做, 的, 序, 尤其, 無趣, 像是... | [空, 尤其, 三立, 電視, 臺, 女主播, 做, 序, 尤其, 無趣, 像是, 硬, 湊... |
Detecting Chinese punctuation#
以下先觀察資料的詞頻(依照高至低排列)
# Take a look at the most common words (from high to low)
from collections import Counter
word_count = Counter([tok for tokens in df['cleaned'] for tok in tokens if len(tok) > 1])
for k, v in word_count.most_common(10):
print(k, '\t', v)
蒙牛 1556
不錯 907
酒店 385
房間 366
感覺 350
外觀 294
系統 276
價格 269
價效 262
螢幕 258
Building word2vec model#
Building model#
vector_size
: 每個詞要表徵為多少維度的向量window
: 每個詞的表徵要納入前後多少個詞。
from gensim.models import Word2Vec
model = Word2Vec(df['token_text'], min_count=1, vector_size=300, window=10, sg=0, workers=4)
Testing Similarity#
Number of dimensions of the NumPy array:
.ndim
Shape of the NumPy array:
.shape
Size of the NumPy array:
.size
Size of the first dimension of the NumPy array:
len()
print(model.wv["火鍋"].shape)
print(model.wv["火鍋"].size)
print(model.wv["火鍋"].ndim)
print(len(model.wv["火鍋"]))
model.wv["蒙牛"]
(300,)
300
1
300
array([-0.5105431 , 0.8858694 , 0.48873267, 0.12496246, -0.57806844,
-0.38385832, 1.0465271 , 1.049438 , 0.530551 , -0.45628113,
0.780779 , 0.2928741 , -0.461724 , 0.15104699, -0.4213029 ,
-1.2010435 , 0.6542298 , -0.37606373, -0.19338731, 0.06049143,
0.11330958, 0.06463069, 0.3427354 , 0.08946352, 1.2562237 ,
-0.45284495, -1.1701094 , 0.08525721, -0.8077981 , -0.82034427,
-1.0748754 , -0.27730462, 0.61387604, -0.00454331, 0.04145009,
0.79247653, 0.65097415, -1.00686 , -0.5981623 , -0.13436933,
-0.31301326, 0.6955541 , 0.05481876, -0.3349052 , 0.4508819 ,
0.09003272, 0.6122374 , 0.39772543, 0.14461593, 0.6841412 ,
0.57146955, 0.17121813, -1.1076547 , 1.0150781 , -0.22128837,
0.18419659, 0.74125236, -0.01680266, -0.27885473, -0.11273608,
-0.75225276, 0.16985638, -0.23147267, 0.4694359 , 0.03754377,
0.37561837, -0.03029334, 0.75836927, -0.4509461 , -0.20502524,
-0.15325408, 0.82858765, 0.35713494, -0.6196256 , 0.7551275 ,
-0.36407316, -0.41704506, -0.08871284, -0.10270957, 0.6075051 ,
-0.41316175, -0.5521212 , 0.18570875, 1.4989591 , -0.32291216,
0.21751997, 0.58580273, -0.34260964, 0.50758195, 1.0364447 ,
0.5164555 , -0.329375 , 0.13779542, -0.39349002, 1.4777262 ,
1.2098545 , 0.45296606, -0.515353 , -0.26470366, 0.60642785,
-0.67223525, -0.0554019 , 0.5581577 , 0.01661327, 0.70742625,
-0.7309818 , -0.44075432, -0.07077634, -0.8144061 , 0.26579872,
-0.7236198 , -0.54474634, -0.07569959, 0.18754831, 1.0042411 ,
0.28739813, -0.2134803 , 1.1050733 , 1.071562 , -0.9877667 ,
0.7792952 , 0.58648026, 0.605833 , 0.09868749, -0.23217976,
0.73651725, -0.07169783, -0.81893927, -0.17743416, 0.8757605 ,
0.5441889 , 0.88884526, 0.06259224, -1.4647007 , 0.1649625 ,
0.53333884, -0.21657729, -0.32347998, -0.6818849 , -0.9754918 ,
1.0529157 , -1.5619938 , -0.48155198, 0.18607919, 0.5106842 ,
0.03263763, -1.5105731 , -0.7288999 , 0.98939544, -0.72269356,
0.8879167 , -1.5596437 , -0.95458895, -0.432601 , -0.24559171,
0.83950406, -1.0616465 , -0.70751524, -0.24720664, 0.9263881 ,
0.48101676, 0.9386984 , -1.0828449 , 0.9566941 , -0.04587612,
0.6994556 , 0.11600865, -0.5792062 , 0.38626483, 1.6532204 ,
-1.1143236 , 0.329551 , 0.6524294 , 0.3362332 , 0.4535553 ,
0.8931658 , -0.24695462, -0.43689886, 0.33014563, -0.60215825,
-0.2443789 , 0.17725153, -1.0194701 , -0.53874034, -0.6997679 ,
0.10869089, 1.0737206 , 0.3195628 , 0.66034293, -1.1869107 ,
0.56816244, -0.17224565, -0.5691373 , -0.11328684, 0.5146643 ,
-1.4241788 , 0.22268268, -1.4028335 , -0.547551 , -0.04455552,
-0.6441659 , -0.25783092, 0.0932089 , -0.85747695, 0.5016894 ,
-0.5361453 , -0.62336814, 0.7438685 , 0.23383614, -0.48486307,
-0.255156 , -0.81642896, -0.8659461 , -0.47886065, 1.0509156 ,
-0.69433945, -0.509587 , -1.3391727 , -0.7740386 , -1.0658995 ,
1.0179071 , 0.14567956, -0.77857834, -0.8035548 , 0.08228252,
-0.2898026 , -0.0797724 , -0.6299001 , -0.7372738 , 0.55476546,
0.16978317, -0.35818005, -0.16692948, -0.65561295, -0.2789109 ,
0.48916954, 0.06176167, 0.7330552 , 0.424453 , -0.5571929 ,
0.6190778 , -0.2869817 , -0.01025965, -0.5546449 , 0.6787046 ,
-1.1680521 , -0.49433735, -0.07052532, -0.15982376, 1.018179 ,
0.3246593 , 0.29522654, 0.6985339 , -0.05513645, -0.4374863 ,
0.06900304, 1.7940474 , 0.40881866, -0.7270854 , -0.61266524,
0.25049093, -0.38816288, 0.00796079, -0.64621377, -1.1206702 ,
-0.28266522, 0.92306924, -0.08905739, -0.02233449, 0.8633096 ,
-0.4685435 , -0.35264182, -0.08124615, 0.06539351, 1.0129662 ,
0.8883599 , 1.2012233 , 0.3172498 , -0.4730123 , 0.09734334,
0.84954786, -0.05685527, 0.48595732, -0.28533053, -0.06361958,
0.45055526, -1.1697162 , 1.0739601 , 0.31660962, 0.86748415,
0.25319037, 0.16810201, 0.7458099 , -0.14978851, 0.34254932,
1.5139303 , 0.4003326 , -0.24550343, 0.42673454, -1.00008 ],
dtype=float32)
# 他 : 工程師 = 她 : ?
print(model.wv.most_similar(["火鍋", "好吃"], ["廁所"], topn=20))
print("-"*40)
# 他 : 醫師 = 她 : ?
print(model.wv.most_similar(["鍵盤", "工具"], ["垃圾"], topn=20))
[('害怕', 0.9128491282463074), ('O', 0.9122375249862671), ('風雲榜', 0.9101558923721313), ('∩', 0.9096634387969971), ('努力', 0.909494161605835), ('哈', 0.9093124866485596), ('香蕉', 0.9091224670410156), ('哈哈', 0.9086211323738098), ('結論', 0.9081854224205017), ('不實', 0.9079273343086243), ('總結', 0.9073262810707092), ('山寨', 0.9072703719139099), ('嘍', 0.9071218371391296), ('`', 0.9070659875869751), ('三位', 0.906972348690033), ('不貴', 0.9067694544792175), ('雪糕', 0.9065198302268982), ('香草', 0.9064580798149109), ('妹夫', 0.9059102535247803), ('史上', 0.9056995511054993)]
----------------------------------------
[('地點', 0.8689790964126587), ('較', 0.8647874593734741), ('溫馨', 0.8629613518714905), ('價效', 0.8583545088768005), ('比', 0.8570104837417603), ('比還', 0.8560540080070496), ('比比', 0.8521322011947632), ('敞', 0.8456562757492065), ('電梯', 0.8448537588119507), ('高', 0.8439202904701233), ('環繞', 0.8435788750648499), ('出入', 0.8434141278266907), ('時聲音', 0.8426613807678223), ('公道', 0.8424654603004456), ('不錯', 0.842320442199707), ('X61', 0.8390520811080933), ('配套', 0.8374311327934265), ('外觀', 0.8350318670272827), ('外觀還', 0.8349447250366211), ('無論', 0.834021270275116)]
Visualized with Dimension reduction#
%matplotlib inline
import matplotlib.pyplot as plt
plt.gcf().set_size_inches(24, 16)
#
plt.rcParams.update({'font.size': 12})
plt.rcParams['font.family'] = ['Heiti TC']
<Figure size 2400x1600 with 0 Axes>
Retrieve top 150 to visualize#
words = [k for k, v in word_count.most_common(150)]
print(words)
X = []
for word in words:
X.append(model.wv[word])
['蒙牛', '不錯', '酒店', '房間', '感覺', '外觀', '系統', '價格', '價效', '螢幕', '喜歡', '方便', '有點', '比較', '功能', '服務', '一個', '配置', '問題', '不好', '速度', '時間', '鍵盤', '支援', '知道', '電池', 'XP', '效果', '質量', '還不錯', '驅動', '散熱', '記憶體', '抵制', '東西', '伊利', '漂亮', '滿意', '顯示', '牛奶', '早餐', '收到', '使用', '安裝', '內容', '做工', '效能', '這本書', '便宜', '環境', '很快', '設施', '聲音', '適合', '發現', '手感', '一點', '現在', '容易', '朋友', '光碟', '真的', '硬碟', '已經', '機器', '應該', '覺得', '麻煩', '產品', '好看', '舒服', '電腦', '位置', '值得', '希望', '一下', '入住', '沒什麼', '設計', '特別', '一本', '待機', '執行', '小巧', '很大', '京東', '送貨', '下次', '軟體', '不到', '包裝', '本本', '還行', '很漂亮', '品牌', '真是', '太小', '介面', '需要', '鈴聲', '總體', '推薦', '失望', '攝像頭', '一直', '垃圾', '比高', '手機', '想象', '選擇', '機子', '客服', '交通', '小時', '孩子', '實用', '還算', '呵呵', '相當', '購買', '滑鼠', '只能', '態度', '電話', '晚上', '酸奶', '下載', '味道', '完美', '還好', '看到', '一些', 'xp', '地方', '簡單', '好像', '建議', '太差', '時尚', '服務態度', '方面', '這款', 'vista', '拿到', '同事', '齊全', '外殼', '水器', 'MP3', '噹噹']
Reduced by PCA#
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
points = pca.fit_transform(X)
points[:20]
array([[ 4.52534862, 6.44803114],
[ 4.24852615, -2.32420487],
[ 4.70027249, -1.37521306],
[ 4.99491412, -1.62780521],
[ 3.90997399, -0.04516882],
[ 3.38035588, -1.94135661],
[ 3.93574247, 0.64477241],
[ 3.17981605, -0.98313698],
[ 3.09375654, -2.75387097],
[ 3.64159842, -0.79397616],
[ 1.16843056, 1.44078738],
[ 2.82517709, -1.10403721],
[ 4.43729271, 0.89251478],
[ 3.82158171, -0.71763592],
[ 2.72372987, -0.57173526],
[ 2.35483552, -1.32678467],
[ 3.31894014, 1.49902618],
[ 2.30579229, -1.33311847],
[ 2.18341624, 1.48769103],
[ 2.52467673, 0.24877299]])
Reduced by t-SNE#
from sklearn.manifold import TSNE
tsne = TSNE(n_components=2, random_state=0)
points = tsne.fit_transform(X)
points[:20]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[11], line 4
1 from sklearn.manifold import TSNE
3 tsne = TSNE(n_components=2, random_state=0)
----> 4 points = tsne.fit_transform(X)
6 points[:20]
File ~/anaconda3/lib/python3.10/site-packages/sklearn/manifold/_t_sne.py:1118, in TSNE.fit_transform(self, X, y)
1097 """Fit X into an embedded space and return that transformed output.
1098
1099 Parameters
(...)
1115 Embedding of the training data in low-dimensional space.
1116 """
1117 self._validate_params()
-> 1118 self._check_params_vs_input(X)
1119 embedding = self._fit(X)
1120 self.embedding_ = embedding
File ~/anaconda3/lib/python3.10/site-packages/sklearn/manifold/_t_sne.py:828, in TSNE._check_params_vs_input(self, X)
827 def _check_params_vs_input(self, X):
--> 828 if self.perplexity >= X.shape[0]:
829 raise ValueError("perplexity must be less than n_samples")
AttributeError: 'list' object has no attribute 'shape'
Plotting#
Plot by matplotlib or seaborn#
# fig = plt.gcf()
# fig.set_size_inches(24, 16)
plt.figure(figsize=(16, 12), dpi=300)
# plt.figure(figsize=(8, 6), dpi=300)
plt.rcParams.update({'font.size': 12})
plt.rcParams['font.family'] = ['Heiti TC']
for i in range(len(points)):
x = points[i][0]
y = points[i][1]
plt.scatter(x, y, alpha=0)
plt.annotate(words[i], xy=(x, y), alpha=0.5)
plt.axis('equal')
(-10.220569610595703,
9.543460845947266,
-12.77907681465149,
12.749464273452759)

plot by bokeh#
https://stackoverflow.com/questions/40450943/adding-labels-to-a-bokeh-plot
https://docs.bokeh.org/en/latest/docs/user_guide/annotations.html
import pandas as pd
import numpy as np
scatter = pd.DataFrame(points, columns = ['x', 'y'])
scatter['label'] = words
scatter
x | y | label | |
---|---|---|---|
0 | 3.505675 | 13.307721 | 蒙牛 |
1 | -8.033687 | -8.971017 | 不錯 |
2 | -8.605733 | -8.072555 | 酒店 |
3 | -8.688294 | -8.623928 | 房間 |
4 | -5.358955 | -3.547830 | 感覺 |
... | ... | ... | ... |
145 | 6.062129 | -3.935656 | 齊全 |
146 | 3.967966 | 1.523833 | 外殼 |
147 | 4.767049 | 2.144461 | 水器 |
148 | 7.782829 | -0.898691 | MP3 |
149 | 6.784741 | 6.188130 | 噹噹 |
150 rows × 3 columns
# !pip install bokeh
# !pip install jupyter_bokeh
from bokeh.models import ColumnDataSource, Label, LabelSet, Range1d
from bokeh.plotting import figure, output_file, show
from bokeh.io import output_notebook
output_notebook()
p = figure(title = "w2v")
p.circle(scatter["x"], scatter["y"], fill_alpha=0.2, size=10)
labels = LabelSet(x='x', y='y', text='label',
x_offset=5, y_offset=5,
source=ColumnDataSource(scatter), render_mode='canvas')
p.add_layout(labels)
show(p)
Doc clustering with embeddings#
Sum up wordvec to docvec#
df
tag | text | token_text | cleaned | |
---|---|---|---|---|
0 | P | 店家很給力,快遞也是相當快,第三次光顧啦 | [店家, 很, 給力, ,, 快遞, 也, 是, 相當快, ,, 第三次, 光顧, 啦] | [店家, 給力, 快遞, 相當快, 第三次, 光顧] |
1 | N | 這樣的配置用Vista系統還是有點卡。 指紋收集器。 沒送原裝滑鼠還需要自己買,不太好。 | [這樣, 的, 配置, 用, Vista, 系統, 還是, 有點, 卡, 。, , 指紋,... | [配置, Vista, 系統, 有點, 卡, 指紋, 收集器, 沒送, 原裝, 滑鼠, 需要... |
2 | P | 不錯,在同等檔次酒店中應該是值得推薦的! | [不錯, ,, 在, 同等, 檔次, 酒店, 中應, 該, 是, 值得, 推薦, 的, !] | [不錯, 同等, 檔次, 酒店, 中應, 值得, 推薦] |
3 | N | 哎! 不會是蒙牛乾的吧 嚴懲真凶! | [哎, !, , 不會, 是, 蒙牛, 乾, 的, 吧, , 嚴懲, 真凶, !] | [蒙牛, 乾, 嚴懲, 真凶] |
4 | N | 空尤其是三立電視臺女主播做的序尤其無趣像是硬湊那麼多字 | [空, 尤其, 是, 三立, 電視, 臺, 女主播, 做, 的, 序, 尤其, 無趣, 像是... | [空, 尤其, 三立, 電視, 臺, 女主播, 做, 序, 尤其, 無趣, 像是, 硬, 湊... |
... | ... | ... | ... | ... |
6383 | P | 價效比高、記憶體大、功能全,螢幕超清晰 | [價效, 比高, 、, 記憶體, 大, 、, 功能, 全, ,, 螢幕超, 清晰] | [價效, 比高, 記憶體, 功能, 全, 螢幕超, 清晰] |
6384 | N | 你太狠了… 告訴你他們不會喧譁的人,肯定是蒙牛喝多了 | [你, 太狠, 了, …, , 告訴, 你, 他們, 不會, 喧, 譁, 的, 人, ,,... | [太狠, 告訴, 喧, 譁, 人, 肯定, 蒙牛, 喝多] |
6385 | N | 醫生居然買了蒙牛,我是喝呢還是不喝呢還是不喝呢? | [ , 醫生, 居然, 買, 了, 蒙牛, ,, 我, 是, 喝, 呢, 還是, 不, 喝,... | [醫生, 買, 蒙牛, 喝, 喝, 喝] |
6386 | N | 我只想說 夾蒙牛是不對的 販賣毒品是犯罪行為 | [我, 只, 想, 說, , 夾, 蒙牛, 是, 不, 對, 的, , 販賣, 毒品, ... | [只, 想, 說, 夾, 蒙牛, 販賣, 毒品, 犯罪, 行為] |
6387 | P | 蒙牛便宜 | [蒙牛, 便宜] | [蒙牛, 便宜] |
6388 rows × 4 columns
Counter([len(tokens) for tokens in df["cleaned"]])
Counter({6: 416,
13: 512,
7: 438,
4: 278,
14: 425,
8: 442,
2: 182,
12: 564,
17: 162,
15: 341,
10: 526,
9: 530,
11: 535,
16: 265,
5: 315,
3: 242,
19: 42,
1: 50,
23: 1,
18: 91,
20: 19,
0: 4,
21: 5,
32: 1,
22: 2})
import numpy as np
all_list = []
# for tokens in df["cleaned"]:
for tokens in df["token_text"]:
temp_w2v = np.zeros(300)
# if len(tokens) == 0:
# all_list.append(temp_w2v)
# continue
count = 0
for tok in tokens:
if tok in model.wv: # Check if the token is in the model
temp_w2v += model.wv[tok]
count += 1
if count > 0:
temp_w2v /= count # Averaging
all_list.append(temp_w2v / np.linalg.norm(temp_w2v)) # Normalizing
len(all_list)
6388
Convert to numpy array#
import numpy as np
X = np.array(all_list)
X.shape
(6388, 300)
Reduce dimension by tsne#
from sklearn.manifold import TSNE
tsne = TSNE(n_components=2,
random_state=0,
init='random',)
tsne_embeddings = tsne.fit_transform(X)
# points_tsne[:10].shape
/Users/jirlong/opt/anaconda3/lib/python3.9/site-packages/sklearn/manifold/_t_sne.py:790: FutureWarning: The default learning rate in TSNE will change from 200.0 to 'auto' in 1.2.
warnings.warn(
Reduce dimension by umap#
# !pip install umap-learn
import umap
# X = np.where(np.isinf(X), np.finfo(np.float32).max, X)
umap_embeddings = umap.UMAP(n_neighbors=15,
n_components=5,
metric='cosine').fit_transform(X)
umap_embeddings.shape[0]
6388
Clustering by hdbscan#
import numpy as np
def gini_coefficient(counts):
counts = np.array(list(counts.values()))
counts.sort()
index = np.arange(1, counts.shape[0] + 1)
n = counts.shape[0]
return ((np.sum((2 * index - n - 1) * counts)) / (n * np.sum(counts)))
from scipy.stats import entropy
def calculate_entropy(counts):
values = np.array(list(counts.values()))
return entropy(values, base=2)
def variance_of_proportions(counts):
total = sum(counts.values())
proportions = [count / total for count in counts.values()]
return np.var(proportions)
def imbalance_ratio(counts):
values = list(counts.values())
return max(values) / min(values)
def coefficient_of_variation(counts):
values = np.array(list(counts.values()))
return np.std(values) / np.mean(values)
# !pip install hdbscan
from collections import Counter
import hdbscan
import matplotlib.pyplot as plt
unclustered_ratio = []
n_clusters = []
ginis = []
entropies = []
K = range(5, 100)
for k in K:
cluster = hdbscan.HDBSCAN(
min_cluster_size=k,
metric='euclidean',
cluster_selection_method='eom').fit(tsne_embeddings)
cluster_counter = Counter(list(cluster.labels_))
unclustered_ratio.append(cluster_counter[-1]/tsne_embeddings.shape[0])
n_clusters.append(len(cluster_counter)-1)
ginis.append(gini_coefficient(cluster_counter))
entropies.append(calculate_entropy(cluster_counter))
print(k, end=" ")
plt.figure(figsize=(16, 4), dpi=150)
plt.plot(K, [r*100 for r in unclustered_ratio], 'bx-')
plt.plot(K, n_clusters, 'rx-')
plt.plot(K, ginis, 'gx-', label="gini")
plt.plot(K, [e*10 for e in entropies], 'kx-', label="entropy")
plt.xlabel('k')
plt.ylabel('uncluster_rate')
plt.show()
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

plt.figure(figsize=(16, 4), dpi=150)
plt.plot(K, [u*100 for u in unclustered_ratio], 'bx-')
plt.plot(K, n_clusters, 'rx-')
plt.plot(K, ginis, 'gx-', label="gini")
plt.plot(K, [e*10 for e in entropies], 'kx-', label="entropy")
plt.axvline(x=16, color='r', linestyle='--')
plt.xlabel('k')
plt.ylabel('uncluster_rate')
plt.show()

# !pip install hdbscan
import hdbscan
from collections import Counter
cluster = hdbscan.HDBSCAN(
min_cluster_size= 16,
metric='euclidean',
cluster_selection_method='eom').fit(tsne_embeddings)
df['cluster'] = list(cluster.labels_)
print(df.columns)
print(Counter(df['cluster']))
Index(['tag', 'text', 'token_text', 'cleaned', 'cluster'], dtype='object')
Counter({13: 4144, -1: 425, 11: 409, 6: 214, 12: 201, 4: 154, 1: 141, 10: 128, 9: 116, 8: 115, 7: 100, 2: 84, 3: 61, 0: 54, 5: 42})
df
tag | text | token_text | cleaned | cluster | |
---|---|---|---|---|---|
0 | P | 店家很給力,快遞也是相當快,第三次光顧啦 | [店家, 很, 給力, ,, 快遞, 也, 是, 相當快, ,, 第三次, 光顧, 啦] | [店家, 給力, 快遞, 相當快, 第三次, 光顧] | 11 |
1 | N | 這樣的配置用Vista系統還是有點卡。 指紋收集器。 沒送原裝滑鼠還需要自己買,不太好。 | [這樣, 的, 配置, 用, Vista, 系統, 還是, 有點, 卡, 。, , 指紋,... | [配置, Vista, 系統, 有點, 卡, 指紋, 收集器, 沒送, 原裝, 滑鼠, 需要... | 11 |
2 | P | 不錯,在同等檔次酒店中應該是值得推薦的! | [不錯, ,, 在, 同等, 檔次, 酒店, 中應, 該, 是, 值得, 推薦, 的, !] | [不錯, 同等, 檔次, 酒店, 中應, 值得, 推薦] | 4 |
3 | N | 哎! 不會是蒙牛乾的吧 嚴懲真凶! | [哎, !, , 不會, 是, 蒙牛, 乾, 的, 吧, , 嚴懲, 真凶, !] | [蒙牛, 乾, 嚴懲, 真凶] | 9 |
4 | N | 空尤其是三立電視臺女主播做的序尤其無趣像是硬湊那麼多字 | [空, 尤其, 是, 三立, 電視, 臺, 女主播, 做, 的, 序, 尤其, 無趣, 像是... | [空, 尤其, 三立, 電視, 臺, 女主播, 做, 序, 尤其, 無趣, 像是, 硬, 湊... | 11 |
... | ... | ... | ... | ... | ... |
6383 | P | 價效比高、記憶體大、功能全,螢幕超清晰 | [價效, 比高, 、, 記憶體, 大, 、, 功能, 全, ,, 螢幕超, 清晰] | [價效, 比高, 記憶體, 功能, 全, 螢幕超, 清晰] | 6 |
6384 | N | 你太狠了… 告訴你他們不會喧譁的人,肯定是蒙牛喝多了 | [你, 太狠, 了, …, , 告訴, 你, 他們, 不會, 喧, 譁, 的, 人, ,,... | [太狠, 告訴, 喧, 譁, 人, 肯定, 蒙牛, 喝多] | 11 |
6385 | N | 醫生居然買了蒙牛,我是喝呢還是不喝呢還是不喝呢? | [ , 醫生, 居然, 買, 了, 蒙牛, ,, 我, 是, 喝, 呢, 還是, 不, 喝,... | [醫生, 買, 蒙牛, 喝, 喝, 喝] | 11 |
6386 | N | 我只想說 夾蒙牛是不對的 販賣毒品是犯罪行為 | [我, 只, 想, 說, , 夾, 蒙牛, 是, 不, 對, 的, , 販賣, 毒品, ... | [只, 想, 說, 夾, 蒙牛, 販賣, 毒品, 犯罪, 行為] | 11 |
6387 | P | 蒙牛便宜 | [蒙牛, 便宜] | [蒙牛, 便宜] | 11 |
6388 rows × 5 columns
Plotting#
import matplotlib.pyplot as plt
# Prepare data
# Reduce original data to two dimensions
umap_data = umap.UMAP(
n_neighbors=10,
n_components=2,
min_dist=0.0,
metric='euclidean').fit_transform(X)
# Combine x and y and cluster label
result = pd.DataFrame(umap_data, columns=['x', 'y'])
result['labels'] = cluster.labels_
# Visualize clusters
fig, ax = plt.subplots(figsize=(20, 10))
outliers = result.loc[result.labels == -1, :]
clustered = result.loc[result.labels != -1, :]
plt.scatter(outliers.x, outliers.y, color='#BDBDBD', s=5, alpha=0.3)
plt.scatter(clustered.x, clustered.y, c=clustered.labels, s=5, alpha=0.5, cmap='hsv_r')
plt.colorbar()
<matplotlib.colorbar.Colorbar at 0x7fdbb8379880>

import unicodedata # for removing Chinese puctuation
# !wget https://github.com/P4CSS/PSS/raw/master/data/stopwords_zh-tw.txt -O stopwords_zh-tw.txt
def remove_stopWords(words):
with open("stopwords_zh-tw.txt", encoding="utf-8") as fin:
stopwords = fin.read().split("\n")[1:]
out = []
for word in words:
if word not in stopwords:
out.append(word)
return out
def remove_punc_by_unicode(words):
out = []
for word in words:
if word != " " and not unicodedata.category(word[0]).startswith('P'):
out.append(word)
return out
df['cleaned'] = df['token_text'].apply(remove_punc_by_unicode).apply(remove_stopWords)
from collections import defaultdict, Counter
clu_counter = Counter(df['cluster'])
cdict = defaultdict(Counter)
for k, v in zip(df['cluster'], df['cleaned']):
for word in v:
cdict[k][word] += 1
for c in cdict:
print("-"*80)
print("Cluster", c, "has", clu_counter[c], "members")
print(cdict[c].most_common(20))
--------------------------------------------------------------------------------
Cluster 13 has 4144 members
[('蒙牛', 1315), ('好', 743), ('不錯', 584), ('買', 415), ('喝', 290), ('說', 274), ('感覺', 253), ('酒店', 228), ('房間', 218), ('喜歡', 181), ('後', 180), ('系統', 172), ('價效', 172), ('外觀', 171), ('價格', 170), ('書', 167), ('太', 163), ('方便', 156), ('人', 156), ('有點', 149)]
--------------------------------------------------------------------------------
Cluster 6 has 214 members
[('好', 52), ('不錯', 36), ('有點', 25), ('買', 23), ('酒店', 20), ('價格', 20), ('說', 19), ('感覺', 16), ('後', 14), ('配置', 14), ('螢幕', 13), ('問題', 12), ('小', 12), ('時間', 11), ('一個', 11), ('房間', 10), ('系統', 10), ('方便', 10), ('速度', 10), ('驅動', 10)]
--------------------------------------------------------------------------------
Cluster 11 has 409 members
[('好', 55), ('買', 51), ('酒店', 47), ('不錯', 46), ('房間', 45), ('說', 44), ('書', 35), ('不好', 27), ('感覺', 26), ('後', 25), ('太', 24), ('人', 23), ('系統', 21), ('方便', 18), ('差', 16), ('一個', 16), ('小', 16), ('住', 16), ('價格', 15), ('有點', 15)]
--------------------------------------------------------------------------------
Cluster 2 has 84 members
[('好', 34), ('不錯', 18), ('價效', 11), ('配置', 11), ('散熱', 10), ('說', 10), ('系統', 9), ('外觀', 9), ('高', 9), ('鍵盤', 9), ('價格', 9), ('有點', 8), ('螢幕', 8), ('速度', 7), ('硬碟', 6), ('記憶體', 6), ('好看', 5), ('品牌', 5), ('設計', 5), ('顯示', 4)]
--------------------------------------------------------------------------------
Cluster 8 has 115 members
[('好', 25), ('蒙牛', 17), ('系統', 14), ('買', 14), ('不錯', 10), ('還不錯', 9), ('有點', 9), ('一個', 8), ('價廉', 8), ('物美', 8), ('XP', 7), ('人', 7), ('服務', 7), ('說', 6), ('找', 6), ('驅動', 6), ('速度', 6), ('不好', 6), ('東西', 6), ('小', 5)]
--------------------------------------------------------------------------------
Cluster 1 has 141 members
[('蒙牛', 65), ('好', 21), ('買', 15), ('說', 14), ('喝', 12), ('喜歡', 11), ('書', 11), ('不錯', 10), ('牛奶', 7), ('味道', 6), ('系統', 6), ('一個', 6), ('好吃', 6), ('知道', 6), ('價格', 5), ('電池', 5), ('不到', 5), ('香蕉', 5), ('再', 5), ('這本書', 5)]
--------------------------------------------------------------------------------
Cluster 9 has 116 members
[('蒙牛', 52), ('買', 14), ('書', 14), ('說', 9), ('好', 8), ('送', 7), ('後', 7), ('支援', 7), ('收到', 6), ('一個', 5), ('喜歡', 5), ('一本', 5), ('時', 5), ('沒什麼', 5), ('太', 5), ('不錯', 5), ('最', 4), ('好喝', 4), ('現在', 4), ('系統', 4)]
--------------------------------------------------------------------------------
Cluster 12 has 201 members
[('好', 32), ('買', 27), ('說', 21), ('不錯', 18), ('蒙牛', 18), ('書', 15), ('問題', 12), ('一個', 11), ('系統', 10), ('挺', 10), ('太', 10), ('喜歡', 10), ('後', 9), ('酒店', 9), ('不好', 9), ('功能', 9), ('差', 8), ('知道', 8), ('質量', 8), ('有點', 8)]
--------------------------------------------------------------------------------
Cluster -1 has 425 members
[('好', 70), ('蒙牛', 68), ('不錯', 52), ('支援', 38), ('功能', 32), ('酒店', 27), ('說', 21), ('房間', 21), ('感覺', 18), ('時間', 18), ('外觀', 17), ('買', 17), ('比較', 17), ('差', 17), ('效果', 16), ('系統', 16), ('鍵盤', 15), ('太', 15), ('有點', 14), ('問題', 14)]
--------------------------------------------------------------------------------
Cluster 10 has 128 members
[('不錯', 59), ('好', 42), ('酒店', 39), ('房間', 38), ('服務', 20), ('方便', 17), ('外觀', 17), ('環境', 15), ('設施', 15), ('早餐', 13), ('價效', 12), ('功能', 12), ('比較', 12), ('交通', 11), ('舊', 11), ('高', 11), ('效果', 10), ('價格', 9), ('入住', 8), ('螢幕', 7)]
--------------------------------------------------------------------------------
Cluster 0 has 54 members
[('好', 39), ('不錯', 20), ('外觀', 14), ('價效', 11), ('服務', 9), ('漂亮', 9), ('價格', 8), ('速度', 7), ('挺', 7), ('東西', 6), ('做工', 5), ('質量', 5), ('賣家', 5), ('周到', 5), ('房間', 5), ('還不錯', 4), ('水器', 4), ('高', 4), ('時尚', 4), ('方便', 4)]
--------------------------------------------------------------------------------
Cluster 5 has 42 members
[('不錯', 19), ('好', 12), ('外觀', 9), ('滿意', 8), ('配置', 8), ('價格', 7), ('漂亮', 6), ('房間', 5), ('服務', 5), ('本本', 4), ('方便', 4), ('質量', 4), ('效果', 4), ('合理', 4), ('功能', 4), ('效能', 4), ('價效', 4), ('喜歡', 3), ('感覺', 3), ('很快', 3)]
--------------------------------------------------------------------------------
Cluster 7 has 100 members
[('蒙牛', 18), ('不好', 10), ('買', 10), ('書', 10), ('好', 10), ('太', 7), ('人', 7), ('支援', 7), ('抵制', 7), ('月', 6), ('時間', 6), ('不錯', 5), ('知道', 5), ('房間', 5), ('差', 5), ('待機', 5), ('噹噹', 5), ('說', 4), ('手機', 4), ('電池', 4)]
--------------------------------------------------------------------------------
Cluster 4 has 154 members
[('功能', 43), ('螢幕', 42), ('效果', 42), ('支援', 30), ('好', 29), ('顯示', 27), ('外觀', 18), ('手感', 18), ('不錯', 18), ('鍵盤', 16), ('做工', 15), ('速度', 15), ('設計', 14), ('鈴聲', 12), ('能力', 12), ('出色', 12), ('電池', 12), ('色彩', 10), ('小', 10), ('時間', 10)]
--------------------------------------------------------------------------------
Cluster 3 has 61 members
[('好', 17), ('螢幕', 17), ('外觀', 8), ('支援', 7), ('比較', 7), ('不錯', 7), ('電池', 7), ('價效', 6), ('鍵盤', 6), ('還不錯', 5), ('配置', 5), ('時間', 5), ('速度', 5), ('方便', 4), ('實用', 4), ('一個', 4), ('寬', 4), ('待機', 4), ('機器', 4), ('比高', 4)]
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Number of columns for subplots
num_columns = 4
# Total number of clusters
num_clusters = len(clu_counter) - 1
# Calculate the number of rows needed
num_rows = num_clusters // num_columns + (num_clusters % num_columns > 0)
# Create a figure with subplots
plt.figure(figsize=(6 * num_columns, 4 * num_rows), dpi=150)
for clu in range(num_clusters):
# Create a subplot in the appropriate grid position
plt.subplot(num_rows, num_columns, clu + 1)
# Create a DataFrame for the current cluster
df1 = pd.DataFrame(list(cdict[clu].most_common(20)), columns=['word', 'n'])
# Sort the data
df_data = df1.sort_values('n', ascending=False)
# Plot the data
sns.barplot(x='n', y='word', data=df_data, label='word', color='royalblue')
# Optionally, add a title for each subplot
plt.title(f"Cluster {clu}")
# Adjust the layout
plt.tight_layout()
plt.show()

"""
import seaborn as sns
for clu in range(len(clu_counter)-1):
df1 = pd.DataFrame(list(cdict[clu].most_common(20)), columns = ['word', 'n'])
plt.figure(figsize=(6, 4), dpi=150)
df_data = df1.sort_values('n', ascending=False)
# print(df_data)
sns.barplot(x='n',
y='word',
data=df_data,
label='word',
color='royalblue',
)
"""
"\nimport seaborn as sns\nfor clu in range(len(clu_counter)-1):\n df1 = pd.DataFrame(list(cdict[clu].most_common(20)), columns = ['word', 'n'])\n plt.figure(figsize=(6, 4), dpi=150) \n df_data = df1.sort_values('n', ascending=False)\n# print(df_data)\n sns.barplot(x='n', \n y='word', \n data=df_data, \n label='word', \n color='royalblue',\n )\n"