Reading history

Topic Modelling with NMF and LDA

10 min read 0 views

Learn topic modelling in Python with NMF and LDA in scikit-learn: find topics in text, read their top words and check if they are stable.

You have thousands of customer reviews or news stories and no time to read them all. What are people writing about? Topic modelling finds groups of words that tend to appear together, such as “rain, wind, cyclone, coast”. Each group is a topic. In this lesson you will find topics with NMF and LDA in scikit-learn, and see why the simpler method can win on small data.

In this lesson you will learn

  • What a topic is in topic modelling
  • How NMF splits a document-word table into topics
  • How LDA treats each document as a mix of topics
  • How to print the top words of each topic
  • How to check whether the topics are stable and useful

You should know TF-IDF and clustering.

What Is a Topic?

In topic modelling, a topic is just a list of words with weights. A cricket topic gives high weight to “bowler”, “match” and “wicket”. A document is then described as a mix of topics. A story about a cyclone that stopped a cricket match might be 60% weather and 40% cricket.

Topic modelling is unsupervised. We never tell the model what the topics are. We only choose how many to look for. The model finds them, and we read the top words to give each topic a name.

Documents x words6 docs, 8 words≈Doc x topictopic mix per doc×Topic x wordword weights per topic

Two Popular Methods

  • NMF (non-negative matrix factorisation) takes the big document-by-word table and splits it into two smaller tables: documents-by-topics and topics-by-words. Multiply them back together and you get close to the original. All values stay zero or positive, which makes the topics easy to read. It usually works on TF-IDF values.
  • LDA (latent Dirichlet allocation) is a probability model. It imagines each document was written by picking a topic, then a word from that topic, again and again. It works on raw word counts. Do not confuse it with linear discriminant analysis, which shares the short name.

Finding Topics in 24 Short Stories

We wrote 24 short texts about four themes: cricket, cooking, phones and weather. The model is not told the themes.

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import NMF, LatentDirichletAllocation

# A small set of short "news" texts about four themes (cricket, food, phones, weather).
# No labels are given to the model; topic modelling must find the themes itself.
docs = [
    "the batsman hit a six and the bowler took a wicket in the cricket match",
    "the captain won the toss and chose to bat first on a dry pitch",
    "a fast bowler took three wickets and the team won the match by ten runs",
    "the opening batsman scored a century in the test match at the stadium",
    "fans filled the stadium to watch the cricket team win the series",
    "the spinner bowled well and the captain praised the young bowler",
    "cook the rice with salt and add fried onion and chicken curry",
    "this biryani recipe uses rice beef potato and a lot of spice",
    "fry the fish in mustard oil and serve it hot with rice",
    "add chilli turmeric and salt to the curry and cook it slowly",
    "the cook made a sweet dessert with milk sugar and rice",
    "mix flour sugar and milk then fry the dough to make a sweet snack",
    "the new phone has a bigger battery and a faster camera",
    "this phone charges fast and the screen is bright in sunlight",
    "update the app to fix the battery drain on your phone",
    "the camera app now takes clearer photos at night on the new phone",
    "a cheap phone with a large screen and long battery life",
    "the app crashed after the update so the phone was restarted",
    "heavy rain and strong wind are expected as the cyclone comes near the coast",
    "the weather office warned of heavy rain and flood in the north",
    "a cold wave and thick fog will continue across the country this week",
    "the cyclone brought strong wind and rain to the coast last night",
    "river water is rising and flood may hit low areas after the rain",
    "fog and cold weather delayed flights and ferries in the morning",
]

def show_topics(model, words, n=6):
    for k, row in enumerate(model.components_):
        top = [words[i] for i in row.argsort()[::-1][:n]]
        print(f"  topic {k}: {' '.join(top)}")

# NMF works on TF-IDF weights
tfidf = TfidfVectorizer(stop_words="english")
T = tfidf.fit_transform(docs)
nmf = NMF(n_components=4, init="nndsvda", random_state=0, max_iter=1000).fit(T)
print("NMF topics:")
show_topics(nmf, tfidf.get_feature_names_out())

# LDA works on plain word counts
cv = CountVectorizer(stop_words="english")
C = cv.fit_transform(docs)
lda = LatentDirichletAllocation(n_components=4, random_state=0, max_iter=50).fit(C)
print("LDA topics:")
show_topics(lda, cv.get_feature_names_out())

# Each document is a mix of topics. Which topic is strongest in each?
W = nmf.transform(T)
print("strongest NMF topic per document:")
print(" ", W.argmax(axis=1))

Output

NMF topics:
  topic 0: phone app battery update camera new
  topic 1: rain strong wind cyclone coast heavy
  topic 2: cook rice salt curry add sugar
  topic 3: match bowler took batsman cricket team
LDA topics:
  topic 0: phone bowler flood hit took weather
  topic 1: cook curry salt add captain rice
  topic 2: sweet sugar milk batsman rice match
  topic 3: rain strong wind cyclone coast heavy
strongest NMF topic per document:
  [3 3 3 3 3 3 2 2 2 2 2 2 0 0 0 0 0 0 1 1 1 1 1 1]
  • stop_words="english" removes common words like “the” and “and”, which appear in every topic and tell us nothing.
  • components_ holds one row of word weights per topic. Sorting a row and taking the top words shows what the topic is about.
  • NMF found four clean topics: phones, weather, food and cricket. The topic numbers are arbitrary; we name them ourselves.
  • LDA found the weather topic, but the others are mixed. “phone”, “bowler” and “flood” share one topic, which makes no sense.
  • transform gives each document’s topic mix. Taking the largest value puts the six stories of each theme into the same topic.

