LDA主题建模的输入数据

4

我是 Python 的新手。我刚开始研究如何在推特上使用 LDA 主题建模。我尝试使用以下代码:

这个例子使用的是在线数据集。我有一个包含需要使用的推特的 CSV 文件。有人能告诉我如何使用本地文件吗?我应该如何制作自己的词汇表和标题?

我找不到一篇教程来解释如何为 LDA 准备材料。它们都假定你已经知道如何做了。

from __future__ import division, print_function

import numpy as np
import lda
import lda.datasets


# document-term matrix

X = lda.datasets.load_reuters()
print("type(X): {}".format(type(X)))
print("shape: {}\n".format(X.shape))

# the vocab
vocab = lda.datasets.load_reuters_vocab()
print("type(vocab): {}".format(type(vocab)))
print("len(vocab): {}\n".format(len(vocab)))

# titles for each story
titles = lda.datasets.load_reuters_titles()
print("type(titles): {}".format(type(titles)))
print("len(titles): {}\n".format(len(titles)))


doc_id = 0
word_id = 3117

print("doc id: {} word id: {}".format(doc_id, word_id))
print("-- count: {}".format(X[doc_id, word_id]))
print("-- word : {}".format(vocab[word_id]))
print("-- doc  : {}".format(titles[doc_id]))


model = lda.LDA(n_topics=20, n_iter=500, random_state=1)
model.fit(X)


topic_word = model.topic_word_ 
print("type(topic_word): {}".format(type(topic_word)))
print("shape: {}".format(topic_word.shape))


for n in range(5):
    sum_pr = sum(topic_word[n,:])
    print("topic: {} sum: {}".format(n, sum_pr))


n = 5
for i, topic_dist in enumerate(topic_word):
    topic_words = np.array(vocab)[np.argsort(topic_dist)][:-(n+1):-1]
    print('*Topic {}\n- {}'.format(i, ' '.join(topic_words)))


doc_topic = model.doc_topic_
print("type(doc_topic): {}".format(type(doc_topic)))
print("shape: {}".format(doc_topic.shape))

1个回答

5
我知道我来晚了,但希望这能有所帮助。首先你必须明白,LDA只适用于DTM(文档术语矩阵)。因此,我建议你按照以下步骤操作:
  1. 加载你的csv文件
  2. 从文件中提取必要的推文
  3. 清理数据
  4. 创建一个包含语料库中每个单词的字典
  5. 构建TDM结构
  6. 将结构拟合到你的数据文件
  7. 获取词汇表- TDM特征(单词)
  8. 继续使用上面的代码
这里,我提供一些代码帮助你入门-
token_dict = {}

for i in range(len(txt1)):
    token_dict[i] = txt1[i]

len(token_dict)


print("\n Build DTM")
%time tf = CountVectorizer(stop_words='english')

print("\n Fit DTM")
%time tfs1 = tf.fit_transform(token_dict.values())

# set the number of topics to look for
num = 8

model = lda.LDA(n_topics=num, n_iter=500, random_state=1)

# we fit the DTM not the TFIDF to LDA
print("\n Fit LDA to data set")
%time model.fit_transform(tfs1)

print("\n Obtain the words with high probabilities")
%time topic_word = model.topic_word_  # model.components_ also works

print("\n Obtain the feature names")
%time vocab = tf.get_feature_names()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接