簡體   English   中英

LDA主題建模輸入數據

[英]LDA topic modeling input data

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

我知道這有點晚了,但希望它有所幫助。您首先必須了解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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM