sklearn: 利用TruncatedSVD做文本主題分析
利用一個demo學習使用TruncatedSVD做文本主題分析。 通過主題分析,我們可以得到一個語料中的關鍵主題,即各個詞語在主題中的重要程度,各個文章在各個主題上的傾向程度。並且可以根據它們,得到主題對應的關鍵詞以及代表性文本。
1、使用TF-IDF對文本進行預處理,將文本化為向量的表示形式
TfidfVectorizer的基本用法以及對中文的處理可以見我之前的一篇博文 https://www.cnblogs.com/jimlau/p/13589908.html
from sklearn.decomposition import TruncatedSVD # namely LSA/LSI(即潛在語義分析)
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
# ♪ Until the Day ♪ by JJ Lin 林俊傑
docs = ["In the middle of the night",
"When our hopes and fears collide",
"In the midst of all goodbyes",
"Where all human beings lie",
"Against another lie"]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(docs)
terms = vectorizer.get_feature_names()
print(terms)
#['against', 'all', 'and', 'another', 'beings', 'collide', 'fears', 'goodbyes', 'hopes', 'human', 'in', 'lie', 'middle', 'midst', 'night', 'of', 'our', 'the', 'when', 'where']
2、使用TruncatedSVD,把原先規模為(文本數,詞匯數)的特征矩陣X化為規模為(文本數,主題數)的新特征矩陣X2:
(由於主題數一般比詞匯數少,這一方法也可以用來降維,以進行分類或聚類操作)
n_pick_topics = 3 # 設定主題數為3
lsa = TruncatedSVD(n_pick_topics)
X2 = lsa.fit_transform(X)
print(X2)
#輸出結果
#array([[ 8.26629804e-01, -2.46905901e-01, -0.00000000e+00],
# [ 4.66516068e-16, 8.40497045e-16, 1.00000000e+00],
# [ 8.66682085e-01, -9.09029610e-02, -1.11022302e-16],
# [ 2.80099067e-01, 7.28669961e-01, -6.38342104e-16],
# [ 1.03123637e-01, 7.63975842e-01, -4.43944669e-16]])
X2[i,t]為第i篇文檔在第t個主題上的分布,所以該值越高的文檔i,可以認為在主題t上更有代表性,我們便以此篩選出最能代表該主題的文檔。
我們可以通過如下方法篩選出文檔,該方法為每個主題篩選了兩篇最具有代表性的文檔。
n_pick_docs= 2
topic_docs_id = [X2[:,t].argsort()[:-(n_pick_docs+1):-1] for t in range(n_pick_topics)]
print(topic_docs_id)
除此之外,lsa.components_是一個大小為(T,V),每一行為主題在每個單詞上的分布。我們可以通過這個矩陣得到哪些詞對主題t貢獻最大。下面這段代碼為每個主題選取了4個關鍵字。
n_pick_keywords = 4
topic_keywords_id = [lsa.components_[t].argsort()[:-(n_pick_keywords+1):-1] for t in range(n_pick_topics)]
print(topic_keywords_id)
print(lsa.components_)
則根據以下方式,我們可以找出每個主題對應文檔,和關鍵詞
for t in range(n_pick_topics):
print("topic %d:" % t)
print(" keywords: %s" % ", ".join(terms[topic_keywords_id[t][j]] for j in range(n_pick_keywords)))
for i in range(n_pick_docs):
print(" doc %d" % i)
print("\t"+docs[topic_docs_id[t][i]])
#topic 0:
# keywords: the, of, in, all
# doc 0
# In the midst of all goodbyes
# doc 1
# In the middle of the night
#topic 1:
# keywords: lie, another, against, beings
# doc 0
# Against another lie
# doc 1
# Where all human beings lie
#topic 2:
# keywords: and, when, our, collide
# doc 0
# When our hopes and fears collide
# doc 1
# Where all human beings lie
我們找到的是,3個主題,每個主題有4個關鍵詞,2個代表性文檔
參考文檔: https://blog.csdn.net/blmoistawinde/article/details/83446529
