I am trying to learn topic modelling using Gensim python library. I have tried so many different tutorials including official one.
Question: How do I get document wise topic distribution using Gensim.
My current output is list of topics with its keywords and probability as shown below.
(0, u'0.086*good + 0.086*brocolli + 0.086*health + 0.061*eat)
(1, u'0.068*mother + 0.068*brother + 0.068*drive + 0.041*pressur)
I would like to know if it is possible to have a list of say each document and top topics for that particular document?
My code is as following:
tokenizer = RegexpTokenizer(r'\w+')
# create English stop words list
en_stop = get_stop_words('en')
# Create p_stemmer of class PorterStemmer
p_stemmer = PorterStemmer()
# create sample documents
doc_a = "Brocolli is good to eat. My brother likes to eat good brocolli, but not my mother."
doc_b = "My mother spends a lot of time driving my brother around to baseball practice."
doc_c = "Some health experts suggest that driving may cause increased tension and blood pressure."
doc_d = "I often feel pressure to perform well at school, but my mother never seems to drive my brother to do better."
doc_e = "Health professionals say that brocolli is good for your health."
# compile sample documents into a list
doc_set = [doc_a, doc_b, doc_c, doc_d, doc_e]
num_topics=2;
# list for tokenized documents in loop
texts = []
# loop through document list
for i in doc_set:
# clean and tokenize document string
raw = i.lower()
tokens = tokenizer.tokenize(raw)
# remove stop words from tokens
stopped_tokens = [i for i in tokens if not i in en_stop]
#print(stopped_tokens)
# stem tokens
stemmed_tokens = [p_stemmer.stem(i) for i in stopped_tokens]
#print("printing stemmed tokens")
#print(stemmed_tokens)
# add tokens to list
texts.append(stemmed_tokens)
# turn our tokenized documents into a id <-> term dictionary
dictionary = corpora.Dictionary(texts)
print("printing each token/words along with unique integer id..")
print(dictionary.token2id)
# convert tokenized documents into a document-term matrix
corpus = [dictionary.doc2bow(text) for text in texts]
print("printing sample bag of words")
print(corpus[0])
# generate LDA model
ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=2, id2word = dictionary, passes=20)
#print(ldamodel.print_topics(num_topics=3, num_words=3))
#print ldamodel.top_topics(corpus,2)
print(ldamodel.show_topics(num_topics=2, num_words=3, log=False, formatted=True))
print(ldamodel.show_topics())
print("from for loop.")
for i in ldamodel.show_topics(len(dictionary)):
print i