【问题标题】:How to create for loop in Python for LDA model如何在 Python 中为 LDA 模型创建 for 循环
【发布时间】:2017-04-26 23:44:49
【问题描述】:

我需要一些帮助来在 Python 中创建一个 for 循环。我是一个完整的编码新手。请指出正确的方向。

这是我到目前为止所做的。我已经使用 Twitter API 流式传输了 1000 条关于某个主题的推文。然后我使用 lda 模型找到了前 3 个主题。

现在我需要通过下面的代码遍历文档(推文),其中 x 等于文档编号(0 到 999),以获取每个文档的主题分布。 ldamodel.get_document_topics(语料库[x]) 有人可以为我指出如何制定循环的正确方向吗?

到目前为止,这是我的猜测:

使用此代码提取推文(不完整):

def get_tweets(input_query):
    consumer_key = "x"
    consumer_secret = "x"
    access_token = "x"
    access_token_secret = "x"
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    return tweepy.Cursor(api.search, q=input_query, lang="en").items()

input_queries = ['Tornado']
tweets = {}
dataset = defaultdict(list)
for input_query in input_queries:
    tweets = get_tweets(input_query)
    download_tweet_count = 1000
    print(input_query)
    counter = 0
    ....

    ....
ldamodel = models.ldamodel.LdaModel(corpus, num_topics=3, id2word = 
dictionary, passes=20)

counter = 0
for x in download_tweet_count:
while counter < x:
    try:
        ldamodel.get_document_topics(corpus[x])

我需要使用 ldamodel.get_document_topics(corpus[x]) 在每个文档(推文)上运行模型,然后将该推文分配给主题匹配概率最高的主题。我相信我可以使用数据框或单独的列表来存储分配。我不知道“数据框”是什么意思。

【问题讨论】:

标签: python lda


【解决方案1】:

这是我的代码的 sn-p,我通常如何创建矩阵来执行 LDA。

# loop through the feature and construct the feature array  
features_size = len(features.items()) 

X = []  #np.ndarray. This is what we are going to put in LDA module.

for i in TweetFeatures.items(): # TweetFeatures is words that appeared in your tweet
    current_vector = np.array([0]*features_size) 
    for j in i[1]: # TweetFeatures key is your tweet ID and value is array of words. (This depends on how you define them)
        if j in map_id_2_index:
            current_vector[map_id_2_index[j]] = 1
    X.append(current_vector) 
X=np.array(X) # document-term matrix
X=X[~np.all(X == 0, axis=1)] # remove all zero line
print("type(X): {}".format(type(X)))
print("shape: {}\n".format(X.shape)) 

####################################
#### LDA MODELLING #################
####################################
model = lda.LDA(n_topics=5, n_iter=1000, random_state=1)
model.fit(X)

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 2017-01-05
    • 2020-09-16
    相关资源
    最近更新 更多