到目前为止,我已经计算出一个主题模型。
首先,我的数据框如下所示:
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))
有帮助吗?谢谢!
答案 0 :(得分:1)
如果数据框长为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
熊猫应该意识到您要执行的操作并应用数据。
您可能不得不去弄乱结果数组的维度,但是只要正确,熊猫就应该管理细节。