Reputation: 105
I am using LDA for Topic modelling.
from sklearn.decomposition import LatentDirichletAllocation
Using a set of 10 files, I made the model. Now, i try to cluster it into 3.
Similar to below:
'''
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)
'''
Whenever I am running the system, I am getting different cluster even for the same set of input data.
Alternatively, the LDA is not reproducible.
How to make it reproducible .. ?
Upvotes: 1
Views: 1250
Reputation: 105
lda_model = LatentDirichletAllocation(n_topics=NUM_TOPICS,
max_iter=10,
learning_method='online'
random_state = 42)
Worked ...!!!
Thanks a lot
Also, I had tried for this
import numpy as np
np.random.seed(42)
But It is not effective.
Thanks for resolution
Upvotes: 1
Reputation: 36599
For reproducibility in scikit, set random_state
param in anywhere you see in your code.
In your case, its LatentDirichletAllocation(...)
Use this:
lda_model = LatentDirichletAllocation(n_topics=NUM_TOPICS,
max_iter=10,
learning_method='online'
random_state = 42)
Check this link:
If you want to make your whole script reproducible and dont want to search where to put random_state
, you can set a global numpy random seed.
import numpy as np
np.random.seed(42)
See this: http://scikit-learn.org/stable/faq.html#how-do-i-set-a-random-state-for-an-entire-execution
Upvotes: 5