python - 获取每个主题的最可能单词
问题描述
我制作了一个 LDA 模型,sklearn
但听起来很奇怪,我在网上找不到任何关于如何获得热门词的信息。这是我的代码:
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
doc_term_matrix = count_vect.fit_transform(tweet_tp['text'].values.astype('U'))
doc_term_matrix
from sklearn.decomposition import LatentDirichletAllocation
LDA = LatentDirichletAllocation(n_components=3, random_state=1)
id_topic = LDA.fit(doc_term_matrix)
一旦我添加了这个:
import numpy as np
vocab = count_vect.get_feature_names()
topic_words = {}
for topic, comp in enumerate(LDA.components_):
word_idx = np.argsort(comp)[::-1][:5]
topic_words[topic] = [vocab[i] for i in word_idx]
for topic, words in topic_words.items():
print('Topic: %d' % topic)
print(' %s' % ', '.join(words))
我在这里找到了答案,但目前找不到。但是,这仅输出第二个主题词。
解决方案
您可以像这样使用 ntopwlst:
from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
doc_term_matrix = count_vect.fit_transform(tweet_tp['text'].values.astype('U'))
from sklearn.decomposition import LatentDirichletAllocation
LDA = LatentDirichletAllocation(n_components=3, random_state=1)
id_topic = LDA.fit(doc_term_matrix)
def ntopwlst(model, features, ntopwords):
'''create a list of the top topc words'''
output = []
for topic_idx, topic in enumerate(model.components_): # compose output message with top words
output.append(str(topic_idx))
output += [features[i] for i in topic.argsort()[:-ntopwords - 1:-1]] # [start (0 if omitted): end : slicing increment]
return output
ntopwords = 5 # change this to show more words for the topic selector (20)
tf_feature_names = count_vect.get_feature_names()
topwds = ntopwlst(LDA, tf_feature_names, ntopwords)
您确实提取了词汇表,但这比直接处理 LDA 结果更容易。由于缺乏数据,因此无法对此进行测试,tweet_tp
因此请谨慎使用。
推荐阅读
- ms-access - 保护 Access 前端的建议
- c++ - 如何在字符串 C++ 中用“aaa”替换字符“a”?
- tensorflow - Tensorflow 中 Tensor 先前条目的平均值
- c - 灵活的数组成员,不必是最后一个
- javascript - 如何正确地将数组中的所有元素替换为其位置?
- macos - ssh 访问 azure debian vm 突然停止
- python - 使用 Pandas 进行数据清理:将“(2.34M)”替换为“-2340000”(将带大小符号的括号中的负数转换为不带括号的浮点/整数)
- automation - 使用 configFile 断言文本数据
- docker-gen - docker-gen 中的 docker 容器元数据是什么?
- css - Material UI 自定义工具提示三角形