我使用python gensim从231个句子的小语料库中训练一个潜在的Dirichlet分配(LDA)模型。然而,每次我重复这个过程,都会产生不同的主题。
为什么每次都使用相同的LDA参数和语料库生成不同的主题?
和如何稳定主题生成?
我正在使用这个语料库(http://pastebin.com/WptkKVF0)和这个停止词列表(http://pastebin.com/LL7dqLcj),下面是我的代码:
from gensim import corpora, models, similarities
from gensim.models import hdpmodel, ldamodel
from itertools import izip
from collections import defaultdict
import codecs, os, glob, math
stopwords = [i.strip() for i in codecs.open('stopmild','r','utf8').readlines() if i[0] != "#" and i != ""]
def generateTopics(corpus, dictionary):
# Build LDA model using the above corpus
lda = ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=50)
corpus_lda = lda[corpus]
# Group topics with similar words together.
tops = set(lda.show_topics(50))
top_clusters = []
for l in tops:
top = []
for t in l.split(" + "):
top.append((t.split("*")[0], t.split("*")[1]))
top_clusters.append(top)
# Generate word only topics
top_wordonly = []
for i in top_clusters:
top_wordonly.append(":".join([j[1] for j in i]))
return lda, corpus_lda, top_clusters, top_wordonly
#######################################################################
# Read textfile, build dictionary and bag-of-words corpus
documents = []
for line in codecs.open("./europarl-mini2/map/coach.en-es.all","r","utf8"):
lemma = line.split("\t")[3]
documents.append(lemma)
texts = [[word for word in document.lower().split() if word not in stopwords]
for document in documents]
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
lda, corpus_lda, topic_clusters, topic_wordonly = generateTopics(corpus, dictionary)
for i in topic_wordonly:
print i发布于 2013-02-25 14:44:31
为什么相同的LDA参数和语料库每次都会产生不同的主题?
因为LDA在训练和推理过程中都使用了随机性。
以及如何稳定主题生成?
通过每次训练模型或执行推理时将numpy.random种子重置为相同的值,使用numpy.random.seed
SOME_FIXED_SEED = 42
# before training/inference:
np.random.seed(SOME_FIXED_SEED)(这是丑陋的,它使Gensim的结果难以复制;请考虑提交一个补丁。我已经打开了一个issue。)
发布于 2018-06-25 05:57:45
在初始化random_state ()方法时设置LdaModel参数。
lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
id2word=id2word,
num_topics=num_topics,
random_state=1,
passes=num_passes,
alpha='auto')发布于 2017-01-21 03:56:12
我也有同样的问题,即使有大约5万条评论。但是,通过增加LDA运行的迭代次数,可以获得更一致的主题。它最初被设置为50,当我把它提高到300时,它通常给出相同的结果,可能是因为它更接近收敛。
具体来说,您只需添加以下选项:
ldamodel.LdaModel(corpus, ..., iterations = <your desired iterations>):https://stackoverflow.com/questions/15067734
复制相似问题