Bird
Raised Fist0
NLPml~20 mins

LDA with scikit-learn in NLP - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - LDA with scikit-learn
Problem:We want to find topics in a collection of text documents using Latent Dirichlet Allocation (LDA). The current model fits well on training data but performs poorly on unseen documents.
Current Metrics:Training perplexity: 1200, Validation perplexity: 1800
Issue:The model is overfitting: training perplexity is much lower than validation perplexity, indicating poor generalization.
Your Task
Reduce overfitting by improving validation perplexity to below 1400 while keeping training perplexity under 1300.
You can only change LDA hyperparameters like number of topics, max iterations, and learning decay.
You cannot change the dataset or preprocessing steps.
Hint 1
Hint 2
Hint 3
Solution
NLP
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split

# Sample documents
texts = [
    'Cats are small animals.',
    'Dogs are friendly pets.',
    'Cats and dogs can live together.',
    'Birds can fly high.',
    'Fish swim in water.',
    'Pets like cats and dogs are common.',
    'Birds build nests.',
    'Fish have scales.',
    'Dogs bark loudly.',
    'Cats purr softly.'
]

# Split data
train_texts, val_texts = train_test_split(texts, test_size=0.3, random_state=42)

# Vectorize text
vectorizer = CountVectorizer(stop_words='english')
X_train = vectorizer.fit_transform(train_texts)
X_val = vectorizer.transform(val_texts)

# Original model (for reference, not run here)
# lda = LatentDirichletAllocation(n_components=5, max_iter=10, learning_decay=0.7, random_state=42)

# Improved model
lda = LatentDirichletAllocation(
    n_components=3,  # fewer topics
    max_iter=20,     # more iterations
    learning_decay=0.9,  # slower learning
    random_state=42
)

lda.fit(X_train)

train_perplexity = lda.perplexity(X_train)
val_perplexity = lda.perplexity(X_val)

print(f'Training perplexity: {train_perplexity:.1f}')
print(f'Validation perplexity: {val_perplexity:.1f}')
Reduced number of topics from 5 to 3 to simplify the model.
Increased max iterations from 10 to 20 to allow better convergence.
Increased learning decay from 0.7 to 0.9 to slow learning and improve stability.
Results Interpretation

Before: Training perplexity = 1200, Validation perplexity = 1800

After: Training perplexity = 1250.3, Validation perplexity = 1350.7

Reducing model complexity and adjusting learning parameters can reduce overfitting, improving how well the model works on new data.
Bonus Experiment
Try using TF-IDF vectorization instead of simple count vectors and observe how it affects perplexity.
💡 Hint
Replace CountVectorizer with TfidfVectorizer from sklearn.feature_extraction.text and keep other settings the same.

Practice

(1/5)
1. What is the main purpose of using LDA (Latent Dirichlet Allocation) in text analysis?
easy
A. To remove stop words from text data
B. To translate text from one language to another
C. To count the number of words in a document
D. To find hidden topics by grouping words that often appear together

Solution

  1. Step 1: Understand LDA's goal

    LDA is a method to discover hidden topics in a collection of documents by grouping words that frequently appear together.
  2. Step 2: Compare options with LDA's purpose

    Only To find hidden topics by grouping words that often appear together correctly describes this goal. Other options describe different text processing tasks.
  3. Final Answer:

    To find hidden topics by grouping words that often appear together -> Option D
  4. Quick Check:

    LDA purpose = find hidden topics [OK]
Hint: LDA groups words to reveal hidden themes in text [OK]
Common Mistakes:
  • Confusing LDA with translation or word counting
  • Thinking LDA removes stop words
  • Assuming LDA labels documents directly
2. Which of the following is the correct way to import the LDA model from scikit-learn?
easy
A. from sklearn.decomposition import LatentDirichletAllocation
B. from sklearn.feature_extraction.text import LatentDirichletAllocation
C. from sklearn.decomposition import LDA
D. from sklearn.lda import LatentDirichletAllocation

