首页 > 解决方案 > 如何从主题建模中制作主题百分比条形图?

问题描述

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

我想要

  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()

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

标签: pythonpandasmatplotlibscikit-learn

解决方案


IIUC,您要绘制条形字符,因此不要将主题更改为列表:

topics = pd.DataFrame(W).idxmax(axis=1, skipna=True)

plt.bar(x=topics.index, height=topics.mul(100)/topics.sum())
plt.show()

给出:

在此处输入图像描述


推荐阅读