将主题分布(主题模型的结果)添加到pandas数据帧中



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

首先,我的数据帧看起来是这样的:

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

有什么帮助吗?非常感谢。

如果你的数据帧是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就应该管理细节。

最新更新