首页 > 解决方案 > 将主题分布(主题模型的结果)添加到熊猫数据框

问题描述

我计算了一个主题模型,到目前为止还不错。

首先,我的数据框如下所示:

identifier     comment_cleaned
1              some cleaned comment
2              another cleaned comment
8              
...            ...

然后我像这样计算我的模型:

import lda
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer

def remove_allzerorows(smatrix):
    nonzero_row_indice, _ = smatrix.nonzero()
    unique_nonzero_indice = np.unique(nonzero_row_indice)
    return smatrix[unique_nonzero_indice]

univectorizer = CountVectorizer(analyzer = "word", min_df = 0.001, ngram_range = (1,1)) 
unicorpus = univectorizer.fit_transform(df["comment_cleaned"])
unicorpus = remove_allzerorows(unicorpus)
unigrams = univectorizer.get_feature_names()

n_topics = [2, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 110, 120]
n_iter = 2000
alpha = 0.1
beta = 0.01

for topics in n_topics:
    print("start with number of topics:", topics)
    lda_model = lda.LDA(
                    n_topics = topics, n_iter = n_iter,
                    alpha = alpha, eta = beta,
                    random_state = 42
                   )
    lda_model.fit(unicorpus)
    joblib.dump(lda_model, f"models/lda_{topics}topics.pkl") 

之后,我评估了主题并选择了最能代表我的数据集的主题数量。这是80个主题。现在我想做的是:向我的数据框中添加 80 列代表主题分布。最后它看起来像这样:

identifier     comment_cleaned          topic_1      topic_2     ...
1              some cleaned comment     0.11         0.0         ...
2              another cleaned comment  0.30         0.1         ...
8                                       0.00         0.0         ...
...            ...                      ...          ...         ...

基本上我了解如何创建文档主题矩阵。但我不知道如何用这个附加我的初始数据框:

best_lda_model = joblib.load(f"models/lda_80topics.pkl")
lda_output = best_lda_model.transform(unicorpus)
df_document_topic = pd.DataFrame(np.round(lda_output, 2))

有什么帮助吗?谢谢!

标签: pythonpandastopic-modeling

解决方案


如果您的数据框有 N 行长,并且您有一个矩阵 M,NxT其中 T 是主题数 - 那么要将此矩阵添加到数据框,您需要做的就是生成一个 T 字符串列表以用作您的新列名 - 也许像:

new_column_names = ["topic_{t}".format(t=t) for t in range(0,M.shape[1])]

然后,您可以像这样简单地将矩阵值插入数据框中:

df_document_topic[new_column_names] = M

Pandas 应该意识到您正在尝试做什么并应用数据。

您可能不得不摆弄结果数组的尺寸,但只要它们是正确的,Pandas 就应该管理细节。


推荐阅读