sklearn: 利用TruncatedSVD做文本主题分析

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("	"+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

原文地址:https://www.cnblogs.com/jimlau/p/13590220.html