gpt4 book ai didi

python - 如何通过主题建模制作主题的百分比条形图?

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:42 25 4
gpt4 key购买 nike

我已经为此绞尽脑汁一个星期了。

我想要

  1. 运行 NMF 主题建模
  2. 通过查看最大权重为每个文档分配一个主题,
  3. 使用 matplot 将此分布绘制为百分比条形图。 (即:X 轴上的主题,y 轴上该主题的文档百分比。)

这里是一些玩具数据并完成步骤 1 和 2:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF
import pandas as pd

# Get data
data = {
"Documents": ["I am a document",
"And me too",
"The cat is big",
"The dog is big"
"My headphones are large",
"My monitor has rabies",
"My headphones are loud"
"The street is loud "]
}

df = pd.DataFrame(data)

# Fit a TFIDF vectorizer
tfidf_vectorizer = TfidfVectorizer()
tfidf = tfidf_vectorizer.fit_transform(df['Documents'])

# Run NMF
nmf_model = NMF(n_components=4, random_state=1).fit(tfidf)

# Weights
W = nmf_model.transform(tfidf)

# Topics
H= nmf_model.components_

现在这是我如何将文档分配给主题:

# Will return document topics as list like [1, 4, 1...] to 
# represent that the first document is topic 1, the second 4, and so on.
topics = pd.DataFrame(W).idxmax(axis=1, skipna=True).tolist()

好吧,现在我应该能够通过这两个结构得到我想要的东西,但我不知所措。

最佳答案

看起来像是 Counter() 的一个用例。我会写这样的东西:

from collections import Counter

mylist = [1,1,1,1,2,2,3,1,1,2,3,1,1,1]
mycount = Counter(mylist)
for key,value in mycount.items():
print(key,value)

这会按以下结构输出您的主题:

1 9
2 3
3 2

潜在狄利克雷/非负矩阵需要注意的一点是,整个点是一个句子是由多个主题组成的。最大化将每个主题分配给单个主题的权重可能会达不到目的。您可能还需要考虑如何处理无意义的句子,因为您的算法当前会自动将它们分配给主题。

关于python - 如何通过主题建模制作主题的百分比条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56995391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com