Monday , November 30 2026
Topic modeling with tested scikit-learn code: NMF on TF-IDF, LDA on word counts, choosing the number of topics and modern BERTopic and LLM approaches.

Topic Modeling in Python: LDA and NMF with scikit-learn

Updated: 29 November 2026Level: IntermediateReading time: about 9 minutesscikit-learn · tested

Topic modeling automatically discovers the themes in a collection of documents without labels. It is used to explore customer feedback, news archives, research papers and support tickets.

What You Will Learn

  • What a topic model outputs
  • NMF on TF-IDF
  • LDA on word counts
  • Why tiny corpora give messy topics
  • BERTopic and LLM-based alternatives

Prerequisites

Bag of Words & TF-IDF.

The Data

Example
docs = ["India won the cricket match by five wickets",
        "The batsman scored a century in the test match",
        "Bowlers took early wickets in the final over",
        "Fans celebrated the cricket world cup victory",
        "The stock market rose as investors bought shares",
        "Sensex and Nifty closed higher on bank stocks",
        "Interest rates and inflation worry investors",
        "The rupee fell against the dollar in trading",
        "The new smartphone has a faster processor and camera",
        "Developers released an AI model for coding",
        "The laptop battery lasts twelve hours",
        "Cloud computing and AI chips drive tech growth"]

NMF (Non-negative Matrix Factorization)

Example
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF

tv = TfidfVectorizer(stop_words="english")
T = tv.fit_transform(docs)
terms = tv.get_feature_names_out()
nmf = NMF(n_components=3, random_state=0, init="nndsvd").fit(T)
for k, comp in enumerate(nmf.components_):
    print("Topic", k, list(terms[np.argsort(comp)[-5:][::-1]]))
Output
Topic 0 ['wickets', 'match', 'cricket', 'india', 'won']
Topic 1 ['investors', 'rates', 'worry', 'inflation', 'shares']
Topic 2 ['ai', 'released', 'coding', 'developers', 'model']

Explanation: NMF splits the document–word matrix into document–topic and topic–word matrices. The top words make the three themes obvious: cricket, finance and technology. You name the topics yourself – the algorithm only groups words.

LDA (Latent Dirichlet Allocation)

Example
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
cv = CountVectorizer(stop_words="english")
X = cv.fit_transform(docs)
words = cv.get_feature_names_out()
lda = LatentDirichletAllocation(n_components=3, learning_method="batch",
                                max_iter=200, random_state=0).fit(X)
for k, comp in enumerate(lda.components_):
    print("Topic", k, list(words[np.argsort(comp)[-5:][::-1]]))
Output
Topic 0 ['investors', 'cricket', 'rose', 'market', 'stock']
Topic 1 ['ai', 'wickets', 'tech', 'chips', 'computing']
Topic 2 ['match', 'sensex', 'nifty', 'stocks', 'higher']

Explanation: LDA is a probabilistic model: each document is a mixture of topics and each topic a distribution over words. On only 12 very short documents its topics are mixed up (“cricket” with “investors”). LDA needs hundreds or thousands of longer documents; NMF on TF-IDF often works better for short texts.

Choosing the Number of Topics

  • Try several values (5, 10, 20) and read the top words – are topics distinct and meaningful?
  • Use coherence scores (e.g. gensim’s CoherenceModel) to compare settings.
  • Remove domain stop words (“said”, “also”, brand names) that appear in every topic.

Modern Alternatives

Method Idea Best for
BERTopic Sentence embeddings → clustering → keyword extraction Short texts, tweets, reviews
LLM labelling Ask an LLM to summarise and name each cluster Readable topic names
NMF / LDA Classic matrix factorisation / probabilistic model Large corpora, interpretable baselines

Series

NLP series: NLP Intro · Tokenizer · Stop Words · Stemming · Lemmatization · Bag of Words & TF-IDF · Word Embeddings · Sentiment Analysis · NER · Topic Modeling · BERT · Spam Project

Interview Questions

Q: What does a topic model output?
Topics as weighted word lists and, for each document, a mixture of topics.

Q: LDA vs NMF?
LDA is a probabilistic generative model on counts; NMF is a matrix factorisation usually on TF-IDF and often clearer on short texts.

Practice Exercises

  1. Print the dominant topic for each document with nmf.transform(T).argmax(1).
  2. Run NMF with 10 topics on a set of customer reviews and name each topic.

Summary

Topic models discover themes without labels. Use NMF for short texts, LDA for large corpora, and BERTopic or LLMs when you need semantic clusters and readable names.

Next: BERT Explained

About Machine Learning

Check Also

Sentiment Analysis in Python: ML Model and Transformers

Sentiment analysis in Python with a tested TF-IDF and logistic regression model, why small datasets fail, word coefficients and pre-trained Hugging Face models.