无法在 gensim 中修复 LDA 模型中的种子值
Fails to fix the seed value in LDA model in gensim
使用LDA模型时,我每次得到不同的主题,我想复制同一个集合。我在 Google 中搜索过类似的问题,例如 this.
我按照 num.random.seed(1000)
的文章中所示修复了种子,但它不起作用。我阅读了 ldamodel.py
并找到了以下代码:
def get_random_state(seed):
"""
Turn seed into a np.random.RandomState instance.
Method originally from maciejkula/glove-python, and written by @joshloyal
"""
if seed is None or seed is numpy.random:
return numpy.random.mtrand._rand
if isinstance(seed, (numbers.Integral, numpy.integer)):
return numpy.random.RandomState(seed)
if isinstance(seed, numpy.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)
所以我使用代码:
lda = models.LdaModel(
corpus_tfidf,
id2word=dic,
num_topics=2,
random_state=numpy.random.RandomState(10)
)
但是还是不行。
corpora.Dictionary
生成的字典可能与同一个语料库不同(例如相同的词但顺序不同)。所以应该修复字典和种子以获得每个相同的主题time.The 下面的代码可能有助于修复字典:
dic = corpora.Dictionary(corpus)
dic.save("filename")
dic=corpora.Dictionary.load("filename")
我同意@Marcel.Shen 的观点,您应该通过保存一次并再次使用它而不是每次都重新生成它来将您的输入字典修复为 LDA 模型。这也可能是您得到不同结果的可能原因。
但我认为您得到不同结果的主要原因是您每次 运行 时随机将 random state
设置在 0-10 之间。只需将随机种子值设置为常量,如 1。
使用LDA模型时,我每次得到不同的主题,我想复制同一个集合。我在 Google 中搜索过类似的问题,例如 this.
我按照 num.random.seed(1000)
的文章中所示修复了种子,但它不起作用。我阅读了 ldamodel.py
并找到了以下代码:
def get_random_state(seed):
"""
Turn seed into a np.random.RandomState instance.
Method originally from maciejkula/glove-python, and written by @joshloyal
"""
if seed is None or seed is numpy.random:
return numpy.random.mtrand._rand
if isinstance(seed, (numbers.Integral, numpy.integer)):
return numpy.random.RandomState(seed)
if isinstance(seed, numpy.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)
所以我使用代码:
lda = models.LdaModel(
corpus_tfidf,
id2word=dic,
num_topics=2,
random_state=numpy.random.RandomState(10)
)
但是还是不行。
corpora.Dictionary
生成的字典可能与同一个语料库不同(例如相同的词但顺序不同)。所以应该修复字典和种子以获得每个相同的主题time.The 下面的代码可能有助于修复字典:
dic = corpora.Dictionary(corpus)
dic.save("filename")
dic=corpora.Dictionary.load("filename")
我同意@Marcel.Shen 的观点,您应该通过保存一次并再次使用它而不是每次都重新生成它来将您的输入字典修复为 LDA 模型。这也可能是您得到不同结果的可能原因。
但我认为您得到不同结果的主要原因是您每次 运行 时随机将 random state
设置在 0-10 之间。只需将随机种子值设置为常量,如 1。