Module 11 β NLP (Text Analytics)ΒΆ
π§ β Agents, Tools & MCP Β· π Course home Β· DeepTab βΆ
Goal: Turn unstructured text β reviews, support tickets, survey verbatims, social posts β into structure you can act on. Discover what people are talking about (topic modeling) and how they feel about it (sentiment analysis), using the libraries practitioners actually reach for.
Estimated time: 2β4 hours.
Prerequisites: Module 5 (NB 17 sklearn basics), Module 8 NB 29 (embeddings & retrieval). NumPy fluency (NB 8) helps.
π Optional, reference-style module. Like the appendices, these notebooks demo a library at work rather than drilling exercises. Every notebook runs end-to-end offline via a small built-in scikit-learn stand-in β install the optional library to swap in the real thing.
ββββββββββββββββββββββββββββββββββββββββββββββ
β raw text β structure you can act on β
βββββββββββββββββββββββ¬βββββββββββββββββββββββ
βββββββββββββββββββββββ΄ββββββββββββββββββββββ
βΌ βΌ
WHAT are they talking about? HOW do they feel?
ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββ
β NB 41 β BERTopic β β NB 43 β Sentiment analysis β
β embed β UMAP β HDBSCAN β β lexicon (VADER) β β
β β c-TF-IDF topic labels β β classical ML (TF-IDF+LogReg) β β
β β β transformers (HF pipeline) β
β NB 42 β STREAM β ββββββββββββββββββββββββββββββββββ
β one API over LDA/NMF/ETM/ β
β CTM/KmeansTMβ¦ + evaluation β
ββββββββββββββββββββββββββββββββ
Notebooks at a glanceΒΆ
# |
Notebook |
β± Time |
Difficulty |
What youβll learn / build |
|---|---|---|---|---|
35 |
|
~45β75 min |
Intermediate |
BERTopic β embedding-based topic modeling (embed β UMAP β HDBSCAN β c-TF-IDF); read |
36 |
|
~45β75 min |
Intermediate |
STREAM ( |
37 |
|
~45β75 min |
Beginner β Intermediate |
The sentiment ladder β lexicon/rule-based (VADER) β TF-IDF + LogReg workhorse β transformer |
Notebook guidesΒΆ
41 Β· Topic Modeling with BERTopic β 41_topic_modeling_bertopic.ipynbΒΆ
You have 50,000 support tickets, a year of product reviews, or 3,000 free-text survey answers β nobody will read them all. Topic modeling builds the map: which themes exist, how big each cluster is, and where the outliers hide. The notebookβs running mental model is the automatic librarian β group notes by meaning, shelve them, write a spine label per shelf, and keep a βmiscβ cart (topic -1) for notes that fit nowhere.
It explains the four-stage pipeline conceptually, shows the real BERTopic API verbatim, then builds a tiny sklearn-only stand-in so everything runs on a laptop with no downloads. From there: reading get_topic_info() / get_topic() / get_document_info(), visualising topic sizes and words, merging over-split topics with reduce_topics, an honest LDA-vs-BERTopic comparison table, and swapping custom components (embedder, UMAP, HDBSCAN, vectorizer) β ending with dynamic, hierarchical, and LLM-enhanced topic representations.
Learning objectives:
Explain the BERTopic pipeline β embed β reduce (UMAP) β cluster (HDBSCAN) β describe (c-TF-IDF) β and why each stage is there.
Run
fit_transformon a list of documents and readget_topic_info(),get_topic(), andget_document_info().Understand topic
-1(the outlier/noise topic) and why it is a feature, not a bug.Contrast BERTopic with classical LDA and know when each is the right tool.
Swap in custom components (embedding model, UMAP, HDBSCAN, vectorizer) and reduce the topic count.
Know where this goes next: dynamic, hierarchical, and LLM-enhanced topic representations.
Sections: 1 Setup & the offline smoke test Β· 2 A small, honest corpus Β· 3 How BERTopic thinks β the four-stage pipeline Β· 4 The real BERTopic API Β· 5 The offline stand-in β BERTopic in ~40 lines of sklearn Β· 6 One object, two implementations Β· 7 Reading the results Β· 8 Visualising topics Β· 9 Topic -1 β outliers are a feature Β· 10 Too many topics? Merge them Β· 11 BERTopic vs classical LDA Β· 12 Custom components β the real power Β· 13 Beyond the basics Β· 14 Where this pays off in business
Practice: 3 β quick exercises (~2 min, collapsible solutions) Β· 3 π§ͺ end-of-notebook exercises (open-ended) Β· β self-assessment checklist.
Libraries & offline behaviour:
pip install bertopic # optional β pulls sentence-transformers (+ PyTorch), umap-learn, hdbscan
That one line pulls a surprisingly large stack (expect a few hundred MB); the default embedder is all-MiniLM-L6-v2. A single HAS_BERTOPIC flag guards every real-API cell; without the install, a ~40-line sklearn stand-in (TF-IDF + KMeans) mimics the same interface (fit_transform, get_topic_info, get_topic, get_document_info), and charts are drawn with matplotlib/seaborn instead of BERTopicβs plotly visualizations.
Datasets: 36 short inline documents across five deliberately obvious themes β cloud computing, customer churn, healthcare, sports, cooking β so you can eyeball whether the model recovered them. No files, no downloads.
42 Β· Topic Modeling with STREAM β 42_topic_modeling_stream.ipynbΒΆ
NB 41 gave you one excellent, opinionated pipeline. But which topic model is best for your pile of text? STREAM (stream-topic) is a unified API over many topic models β classical (LDA, NMF), neural (ETM, CTM, ProdLDA, NeuralLDA, NSTM, TNTM, WordCluTM), and clustering/embedding (KmeansTM, CEDC, DCTE, SomTM, CBC) β all trained with the same model.fit(dataset, n_topics=β¦) β model.get_topics() calls. The mental model is a test kitchen: same ingredients (your corpus), swappable chefs (models), and a consistent panel of judges (the evaluation metrics), so you can say which recipe was actually better.
The bake-off runs on a voice-of-customer corpus: fit KmeansTM, swap to ProdLDA with a one-line change, read get_beta/get_theta (what a probabilistic model gives you that a clustering model doesnβt), score topics with embedding-based coherence/diversity metrics plus classic NPMI, sweep the number of topics with optimize_and_fit, and finish with STREAMβs DownstreamModel β an interpretable Neural Additive Model that predicts an outcome from topic proportions.
Learning objectives:
Explain what STREAM adds on top of a single pipeline like BERTopic β a unified interface across classical, neural and clustering topic models.
Load and preprocess a corpus with
TMDatasetand fit a model with the canonicalfit/get_topicsflow.Swap model families (
KmeansTMβProdLDA) with no other code change, and know when to reach for probabilistic (get_beta/get_theta) vs clustering models.Evaluate topics with embedding metrics (
ISIM/INT/ISH/Expressivity) and classicNPMI, and read the difference.Search the number of topics with
optimize_and_fit, and understand theDownstreamModel(NAM) idea for prediction.
Sections: 1 Setup & offline smoke-test Β· 2 A small business corpus Β· 3 The offline stand-in Β· 4 Fitting a model β the canonical STREAM flow Β· 5 The killer feature β swap the model, change nothing else Β· 6 get_beta and get_theta β what a probabilistic model gives you Β· 7 Evaluation β is this topic model any good? Β· 8 How many topics? optimize_and_fit Β· 9 Visualization Β· 10 Downstream prediction with a Neural Additive Model
Practice: 4 β quick exercises (~2 min, collapsible solutions) Β· 5 π§ͺ end-of-notebook exercises (the last one needs a real STREAM install) Β· β self-assessment checklist.
Libraries & offline behaviour: pip install stream-topic (also pulls lightning for the NAM and sentence-transformers for the embedding metrics). A HAS_STREAM flag guards every real cell; offline, a StandInTopicModel (TF-IDF + sklearn NMF β itself a legitimate classical topic model) mirrors the STREAM API (fit, get_topics, get_beta, get_theta), a NumPy NPMI proxy replaces the metric suite, PCA replaces the built-in visualizations, and plain LinearRegression stands in for the downstream NAM.
Datasets: ~36 short inline business documents β product reviews, support tickets, and finance/news snippets β with three baked-in themes (shipping/delivery, app/login/technical, price/billing). With the real library, the same docs are wrapped in a TMDataset (falling back to the bundled BBC_News corpus if that fails).
43 Β· Sentiment Analysis β 43_sentiment_analysis.ipynbΒΆ
Sentiment analysis turns free text into a signal you can aggregate β positive/negative/neutral or a polarity score β the thing that answers βdid sentiment drop after the price change?β or βroute this angry ticket to a human now.β The running mental model is the sentiment ladder: rung 1 a lexicon (VADER β no training, instant, transparent), rung 2 classical ML (TF-IDF + Logistic Regression β the workhorse, shockingly hard to beat in-domain), rung 3 a transformer (context-aware, strongest, heaviest). Golden rule: climb only as high as the problem forces you to.
The same six gadget-review snippets β including deliberate negation, sarcasm, and mixed-opinion traps β are scored on every rung so you can watch each method pass or fail on identical text. Along the way you inspect .coef_ to see which words drive the classical model, compare all three rungs side by side (with a keep-it cheat-sheet), build a toy word-window aspect-based sentiment scorer, and close with practitioner pitfalls: sarcasm, domain shift, the neutral class, class imbalance, calibration, and mapping stars to sentiment.
Learning objectives:
Explain the three families of sentiment methods and pick one for a given business constraint (latency, labels, accuracy, interpretability).
Run a lexicon scorer, read its
compoundscore, and explain the tricks VADER handles (negation, intensifiers, emoji, CAPS, punctuation).Train, evaluate, and inspect a TF-IDF + LogisticRegression classifier β including reading
.coef_to see which words drive the prediction.Call a Hugging Face
pipeline("sentiment-analysis")and name a few domain-specific models (FinBERT, twitter-roberta).Describe aspect-based sentiment and the pitfalls (sarcasm, domain shift, neutral class, class imbalance, calibration, starsβsentiment).
Sections: 0 Setup & imports Β· 1 Lexicon / rule-based sentiment β VADER Β· 2 Classical ML β TF-IDF + Logistic Regression (the workhorse) Β· 3 Transformers β Hugging Face pipeline Β· 4 Side-by-side: the three rungs of the ladder Β· 5 Aspect-based sentiment (ABSA) Β· 6 Pitfalls & practitioner notes
Practice: 3 β quick exercises (~2 min, collapsible solutions) Β· 6 π§ͺ end-of-notebook exercises (one needs transformers) Β· β
self-assessment checklist.
Libraries & offline behaviour: pip install vaderSentiment transformers torch β all optional, behind HAS_VADER / HAS_TRANSFORMERS capability flags. Offline, VADER is replaced by a minimal built-in lexicon scorer (hand-set word valences + negation flipping), and the transformer rung falls back to the Section-2 classical model β the notebook guards the model download too, not just the import, so it survives a no-network machine even with transformers installed. The classical rung is plain scikit-learn and always real.
Datasets: six running-example review snippets (love/hate/neutral/negated/sarcastic/mixed) plus 62 inline labeled gadget/product reviews (with deliberately βhardβ mixed-vocabulary cases) for training the classifier.
How these notebooks workΒΆ
Module 11 is optional and written reference-style: each notebook demos a real libraryβs API verbatim, but a try/except import sets a capability flag (HAS_BERTOPIC, HAS_STREAM, HAS_VADER, HAS_TRANSFORMERS) and every heavy cell degrades gracefully to a built-in scikit-learn/NumPy stand-in β so everything runs 100% offline, and installing the real library simply swaps the backend. Short ββ Quick exercise (~2 min)β checkpoints with collapsible <details> solutions punctuate each notebook, and each one closes with a π§ͺ exercise block of open-ended extensions (no autograder here, unlike the core modules), a π§ key-takeaways recap, and a β
self-assessment checklist to gauge what stuck. The habits this module drills: read the topics, donβt trust the count (always inspect topic words and the -1 outlier topic); pick embeddings vs. bag-of-words deliberately; start sentiment classical before reaching for transformers; and beware domain shift and sarcasm β validate on your text.
Where nextΒΆ
β Module 12 β DeepTab (../12_deeptab/44_deeptab_tabular_deep_learning.ipynb) for deep learning on tabular data, or
β back to Module 8 β AI Engineering (../08_ai_engineering/29_embeddings_retrieval.ipynb) to combine these signals with retrieval and LLMs.
π Finished this module? Test yourself with the Module 11 quiz β five questions, ~10 minutes.