Scikit-learn 中可重现的 LDA 模型

raj*_*rgp 1 python lda scikit-learn

我正在使用 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)
Run Code Online (Sandbox Code Playgroud)

'''


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

或者,LDA 不可重现。

如何使其可重现..?

Viv*_*mar 5

为了在 scikit 中实现可重复性,请random_state在代码中看到的任何位置设置参数。

就你而言,它的LatentDirichletAllocation(...)

用这个:

lda_model = LatentDirichletAllocation(n_topics=NUM_TOPICS, 
                                      max_iter=10,  
                                      learning_method='online'
                                      random_state = 42)
Run Code Online (Sandbox Code Playgroud)

检查此链接:

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

import numpy as np
np.random.seed(42)
Run Code Online (Sandbox Code Playgroud)

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