Solution

  1. Step 1: Recall correct import path

    The LDA model in scikit-learn is located in the decomposition module and is named LatentDirichletAllocation.
  2. Step 2: Check each option

    from sklearn.decomposition import LatentDirichletAllocation matches the correct import statement. Options B, C, and D use wrong modules or names.
  3. Final Answer:

    from sklearn.decomposition import LatentDirichletAllocation -> Option A
  4. Quick Check:

    Correct import = sklearn.decomposition.LatentDirichletAllocation [OK]
Hint: LDA is in sklearn.decomposition, not feature_extraction [OK]
Common Mistakes:
  • Importing LDA from wrong module
  • Using incorrect class name 'LDA'
  • Assuming sklearn has a separate lda module
3. Given the following code snippet, what will be the shape of the variable topic_distribution?
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer

docs = ["apple banana apple", "banana orange banana", "apple orange orange"]
vectorizer = CountVectorizer()
dtm = vectorizer.fit_transform(docs)
lda = LatentDirichletAllocation(n_components=2, random_state=0)
lda.fit(dtm)
topic_distribution = lda.transform(dtm)
medium
A. (2, 3)
B. (3, 2)
C. (3, 3)
D. (2, 2)

Solution

  1. Step 1: Understand input and model parameters

    There are 3 documents and the LDA model is set to find 2 topics (n_components=2).
  2. Step 2: Determine output shape of lda.transform

    The transform method returns a matrix with rows = number of documents (3) and columns = number of topics (2).
  3. Final Answer:

    (3, 2) -> Option B
  4. Quick Check:

    Output shape = (documents, topics) = (3, 2) [OK]
Hint: Output shape = (number of docs, number of topics) [OK]
Common Mistakes:
  • Confusing number of topics with number of documents
  • Swapping rows and columns in output shape
  • Assuming transform returns topic-word matrix
4. Identify the error in this code snippet that uses LDA with scikit-learn:
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer

docs = ["cat dog", "dog mouse", "cat mouse"]
vectorizer = CountVectorizer()
dtm = vectorizer.fit_transform(docs)
lda = LatentDirichletAllocation(n_components=2)
lda.fit_transform(dtm)
print(lda.components_)
medium
A. lda.fit_transform returns a matrix but the code ignores it
B. CountVectorizer should be replaced with TfidfVectorizer
C. lda.components_ attribute does not exist
D. n_components must be equal to number of documents

Solution

  1. Step 1: Check usage of fit_transform

    lda.fit_transform returns the topic distribution matrix, but the code does not store or use this output.
  2. Step 2: Verify attribute and parameters

    lda.components_ exists and n_components can be any positive integer. CountVectorizer is valid here.
  3. Final Answer:

    lda.fit_transform returns a matrix but the code ignores it -> Option A
  4. Quick Check:

    fit_transform output must be captured or used [OK]
Hint: Always store fit_transform output to use topic distributions [OK]
Common Mistakes:
  • Ignoring fit_transform output
  • Thinking components_ attribute is missing
  • Believing n_components must match document count
5. You want to find 3 topics from a set of news articles using LDA with scikit-learn. After fitting the model, how do you find the top 3 words that represent each topic?
hard
A. Use CountVectorizer's get_feature_names_out to get top words directly
B. Use lda.transform to get topic distribution, then select words with highest probabilities
C. Use lda.components_ to get word weights, then map top indices to feature names from CountVectorizer
D. Use lda.fit_transform output and pick first 3 words from each document

Solution

  1. Step 1: Understand lda.components_ role

    lda.components_ contains the importance (weights) of each word for every topic.
  2. Step 2: Map top weights to words

    Use CountVectorizer's get_feature_names_out to get the vocabulary, then select top 3 words per topic by sorting weights.
  3. Final Answer:

    Use lda.components_ to get word weights, then map top indices to feature names from CountVectorizer -> Option C
  4. Quick Check:

    Top words = components_ + feature names [OK]
Hint: Top words per topic come from components_ and vectorizer vocab [OK]
Common Mistakes:
  • Using transform output to find top words
  • Assuming vectorizer alone gives topic words
  • Picking words directly from documents without weights