Are the Topics Real?

Here we cheat a little: since we wrote the stories, we know the true theme of each. The adjusted Rand score compares the model’s grouping with the truth. A score of 1 means a perfect match and 0 means no better than random. We also try four random seeds.

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import NMF, LatentDirichletAllocation
from sklearn.metrics import adjusted_rand_score

# A small set of short "news" texts about four themes (cricket, food, phones, weather).
# No labels are given to the model; topic modelling must find the themes itself.
docs = [
    "the batsman hit a six and the bowler took a wicket in the cricket match",
    "the captain won the toss and chose to bat first on a dry pitch",
    "a fast bowler took three wickets and the team won the match by ten runs",
    "the opening batsman scored a century in the test match at the stadium",
    "fans filled the stadium to watch the cricket team win the series",
    "the spinner bowled well and the captain praised the young bowler",
    "cook the rice with salt and add fried onion and chicken curry",
    "this biryani recipe uses rice beef potato and a lot of spice",
    "fry the fish in mustard oil and serve it hot with rice",
    "add chilli turmeric and salt to the curry and cook it slowly",
    "the cook made a sweet dessert with milk sugar and rice",
    "mix flour sugar and milk then fry the dough to make a sweet snack",
    "the new phone has a bigger battery and a faster camera",
    "this phone charges fast and the screen is bright in sunlight",
    "update the app to fix the battery drain on your phone",
    "the camera app now takes clearer photos at night on the new phone",
    "a cheap phone with a large screen and long battery life",
    "the app crashed after the update so the phone was restarted",
    "heavy rain and strong wind are expected as the cyclone comes near the coast",
    "the weather office warned of heavy rain and flood in the north",
    "a cold wave and thick fog will continue across the country this week",
    "the cyclone brought strong wind and rain to the coast last night",
    "river water is rising and flood may hit low areas after the rain",
    "fog and cold weather delayed flights and ferries in the morning",
]

# We wrote the texts, so we secretly know the true theme of each one
truth = np.repeat([0, 1, 2, 3], 6)       # cricket, food, phones, weather

T = TfidfVectorizer(stop_words="english").fit_transform(docs)
C = CountVectorizer(stop_words="english").fit_transform(docs)

# Adjusted Rand score: 1.0 = groups match the true themes exactly, 0 = random
print("seed   NMF    LDA")
for seed in range(4):
    nmf = NMF(n_components=4, init="nndsvda", random_state=seed, max_iter=1000)
    lda = LatentDirichletAllocation(n_components=4, random_state=seed, max_iter=200)
    a = adjusted_rand_score(truth, nmf.fit_transform(T).argmax(axis=1))
    b = adjusted_rand_score(truth, lda.fit_transform(C).argmax(axis=1))
    print(f"  {seed}   {a:.2f}   {b:.2f}")

Output

seed   NMF    LDA
  0   1.00   -0.01
  1   1.00   0.03
  2   1.00   0.19
  3   1.00   -0.00
  • NMF scores 1.00 every time. With init="nndsvda" it starts from the same point on every run, so the seed does not change it.
  • LDA scores near 0 on every seed. With only 24 short texts, it does not have enough word counts to estimate its probabilities.
  • On thousands of longer documents LDA does much better, and its probability view is useful. On small or short texts, try NMF first.

Without true labels

In real work you will not know the true themes. Instead, read the top words and a few sample documents for each topic. Good topics have top words that clearly belong together. Run the model with a few seeds too: topics that change a lot between runs are not trustworthy.

Practical Tips

ChoiceTip
Number of topicsTry a few values, such as 5, 10 and 20, and read the results
Rare and common wordsUse min_df and max_df to drop words in very few or very many documents
Input for NMFTfidfVectorizer
Input for LDACountVectorizer (raw counts)
Bangla or mixed textBuild your own stop word list

Common Mistakes

  1. Feeding TF-IDF to LDA. LDA expects whole-number word counts. Use CountVectorizer.
  2. Keeping stop words. Every topic ends up full of “the”, “is” and “and”.
  3. Trusting topic numbers. Topic 0 in one run may be topic 3 in the next. Always name topics by their top words.
  4. Expecting magic on tiny data. A few short texts give LDA too little to work with.

Practice Exercises

Exercise 1. In tm1.py, set n_components=3 for NMF. What do you expect to happen to the four themes?

Show answer

The model must squeeze four themes into three topics, so two themes will share a topic. Which two merge depends on which words they share. Reading the top words shows you which pair was joined.

Exercise 2. Why does NMF use TF-IDF while LDA uses raw counts?

Show answer

NMF only needs non-negative numbers, and TF-IDF lowers the weight of words that appear everywhere, which gives cleaner topics. LDA is built on a model of how word counts are generated, so it needs real counts.

Frequently Asked Questions

How many topics should I choose?

There is no single right number. Try a few values and pick the one whose topics are clearest to a human reader. Too few topics mix themes together; too many split one theme into near copies.

Is topic modelling the same as clustering?

They are related. Clustering puts each document in one group. Topic modelling gives each document a mix of topics, so a story can be part weather and part cricket.

Can topic modelling work on Bangla text?

Yes. The methods only see word counts, so any language works. You need a good way to split text into words and a Bangla stop word list.

Summary

  • A topic is a weighted list of words that often appear together.
  • NMF splits a TF-IDF table into topics; LDA models word counts with probabilities.
  • Read each topic’s top words to name it.
  • Check that topics make sense and stay stable across runs.

Next: The Perceptron Algorithm in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *