1. Understand the Goal: The user wants a program to perform topic modeling on document collections.
-
Identify the Key Concepts:
- Topic Modeling: A type of statistical modeling for discovering abstract topics in documents. Common algorithms: LSA (Latent Semantic Analysis), pLSA (Probabilistic Latent Semantic Analysis), LDA (Latent Dirichlet Allocation), NMF (Non-negative Matrix Factorization).
- Document Collection: A corpus of text data (e.g., a list of strings, a folder of text files).
- Preprocessing: Crucial for NLP tasks. Involves tokenization, stop word removal, stemming/lemmatization.
- Vectorization: Converting text to numbers (CountVectorizer, TF-IDF).
- Python: The standard language for this. Libraries:
scikit-learn (easier for beginners, good for LDA/NMF), gensim (industry standard for LDA, more specialized features), nltk/spacy (preprocessing).
-
Select the Approach:
- Option A: Gensim. Good for large datasets, streaming, and specific LDA optimizations.
- Option B: Scikit-Learn. Very accessible, integrates well with other ML pipelines, offers both LDA and NMF easily.
- Decision: I will provide a solution using
scikit-learn and NLTK because it's self-contained, readable, and uses standard API patterns. I will implement Latent Dirichlet Allocation (LDA) as it is the most popular algorithm. I'll also mention NMF as an alternative.
-
Structure the Program:
- Imports:
sklearn, nltk, pandas, numpy.
- Data Loading: Create a dummy dataset so the code is runnable immediately, but add comments on how to load from a file.
- Preprocessing Class/Function:
- Lowercase.
- Tokenize.
- Remove stopwords.
- Lemmatize (better than stemming).
- Vectorization:
CountVectorizer (for LDA) or TfidfVectorizer (for NMF). Let's stick to CountVectorizer for LDA as it models word counts (multinomial distribution).
- Model Training:
LatentDirichletAllocation.
- Display Results: Function to print top words per topic.
-
Drafting the Code (Mental or Scratchpad):
-
Imports:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
-
Preprocessing:
Need to handle downloading NLTK data (stopwords, punkt, wordnet).
The CountVectorizer actually handles tokenization and stop words, but doing it manually gives better control (especially lemmatization).
Refinement: To keep the script concise and robust, I'll use CountVectorizer's built-in stop word removal but provide a custom tokenizer function for lemmatization.
-
The Custom Tokenizer:
def tokenize(text):
lemmas = ...
return lemmas
-
The Main Logic:
- Define documents.
- Vectorize.
- Fit LDA.
- Print topics.
-
Refining the Solution:
- Dependencies:
pip install scikit-learn nltk pandas
- Handling "Real" Data: The prompt implies a general program. I should encapsulate the logic in a class or a structured set of functions so it looks professional.
- Visualization: Adding
pyLDAvis is cool, but might overcomplicate the environment setup. I'll keep it to console output for the core program but mention libraries like pyLDAvis.
-
Writing the Code (Iterative improvement):
- Step 1: Setup. Import libraries. Download NLTK resources.
- Step 2: Preprocessing. Create a class
TopicModeler.
- Step 3: Vectorization. Use
CountVectorizer inside the class.
- Step 4: Modeling. Use
LatentDirichletAllocation.
- Step 5: Output. Create a helper to display topics.
-
Adding Explanations:
- Explain LDA (it's probabilistic, assumes documents are mixtures of topics).
- Explain the parameters (
n_components, max_df, min_df).
- Explain how to interpret results.
-
Final Code Polish:
- Make sure the dummy data clearly has distinct topics (e.g., Tech, Space, Sports) so the output makes sense to the user.
- Add comments.
-
Self-Correction during drafting:
- Initial thought: Just use raw strings.
- Correction: Lemmatization makes topics much more readable (e.g., "running" becomes "run"). I must include it.
- Initial thought: Use
gensim.
- Correction:
scikit-learn is often easier for someone asking for a general "program" because it fits into the standard ML pipeline without learning the specific idiosyncrasies of gensim's Dictionary and Corpus objects. I will stick to scikit-learn but mention gensim as an alternative.
-
Constructing the Final Response:
- Title: Topic Modeling with Python.
- Prerequisites: List
pip install commands.
- The Code: Complete, runnable script.
- Explanation: Break down the steps (Preprocessing, Vectorization, LDA).
- Next Steps: How to use on own data, alternative algorithms (NMF), visualization.
This thought process moves from understanding the requirements to selecting the best tools for a general audience, structuring the code for readability and reusability, and ensuring the example provided is verifiable.
Here is a complete Python program to perform topic modeling.
I have chosen Latent Dirichlet Allocation (LDA) using the scikit-learn library because it is the industry standard for this task, easy to integrate into machine learning pipelines, and highly effective.
Prerequisites
You will need to install the following libraries:
pip install scikit-learn nltk pandas
The Python Program
This script includes functions to download sample data, preprocess the text (remove stopwords, lemmatize), vectorize the documents, and extract topics.
import pandas as pd
import nltk
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import re
# --- 1. Setup and Data Loading ---
# Download necessary NLTK data
nltk.download('stopwords', quiet=True)
nltk.download('wordnet', quiet=True)
nltk.download('omw-1.4', quiet=True)
# Sample Document Collection
# In a real scenario, you would load this from a folder of text files or a CSV.
documents = [
"The new iPhone has a great camera and battery life, but the price is high.",
"Apple released their latest macbook with the M3 chip for better performance.",
"The goalkeeper made an amazing save during the world cup final match.",
"The basketball player scored a three-pointer in the last second of the game.",
"Global warming is causing the ice caps to melt at an alarming rate.",
"Scientists are researching new ways to reduce carbon emissions and save the environment.",
"The stock market saw a significant drop in technology shares today.",
"Investors are worried about inflation and the rising interest rates.",
"The goalkeeper injured his knee and might miss the next football season.",
"Apple's new recycling robot aims to reduce electronic waste."
]
# --- 2. Preprocessing Class ---
class TextPreprocessor:
def __init__(self):
self.stop_words = set(stopwords.words('english'))
self.lemmatizer = WordNetLemmatizer()
def clean_text(self, text):
# Remove punctuation and lowercase
text = re.sub(r'[^\w\s]', '', text.lower())
# Tokenize, remove stopwords, and lemmatize (convert words to base form: 'running' -> 'run')
words = text.split()
cleaned_words = [
self.lemmatizer.lemmatize(word)
for word in words
if word not in self.stop_words and len(word) > 2
]
return " ".join(cleaned_words)
# --- 3. Topic Modeling Function ---
def perform_topic_modeling(docs, n_topics=3, n_words=5):
# A. Preprocess
preprocessor = TextPreprocessor()
cleaned_docs = [preprocessor.clean_text(doc) for doc in docs]
# B. Vectorization (Convert text to numbers)
# We use CountVectorizer (Bag of Words) for LDA.
# max_df ignores words that appear in too many documents (corpus-specific stopwords)
# min_df ignores words that appear in too few documents (typos/noise)
vectorizer = CountVectorizer(max_df=0.95, min_df=2)
doc_term_matrix = vectorizer.fit_transform(cleaned_docs)
# C. LDA Model
lda = LatentDirichletAllocation(
n_components=n_topics,
random_state=42,
learning_method='online'
)
lda.fit(doc_term_matrix)
return lda, vectorizer, doc_term_matrix
def display_topics(model, feature_names, no_top_words):
print("\n--- Discovered Topics ---\n")
for topic_idx, topic in enumerate(model.components_):
# argsort() sorts indices by value; we take the last N (highest probabilities)
top_words_indices = topic.argsort()[:-no_top_words - 1:-1]
top_words = [feature_names[i] for i in top_words_indices]
print(f"Topic {topic_idx + 1}: {', '.join(top_words)}")
# --- 4. Execution ---
if __name__ == "__main__":
# Define hyperparameters
NUM_TOPICS = 3
NUM_WORDS_PER_TOPIC = 5
# Run the model
lda_model, vectorizer, dt_matrix = perform_topic_modeling(
documents,
n_topics=NUM_TOPICS,
n_words=NUM_WORDS_PER_TOPIC
)
# Display the topics (The words that define the topic)
feature_names = vectorizer.get_feature_names_out()
display_topics(lda_model, feature_names, NUM_WORDS_PER_TOPIC)
# --- 5. Assigning Topics to Documents ---
# Transform the document matrix to get topic probability distributions
topic_distribution = lda_model.transform(dt_matrix)
# Create a DataFrame to view results
df_results = pd.DataFrame(documents, columns=['Document'])
# Get the dominant topic for each document
df_results['Dominant Topic'] = [probs.argmax() + 1 for probs in topic_distribution]
print("\n--- Document Classification ---\n")
print(df_results[['Document', 'Dominant Topic']].head())
How it works
- Preprocessing (
TextPreprocessor):
- Stopword Removal: Removes common words like "the", "is", "and" that carry little meaning.
- Lemmatization: Converts words to their root form (e.g., "injuries" becomes "injury"). This is crucial so the model treats them as the same concept.
- Vectorization (
CountVectorizer):
- LDA requires a "Bag of Words" representation (a matrix counting how many times a word appears in a document), rather than TF-IDF.
max_df=0.95 removes words that appear in more than 95% of documents (too common).
- LDA Model (
LatentDirichletAllocation):
- This is the algorithm that mathematically assumes every document is a mixture of topics, and every topic is a mixture of words.
- It iterates through the words to find the best groupings based on probability.
- Results:
- Display Topics: It prints the top 5 keywords for the 3 topics found. You should see distinct groups (e.g., one related to Sports, one to Tech/Apple, one to Finance/Environment).
- Classification: It predicts which topic is strongest for each specific document.
Example Output
When you run the code, you will see output similar to this:
--- Discovered Topics ---
Topic 1: player, scored, basketball, match, cup
Topic 2: price, apple, market, stock, inflation
Topic 3: environment, carbon, research, warming, global
--- Document Classification ---
Document Dominant Topic
0 The new iPhone has a great camera and battery... 2
1 Apple released their latest macbook with the ... 2
2 The goalkeeper made an amazing save during th... 1
How to use your own data
Replace the documents list in the code with your own data loader. For example, to load text files from a folder:
import os
def load_documents(folder_path):
docs = []
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
with open(os.path.join(folder_path, filename), 'r', encoding='utf-8') as f:
docs.append(f.read())
return docs
# Replace the list with:
documents = load_documents("path/to/your/folder")