Scikit-learn中可重复的LDA模型

时间:2018-05-21 09:55:13

标签: python scikit-learn lda

我正在使用LDA进行主题建模。

来自sklearn.decomposition导入LatentDirichletAllocation

使用一组10个文件,我制作了模型。现在,我尝试将其聚为3个。

类似于以下内容:

'''

import numpy as np  
data = []
a1 = " a word in groupa doca"
a2 = " a word in groupa docb"
a3 = "a word in groupb docc"
a4 = "a word in groupc docd"
a5 ="a word in groupc doce"
data = [a1,a2,a3,a4,a5]
del a1,a2,a3,a4,a5

NO_DOCUMENTS = len(data)
print(NO_DOCUMENTS)


from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer

NUM_TOPICS = 2

vectorizer = CountVectorizer(min_df=0.001, max_df=0.99998, 
                         stop_words='english', lowercase=True, 
                         token_pattern='[a-zA-Z\-][a-zA-Z\-]{2,}')
data_vectorized = vectorizer.fit_transform(data)

# Build a Latent Dirichlet Allocation Model
lda_model = LatentDirichletAllocation(n_topics=NUM_TOPICS, 
   max_iter=10, learning_method='online')
lda_Z = lda_model.fit_transform(data_vectorized)

vocab = vectorizer.get_feature_names()  
text = "The economy is working better than ever"
x = lda_model.transform(vectorizer.transform([text]))[0]
print(x, x.sum())

for iDocIndex,text in enumerate(data):            
    x = list(lda_model.transform(vectorizer.transform([text]))[0])
    maxIndex = x.index(max(x))            
    if TOPICWISEDOCUMENTS[maxIndex]:
        TOPICWISEDOCUMENTS[maxIndex].append(iDocIndex) 
    else:
        TOPICWISEDOCUMENTS[maxIndex] = [iDocIndex]    



 print(TOPICWISEDOCUMENTS)

'''

每当我运行系统时,即使对于同一组输入数据,我也会得到不同的集群。

或者,LDA不可再现。

如何使其重现......?

2 个答案:

答案 0 :(得分:4)

为了在scikit中重现性,请在代码中看到的任何位置设置random_state param。

在您的情况下,LatentDirichletAllocation(...)

使用此:

lda_model = LatentDirichletAllocation(n_topics=NUM_TOPICS, 
                                      max_iter=10,  
                                      learning_method='online'
                                      random_state = 42)

检查此链接:

如果您想让整个脚本重现并且不想搜索放置random_state的位置,则可以设置全局numpy随机种子。

import numpy as np
np.random.seed(42)

请参阅:http://scikit-learn.org/stable/faq.html#how-do-i-set-a-random-state-for-an-entire-execution

答案 1 :(得分:0)

lda_model = LatentDirichletAllocation(n_topics=NUM_TOPICS, 
                                      max_iter=10,  
                                      learning_method='online'
                                      random_state = 42) 

工作...... !!!

非常感谢

另外,我曾尝试过这个

import numpy as np
np.random.seed(42)

但它没有效果。

感谢您的决议