I have used gensim LDA Topic Modeling to get associated topics from a corpus. Now I want to get the top 20 documents representing each topic: documents that have the highest probability in a topic. And I want to save them in a CSV file with this format: 4 columns for Topic ID, Topic words, probability of each word in the topic, top 20 documents for each topic.
I have tried get_document_topics which I think it is the best approach for this task:
all_topics = lda_model.get_document_topics(corpus, minimum_probability=0.0, per_word_topics=False)
But I am not sure how to get top 20 documents that best represent the topic and add them to the CSV file.
data_words_nostops = remove_stopwords(processed_docs)
# Create Dictionary
id2word = corpora.Dictionary(data_words_nostops)
# Create Corpus
texts = data_words_nostops
# Term Document Frequency
corpus = [id2word.doc2bow(text) for text in texts]
# Build LDA model
lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
id2word=id2word,
num_topics=20,
random_state=100,
update_every=1,
chunksize=100,
passes=10,
alpha='auto',
per_word_topics=True)
pprint(lda_model.print_topics())
#save csv
fn = "topic_terms5.csv"
if (os.path.isfile(fn)):
m = "a"
else:
m = "w"
num_topics=20
# save topic, term, prob data in the file
with open(fn, m, encoding="utf8", newline='') as csvfile:
fieldnames = ["topic_id", "term", "prob"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if (m == "w"):
writer.writeheader()
for topic_id in range(num_topics):
term_probs = lda_model.show_topic(topic_id, topn=6)
for term, prob in term_probs:
row = {}
row['topic_id'] = topic_id
row['prob'] = prob
row['term'] = term
writer.writerow(row)
Expected result: CSV file with this format: 4 columns for Topic ID, Topic words, probability of each word, top 20 documents for each topic.