Skip to content

41. NLP fundamentals

Most data that people write is text: product reviews, support tickets, emails, survey answers and log messages. A model cannot read words. It needs numbers. Natural language processing (NLP) is the field that turns text into numbers and lets programs classify, search and summarize it. This module builds the classic NLP toolbox on one realistic task: the 3,000 product reviews in data/reviews.csv. You clean the text, turn it into a table of word counts and weights, train a sentiment classifier, find the themes that customers write about and look up reviews that say the same thing in other words.

  • Clean raw text: lowercase it, decode HTML entities with html.unescape, collapse whitespace, decide what to do with punctuation and know why typos stay a problem.
  • Split text into tokens with re and str methods, and know what stop words remove, including the words that carry sentiment.
  • Represent documents as a bag of words with CountVectorizer and as TF-IDF weights with TfidfVectorizer, read the sparse matrices they return, and compute the smooth TF-IDF formula by hand.
  • Add n-grams so that a model sees phrases such as “not worth”, and control the vocabulary size with min_df, max_df and max_features.
  • Build a text classifier as a Pipeline (vectorizer + LogisticRegression or MultinomialNB), cross-validate it, read its confusion matrix and its most informative words, and extend it to three sentiment classes.
  • Discover topics with NMF and LDA, and build dense document embeddings with TruncatedSVD (LSA) to find similar reviews by cosine similarity.

Everything on this page runs offline. No library downloads a model or a word list.

The lesson page runs top to bottom in one namespace. The setup block loads the reviews. keep_default_na=False keeps the 51 empty titles as "" instead of NaN.

import html
import re
import textwrap
from collections import Counter
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
pd.set_option("display.max_colwidth", 60)
np.set_printoptions(precision=3, suppress=True)
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
print(reviews.shape)
print(reviews["sentiment"].value_counts().to_dict())
print(reviews.loc[158, "product"], reviews.loc[158, "rating"])
print(reviews.loc[158, "text"])
Output
(3000, 9)
{'positive': 2066, 'negative': 596, 'neutral': 338}
Electric Toothbrush 1
Battery life drains fast. The price is way too high.

Each row is one review. rating is the star rating from 1 to 5. sentiment is derived from it: positive for 4 or 5 stars, negative for 1 or 2, neutral for 3. The text column is what you turn into numbers.

Text as data: corpus, documents and tokens

Section titled “Text as data: corpus, documents and tokens”

NLP has its own words for familiar things:

Term Meaning In this module
Corpus the whole collection of texts the 3,000 reviews
Document one text of the corpus, the unit you classify or compare one review
Token one unit of text after splitting, usually a word battery, died, not
Vocabulary the set of distinct tokens that the model knows, each with an integer id about 380 words

A classifier needs every document as a feature vector of the same length (module 32). Text has no fixed length: one review has 3 words, another has 52. Every method in this module solves that problem in the same order:

flowchart LR
    R["raw text"] --> C["clean<br/>lowercase, unescape"]
    C --> T["tokenize<br/>split into words"]
    T --> V["vectorize<br/>counts or TF-IDF"]
    V --> M["classify"]
    V --> P["find topics"]
    V --> E["embed<br/>and compare"]

Cleaning and tokenizing are plain Python. Vectorizing is where scikit-learn takes over. After that step, text is a matrix like any other, and every model from the earlier modules works on it.

Raw text is messy. The reviews contain HTML entities (&amp; for &), whole reviews in upper case, double spaces, line breaks and typos. Each quirk splits one word into several forms that a model treats as unrelated: Battery, BATTERY and battery are three different strings.

Text cleaning (also called text normalization, module 26) rewrites text into one standard form. Four steps cover most needs:

Step Tool Why Risk
Decode HTML entities html.unescape(text) &amp; becomes &, &#39; becomes '; otherwise amp and 39 turn into words none
Lowercase text.lower() Great and great become one token loses shouting (NEVER AGAIN) and proper names (Apple vs apple)
Collapse whitespace re.sub(r"\s+", " ", text).strip() removes line breaks, tabs, double and edge spaces none for word models
Remove punctuation re.sub(r"[^\w\s']", " ", text) great! and great become one token loses !!! and emoticons such as :(

Decode the entities first. Entity names are case-sensitive: &Eacute; is É and &eacute; is é. Lowercasing first can change an entity into another one, or into one that does not exist.

def clean_text(text: str) -> str:
"""Decode HTML entities, lowercase and collapse whitespace."""
text = html.unescape(text)
text = text.lower()
text = re.sub(r"\s+", " ", text)
return text.strip()
raw = " I&#39;ve used it daily.\nSturdy &amp; WELL MADE!!! "
print(repr(raw))
print(repr(clean_text(raw)))
Output
' I&#39;ve used it daily.\nSturdy &amp; WELL MADE!!! '
"i've used it daily. sturdy & well made!!!"

repr() shows the hidden characters: the edge spaces, the double space and the \n. After cleaning, the text is one line of lowercase words with single spaces. The function keeps punctuation on purpose. The tokenizer in the next section drops it anyway, and the !!! stays available if you want to count it as a feature.

Typos are a caveat, not a cleaning step. The reviews contain qualty, recieved and batery. A cleaning function cannot know every misspelling. A word model sees qualty as a new word that it met only a few times, so the review loses part of its signal. Three fixes exist, from simple to robust:

  1. A replacement dictionary for the typos you found ({"qualty": "quality"}). It fixes only the typos you know.
  2. Dropping rare tokens with min_df (later in this lesson). A rare typo is ignored, not fixed. A frequent typo survives: in this corpus qualty appears 51 times, so min_df=5 keeps it.
  3. Character n-grams (analyzer="char_wb"): features made of letter sequences such as qua and ual. qualty shares most of them with quality, so the two stay similar. Exercise M41-C13 measures this.

A spell checker is a fourth option. It needs a large word list, and it “corrects” product names and slang into wrong words.

Tokenization splits a text into tokens. The simplest tokenizer is str.split(), which splits on whitespace. It leaves punctuation stuck to the words. A regular expression (module 09) that keeps runs of letters, digits and apostrophes works better:

sentence = clean_text("I've had it 2 weeks. Battery died, NOT worth it!")
print(sentence.split())
print(re.findall(r"[a-z0-9']+", sentence))
print(re.findall(r"(?u)\b\w\w+\b", sentence))
Output
["i've", 'had', 'it', '2', 'weeks.', 'battery', 'died,', 'not', 'worth', 'it!']
["i've", 'had', 'it', '2', 'weeks', 'battery', 'died', 'not', 'worth', 'it']
['ve', 'had', 'it', 'weeks', 'battery', 'died', 'not', 'worth', 'it']

The three lines show three tokenizers:

  • split() keeps weeks., died, and it!. These are new “words” that the model has never seen.
  • [a-z0-9']+ finds runs of lowercase letters, digits and apostrophes. It keeps i've in one piece.
  • (?u)\b\w\w+\b is scikit-learn’s default token_pattern: words of two or more word characters. It drops i and 2, and it splits i've into ve. Usually that is fine. When single letters matter (a size s, a grade a), pass your own token_pattern.

Two counts describe a corpus. The number of tokens counts every occurrence. The number of distinct tokens is the vocabulary size. Counter (module 09) gives both:

all_tokens = [
token
for text in reviews["text"].map(clean_text)
for token in re.findall(r"[a-z0-9']+", text)
]
token_counts = Counter(all_tokens)
print(f"{len(all_tokens):,} tokens, {len(token_counts):,} distinct")
print(token_counts.most_common(6))
Output
48,723 tokens, 390 distinct
[('the', 4052), ('is', 1772), ('it', 1498), ('to', 1055), ('this', 1047), ('for', 998)]

The most common tokens are short function words: the, and, it. A stop word is such a frequent word that carries little meaning on its own. Many NLP pipelines remove stop words to shrink the vocabulary. scikit-learn ships a list of 318 English stop words, ENGLISH_STOP_WORDS. Look at what it contains before you use it:

from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
print(len(ENGLISH_STOP_WORDS))
sentiment_words = ["not", "no", "never", "nor", "cannot", "without", "but", "very"]
print([word for word in sentiment_words if word in ENGLISH_STOP_WORDS])
Output
318
['not', 'no', 'never', 'nor', 'cannot', 'without', 'but', 'very']

Two more normalization steps reduce words to a base form:

Method Does Example Needs
Stemming cuts word endings with fixed rules charges, charging → charg rules (NLTK’s Porter stemmer)
Lemmatization maps a word to its dictionary form better → good, arrived → arrive a dictionary and a grammar model (spaCy)

Both help when a corpus is small and its words appear in many forms. This module does not use them: they need extra downloads, and the TF-IDF models here work well without them. Character n-grams (above) and pretrained embeddings (at the end of this lesson) handle word forms without explicit rules.

A bag of words represents each document by how often each vocabulary word appears in it. Word order is thrown away, as if you cut the text into words and shook them in a bag. The result is a document-term matrix: one row per document, one column per vocabulary word, and a count in each cell.

CountVectorizer builds it. Like every scikit-learn transformer, it learns in fit (here: the vocabulary) and applies what it learned in transform:

from sklearn.feature_extraction.text import CountVectorizer
toy_docs = [
"Great battery, fast charging.",
"Battery died. Not worth the money.",
"Great value for the money.",
]
count_vec = CountVectorizer()
toy_counts = count_vec.fit_transform(toy_docs)
toy_table = pd.DataFrame(
toy_counts.toarray(), columns=count_vec.get_feature_names_out()
)
print(toy_table)
print(count_vec.vocabulary_["money"])
Output
battery charging died fast for great money not the value worth
0 1 1 0 1 0 1 0 0 0 0 0
1 1 0 1 0 0 0 1 1 1 0 1
2 0 0 0 0 1 1 1 0 1 1 0
6

CountVectorizer lowercases and tokenizes by itself, with the default token_pattern. get_feature_names_out() returns the vocabulary in column order (alphabetical). vocabulary_ maps each word to its column index: money is column 6.

Two rules follow from fit and transform:

  • A word that was not in the training texts is an out-of-vocabulary (OOV) word. transform ignores it, without an error.
  • Fit the vectorizer on training data only. Fitting it on the test set too is data leakage (module 33): the vocabulary would contain words that the model could not know.
new_counts = count_vec.transform(["Great price, great battery!"])
print(new_counts.toarray())
Output
[[1 0 0 0 0 2 0 0 0 0 0]]

great counts 2 and battery counts 1. price is OOV, so the row has no place for it.

A document uses only a few words of the vocabulary, so almost every cell of the matrix is 0. CountVectorizer returns a sparse matrix from SciPy: a matrix that stores only its non-zero values and their positions. The format is CSR (compressed sparse row), which is fast for row slicing and for matrix products.

corpus_counts = CountVectorizer().fit_transform(reviews["text"].map(clean_text))
n_cells = corpus_counts.shape[0] * corpus_counts.shape[1]
print(type(corpus_counts).__name__, corpus_counts.shape)
print(f"non-zero cells: {corpus_counts.nnz:,} of {n_cells:,}")
print(f"density: {corpus_counts.nnz / n_cells:.2%}")
sparse_bytes = (
corpus_counts.data.nbytes
+ corpus_counts.indices.nbytes
+ corpus_counts.indptr.nbytes
)
print(f"sparse: {sparse_bytes / 1e6:.2f} MB, dense: {n_cells * 8 / 1e6:.1f} MB")
Output
csr_matrix (3000, 376)
non-zero cells: 44,216 of 1,128,000
density: 3.92%
sparse: 0.54 MB, dense: 9.0 MB

The density is the share of non-zero cells: about 4%. The sparse matrix needs about half a megabyte; the same matrix as a dense float array needs 9 MB. The reviews use a small, repetitive vocabulary. Real corpora have tens of thousands of words and a density well below 1%, so the gap grows. A corpus of a million documents and 100,000 words would need 800 GB dense. Keep text matrices sparse. Do not call .toarray() on a real corpus; use it only on a few rows to look at them.

TF-IDF: weight words by how informative they are

Section titled “TF-IDF: weight words by how informative they are”

Raw counts give the as much weight as refund. TF-IDF (term frequency × inverse document frequency) fixes this. A word gets a high weight in a document when it is frequent in that document (high term frequency) and rare in the corpus (high inverse document frequency, or idf).

scikit-learn’s TfidfVectorizer uses these definitions with its default settings. nn is the number of documents, tf⁡(t,d)\operatorname{tf}(t, d) is the count of term tt in document dd, and df⁡(t)\operatorname{df}(t) is the document frequency: the number of documents that contain tt at least once.

idf⁡(t)=ln⁡1+n1+df⁡(t)+1\operatorname{idf}(t) = \ln\frac{1 + n}{1 + \operatorname{df}(t)} + 1 w(t,d)=tf⁡(t,d)⋅idf⁡(t)w(t, d) = \operatorname{tf}(t, d) \cdot \operatorname{idf}(t)

Then each document vector is divided by its L2 norm (module 32), so every row has length 1:

w^(t,d)=w(t,d)∑t′w(t′,d)2\hat{w}(t, d) = \frac{w(t, d)}{\sqrt{\sum_{t'} w(t', d)^2}}

The 1+1 + in the fraction is smoothing (smooth_idf=True): it acts as if one extra document contained every word, so no division by zero can happen. The final +1+ 1 keeps a word that appears in every document from getting a weight of 0. The row normalization makes a long review and a short review comparable.

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vec = TfidfVectorizer()
toy_tfidf = tfidf_vec.fit_transform(toy_docs)
print(pd.Series(tfidf_vec.idf_, index=tfidf_vec.get_feature_names_out()).round(3))
print(pd.DataFrame(toy_tfidf.toarray(), columns=tfidf_vec.get_feature_names_out()))
Output
battery 1.288
charging 1.693
died 1.693
fast 1.693
for 1.693
great 1.288
money 1.288
not 1.693
the 1.288
value 1.693
worth 1.693
dtype: float64
battery charging died fast for great money not the value worth
0 0.428 0.563 0.00 0.563 0.000 0.428 0.000 0.00 0.000 0.000 0.00
1 0.349 0.000 0.46 0.000 0.000 0.000 0.349 0.46 0.349 0.000 0.46
2 0.000 0.000 0.00 0.000 0.517 0.394 0.394 0.00 0.394 0.517 0.00

battery, great, money and the appear in 2 of the 3 documents, so their idf is ln⁡(4/3)+1≈1.288\ln(4/3) + 1 \approx 1.288. The other words appear once: ln⁡(4/2)+1≈1.693\ln(4/2) + 1 \approx 1.693. In document 2, died (rare) outweighs battery (common), although both appear once. Example 3 computes the same formula by hand on three real reviews.

Four options change the formula:

Option Effect Use when
sublinear_tf=True replaces tf by 1+ln⁡(tf⁡)1 + \ln(\operatorname{tf}) long documents repeat a word many times
smooth_idf=False idf becomes ln⁡(n/df⁡)+1\ln(n / \operatorname{df}) + 1 you must match another library’s formula
use_idf=False no idf, only normalized counts as a baseline
norm=None no row normalization you need the raw weights

A bag of words loses word order, so “not worth” and “worth” look almost the same. An n-gram is a sequence of nn consecutive tokens. A bigram has 2 tokens (not worth), a trigram 3. ngram_range=(1, 2) adds every bigram to the single words (unigrams):

bigram_vec = CountVectorizer(ngram_range=(1, 2))
bigram_vec.fit(["Not worth the money."])
print(bigram_vec.get_feature_names_out())
Output
['money' 'not' 'not worth' 'the' 'the money' 'worth' 'worth the']

Now not worth is its own feature, and a model can give it a negative weight while worth stays positive. The price is a much larger vocabulary. Most bigrams are rare, so pair n-grams with a document frequency cut-off:

  • min_df=2 drops terms that appear in fewer than 2 documents (an int is a count; a float such as 0.01 is a share).
  • max_df=0.5 drops terms that appear in more than half of the documents. It acts as an automatic stop-word list, built from the corpus.
  • max_features=5000 keeps only the 5,000 most frequent terms.
clean_reviews = reviews["text"].map(clean_text)
for ngrams, min_df in [((1, 1), 1), ((1, 2), 1), ((1, 2), 2), ((1, 3), 2)]:
vec = CountVectorizer(ngram_range=ngrams, min_df=min_df).fit(clean_reviews)
print(f"ngram_range={ngrams}, min_df={min_df}: {len(vec.vocabulary_):6,} terms")
Output
ngram_range=(1, 1), min_df=1: 376 terms
ngram_range=(1, 2), min_df=1: 3,532 terms
ngram_range=(1, 2), min_df=2: 2,310 terms
ngram_range=(1, 3), min_df=2: 5,642 terms

Bigrams multiply the vocabulary by about 9. min_df=2 removes about a third of the terms: the phrases that appear in only one review.

Here is why stop-word removal and sentiment do not mix. With stop_words="english", both texts below lose not and the, and their vectors become identical:

stop_vec = CountVectorizer(stop_words="english").fit(clean_reviews)
pair = stop_vec.transform(["Not worth the money.", "Worth the money."])
print(pair.toarray().sum(axis=1), (pair[0] != pair[1]).nnz)
Output
[2 2] 0

Each text keeps 2 tokens (worth and money), and the two rows differ in 0 cells. No model can tell them apart.

Text classification assigns a label to each document: positive or negative, spam or not spam, which team gets a ticket. With a vectorizer, it is ordinary supervised learning. Put the vectorizer and the model in one Pipeline (module 34):

flowchart LR
    X["review texts"] --> V["TfidfVectorizer<br/>fit: vocabulary, idf"]
    V --> S["sparse matrix<br/>n × vocabulary"]
    S --> M["LogisticRegression<br/>fit: one weight per term"]
    M --> P["predict:<br/>positive / negative"]

The pipeline matters more for text than for tables. The vocabulary and the idf values are learned from data. Inside a pipeline, cross-validation refits them on each training fold, so the validation fold stays unseen. A vectorizer fitted on all the data first leaks the test vocabulary into training (exercise M41-C08).

Three linear models suit sparse text features:

Model Idea Strengths Watch out
LogisticRegression one weight per term, sigmoid of the sum (module 32) calibrated probabilities, readable weights tune C (default 1 underfits on TF-IDF)
MultinomialNB counts how often each word appears in each class very fast, strong on small data probabilities are overconfident
LinearSVC maximum-margin linear classifier often the most accurate no predict_proba

Multinomial naive Bayes treats a document as words drawn from a class-specific word distribution. It estimates P(word∣class)P(\text{word} \mid \text{class}) from counts and assumes that words are independent given the class (the “naive” part). For a new document it adds up the log-probabilities of its words for each class and picks the larger sum:

log⁡P(c∣d)=log⁡P(c)+∑t∈dtf⁡(t,d)log⁡P(t∣c)+const\log P(c \mid d) = \log P(c) + \sum_{t \in d} \operatorname{tf}(t, d) \log P(t \mid c) + \text{const}

The parameter alpha=1.0 adds 1 to every count (Laplace smoothing), so a word that never appeared with a class does not get probability 0.

Tree models and k-nearest neighbors are a poor fit here. Trees split on one word at a time and need thousands of splits. KNN suffers in 10,000 dimensions. Linear models are the standard baseline for text.

Sentiment analysis finds the opinion in a text: positive, negative or neutral, sometimes with a score. Two approaches exist:

  • A sentiment lexicon is a hand-made word list with a score per word (great +1, broke −1). The sentiment of a text is the sum of its scores. It needs no training data and is easy to explain. It misses negation (“not great”), context and domain words.
  • A learned classifier (the pipeline above) learns the weights from labeled examples. It needs labels, but it learns the words of your domain, such as refund and returning.

A five-word lexicon shows both sides:

LEXICON = {"great": 1, "love": 1, "excellent": 1, "broke": -1, "awful": -1}
def lexicon_score(text: str) -> int:
"""Sum the lexicon scores of the tokens of one text."""
return sum(LEXICON.get(token, 0) for token in re.findall(r"[a-z']+", text.lower()))
for text in ["Great value, love it!", "It broke. Awful.", "Not great at all."]:
print(f"{lexicon_score(text):+d} {text}")
Output
+2 Great value, love it!
-2 It broke. Awful.
+1 Not great at all.

The third line scores +1 although it is negative: the lexicon does not see not. Libraries such as VADER add rules for negation and intensifiers. The star rating gives labels for free, so this module learns the weights instead. A rating is a noisy label. Label noise means that some training labels are wrong: about 6% of the 1-, 2-, 4- and 5-star reviews in this dataset have a text whose tone contradicts the stars, so no model can reach an accuracy of 1.0.

Binary sentiment (positive vs negative) is the easier task. A neutral class is harder in most data, because neutral texts mix both tones. Example 6 adds it. A finer task, aspect-based sentiment analysis, rates each aspect of a product separately: “battery: negative, delivery: positive”. Exercise M41-X02 builds a simple version.

Topic modeling finds the themes of a corpus without labels. It is unsupervised learning (module 39) on a document-term matrix. A topic is a weighted list of words that tend to appear together, such as battery charge holds days. Each document gets a share of each topic.

Non-negative matrix factorization (NMF) writes the TF-IDF matrix XX (nn documents × pp terms) as the product of two smaller matrices with no negative values:

X≈WH,W∈R≥0n×k,  H∈R≥0k×pX \approx W H, \qquad W \in \mathbb{R}_{\ge 0}^{n \times k},\; H \in \mathbb{R}_{\ge 0}^{k \times p}

Row ii of WW holds the topic weights of document ii. Row jj of HH holds the word weights of topic jj. Because no value is negative, a document is built only by adding topics, which makes the topics easy to read. NMF minimizes the reconstruction error ∥X−WH∥F\lVert X - WH \rVert_F, the size of the part of XX that the topics do not explain.

Latent Dirichlet allocation (LDA) is a probabilistic model. It assumes that each document is a mixture of topics and that each topic is a probability distribution over words. It fits these distributions to the raw word counts. A Dirichlet prior (a distribution over mixtures) makes each document use a few topics and each topic use a few words.

NMF LDA
Input TF-IDF (or counts) raw counts (CountVectorizer)
Output per document non-negative topic weights topic probabilities that sum to 1
Speed fast slower
Short texts (reviews, tweets) usually cleaner topics often mixed topics
Long texts (articles, papers) good the classic choice
Class in scikit-learn NMF LatentDirichletAllocation

Both need the number of topics n_components in advance. No score picks it for you. Fit a few values, read the top words of each topic and choose the smallest number that gives distinct, nameable topics. The reconstruction error always falls as n_components grows, so it shows a trade-off, not an answer. Remove stop words and very frequent words here (stop_words="english", max_df=0.5): topics should be about content words.

Embeddings: dense vectors that capture meaning

Section titled “Embeddings: dense vectors that capture meaning”

In a bag of words, every word is its own dimension. great and excellent are two columns that have nothing in common, so two reviews with no shared words have a cosine similarity of 0, even when they say the same thing. Such vectors are sparse (mostly zeros) and very long (one dimension per word).

An embedding maps each word or document to a dense vector: a short vector (50 to 1,000 numbers) in which most values are non-zero. Similar meanings get nearby vectors. The idea rests on the distributional hypothesis: words that appear in similar contexts have similar meanings. battery, life and lasts keep the same company in reviews, so their vectors end up close (Example 8).

The simplest embedding is latent semantic analysis (LSA): a truncated SVD (module 23) of the TF-IDF matrix. It keeps the kk strongest directions of the matrix, so each review becomes a dense vector of kk numbers. LSA is defined without centering the columns, which is what TruncatedSVD does, directly on a sparse matrix. (PCA centers the columns first; on sparse input it supports only its arpack and covariance_eigh solvers.) Example 8 builds it and finds similar reviews by cosine similarity, the cosine of the angle between two vectors (module 32).

LSA learns from your corpus only. Modern NLP uses pretrained embeddings: vectors learned once from billions of words and then reused.

Method What it embeds Idea Notes
LSA (TruncatedSVD) documents and words SVD of the TF-IDF matrix fast, offline, corpus vocabulary only
word2vec, GloVe words predict a word from its neighbors, or factor co-occurrence counts one vector per word, whatever the context
fastText words and subwords word2vec on character n-grams handles typos and unseen words
Transformer sentence embeddings whole sentences a transformer (a neural network that reads every word in the context of every other word) trained on large corpora the current default for search and clustering

A pretrained sentence model works like a vectorizer. This code needs the sentence-transformers package and downloads a model of about 90 MB on its first run, so it is not run on this page:

embed_reviews.py
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
vectors = model.encode(["The battery died after two days.", "Charge lasts all week."])
print(vectors.shape) # (2, 384): one dense vector of 384 numbers per text

Module 42 builds neural networks with PyTorch, the foundation of these models. Capstone 7 compares a TF-IDF baseline with a PyTorch model on these reviews.

Goal: Prepare the review texts for every later model. Find the quirks, clean them, and measure what cleaning changes in the vocabulary.

quirks = {
"HTML entity": reviews["text"].str.contains("&amp;|&#39;", regex=True),
"upper case": reviews["text"].str.isupper(),
"double space": reviews["text"].str.strip().str.contains(" ", regex=False),
"line break": reviews["text"].str.contains("\n", regex=False),
"edge space": reviews["text"] != reviews["text"].str.strip(),
}
for name, mask in quirks.items():
print(f"{name:13} {mask.sum():4}")
Output
HTML entity 62
upper case 39
double space 96
line break 23
edge space 95

Each mask is a boolean Series, and sum() counts its True values. The double-space check strips the edges first, so it does not count the edge spaces twice. The counts overlap: one review can have several quirks. These numbers match the data dictionary, so the checks find what they should.

Step 2 — Apply the cleaning function to the column

Section titled “Step 2 — Apply the cleaning function to the column”
reviews["clean"] = reviews["text"].map(clean_text)
changed = reviews["text"] != reviews["clean"]
print(f"{changed.sum():,} of {len(reviews):,} texts changed")
print(repr(reviews.loc[quirks["HTML entity"], "text"].iloc[0]))
print(repr(reviews.loc[quirks["HTML entity"], "clean"].iloc[0]))
Output
3,000 of 3,000 texts changed
'I&#39;ve been using it for 2 weeks now. The price is way too high. But sturdy and built to last.'
"i've been using it for 2 weeks now. the price is way too high. but sturdy and built to last."

Series.map calls clean_text once per review. Every text changes, because every review starts with a capital letter. The original column stays in the DataFrame, so you can always compare.

Step 3 — Measure the effect on the vocabulary

Section titled “Step 3 — Measure the effect on the vocabulary”
raw_vocab = CountVectorizer(lowercase=False).fit(reviews["text"]).vocabulary_
clean_vocab = CountVectorizer(lowercase=False).fit(reviews["clean"]).vocabulary_
print(len(raw_vocab), "->", len(clean_vocab), "distinct tokens")
for token in ["amp", "39", "Battery", "BATTERY", "battery"]:
print(f"{token:8} raw: {token in raw_vocab!s:5} clean: {token in clean_vocab}")
Output
642 -> 376 distinct tokens
amp raw: True clean: False
39 raw: True clean: False
Battery raw: True clean: False
BATTERY raw: True clean: False
battery raw: True clean: True

lowercase=False switches off the vectorizer’s own lowercasing, so you see the raw effect. Before cleaning, amp and 39 are “words” and battery exists in three spellings. Cleaning removes the fake tokens and merges the spellings, so the vocabulary shrinks.

Step 4 — Find the typos that cleaning cannot fix

Section titled “Step 4 — Find the typos that cleaning cannot fix”
clean_counts = Counter(re.findall(r"[a-z']+", " ".join(reviews["clean"])))
typos = ["qualty", "recieved", "definately", "batery", "teh", "recomend"]
print({typo: clean_counts[typo] for typo in typos})
print({word: clean_counts[word] for word in ["quality", "received", "battery"]})
Output
{'qualty': 51, 'recieved': 1, 'definately': 8, 'batery': 13, 'teh': 54, 'recomend': 17}
{'quality': 851, 'received': 32, 'battery': 359}

The typos appear from 1 to 54 times; the correct spellings appear far more often (quality 851 times). A model learns little from the rare form. A stop-word list removes the but keeps teh, which then looks like a content word. A small dictionary of known typos would fix these, but new typos keep arriving. min_df removes only the rare ones: every typo in this list except recieved appears more than 5 times and survives min_df=5. For this corpus the loss is small, so the lesson leaves the typos in place. Character n-grams (exercise M41-C13) are the robust fix.

Common mistakes:

  • Lowercasing before html.unescape. It works for &amp;, but entity names are case-sensitive in general (&Eacute; is É, &eacute; is é). Decode first.
  • Cleaning with str.replace("&amp;", "&") only. Other entities (&#39;, &quot;) survive. html.unescape handles all of them.
  • Overwriting the original text column. Keep the raw text, so you can debug the cleaning and change it later.

Example 2 — Build a bag of words by hand

Section titled “Example 2 — Build a bag of words by hand”

Goal: Build the document-term matrix of three reviews with plain Python, then check that CountVectorizer gives the same matrix. Knowing the mechanics helps you debug a vectorizer that behaves oddly.

sample = reviews.loc[[40, 7, 11], "clean"].tolist()
token_pattern = r"(?u)\b\w\w+\b"
sample_tokens = [re.findall(token_pattern, text) for text in sample]
for tokens in sample_tokens:
print(len(tokens), tokens[:8])
Output
14 ['replaced', 'my', 'old', 'one', 'with', 'this', 'the', 'seller']
24 ['replaced', 'my', 'old', 'one', 'with', 'this', 'the', 'quality']
23 ['delivery', 'took', 'only', 'two', 'days', 'customer', 'service', 'was']

The pattern is scikit-learn’s default token_pattern, so the hand-made version and the library see the same tokens.

vocab = sorted({token for tokens in sample_tokens for token in tokens})
word_index = {word: i for i, word in enumerate(vocab)}
print(len(vocab), vocab[:10])
print(word_index["quality"])
Output
46 ['awful', 'better', 'build', 'but', 'customer', 'days', 'delivery', 'expected', 'for', 'happy']
25

The set comprehension collects each distinct token once. Sorting it gives the same alphabetical column order as CountVectorizer. The dictionary word_index plays the role of vocabulary_.

by_hand = np.zeros((len(sample), len(vocab)), dtype=np.int64)
for row, tokens in enumerate(sample_tokens):
for token, count in Counter(tokens).items():
by_hand[row, word_index[token]] = count
print(by_hand.shape, by_hand.sum(axis=1))
print(by_hand[:, word_index["the"]])
Output
(3, 46) [14 24 23]
[1 3 0]

Each row holds the counts of one review. The row sums equal the token counts from step 1. the appears 1, 3 and 0 times.

sample_vec = CountVectorizer()
sample_matrix = sample_vec.fit_transform(sample)
print(list(sample_vec.get_feature_names_out()) == vocab)
print(np.array_equal(sample_matrix.toarray(), by_hand))
Output
True
True

Same vocabulary, same order, same counts. CountVectorizer does exactly this, in fast compiled code, and stores the result sparse.

Common mistakes:

  • Building the vocabulary from an unsorted set. The column order then changes between runs, because set order of strings is not stable between Python processes.
  • Using a different tokenizer for the hand-made version. str.split() keeps punctuation, so the counts never match.
  • Forgetting that CountVectorizer lowercases by default. Pass lowercase=False when case carries meaning.

Example 3 — Compute TF-IDF by hand and match scikit-learn

Section titled “Example 3 — Compute TF-IDF by hand and match scikit-learn”

Goal: Turn the counts of Example 2 into TF-IDF weights with the smooth idf formula and the L2 normalization, and prove that the result equals TfidfVectorizer.

Step 1 — Count the documents that contain each word

Section titled “Step 1 — Count the documents that contain each word”
n_docs = by_hand.shape[0]
doc_freq = (by_hand > 0).sum(axis=0)
for word in ["the", "quality", "replacement"]:
print(word, doc_freq[word_index[word]])
Output
the 2
quality 2
replacement 1

by_hand > 0 marks the cells where a word appears at least once. Summing down each column (axis=0) counts the documents per word.

idf = np.log((1 + n_docs) / (1 + doc_freq)) + 1
for word in ["the", "quality", "replacement"]:
print(f"{word:12} {idf[word_index[word]]:.3f}")
Output
the 1.288
quality 1.288
replacement 1.693

This is ln⁡1+n1+df⁡+1\ln\frac{1+n}{1+\operatorname{df}} + 1 for all words at once. np.log is the natural logarithm. A word in 2 of 3 reviews gets a smaller idf than a word in only 1.

Step 3 — Multiply and normalize each row

Section titled “Step 3 — Multiply and normalize each row”
weights = by_hand * idf
norms = np.linalg.norm(weights, axis=1, keepdims=True)
tfidf_by_hand = weights / norms
print(np.linalg.norm(tfidf_by_hand, axis=1))
Output
[1. 1. 1.]

Broadcasting (module 23) multiplies every row by the idf vector. keepdims=True keeps the norms as a column, so each row is divided by its own norm. Every row now has length 1.

sample_tfidf = TfidfVectorizer().fit_transform(sample)
print(np.allclose(sample_tfidf.toarray(), tfidf_by_hand))
row = pd.Series(tfidf_by_hand[2], index=vocab).sort_values(
ascending=False, kind="stable"
)
print(row.head(4).round(3).to_dict())
print(row[["quality", "the"]].round(3).to_dict())
Output
True
{'better': 0.224, 'build': 0.224, 'customer': 0.224, 'days': 0.224}
{'quality': 0.17, 'the': 0.0}

np.allclose confirms that the two matrices agree to floating-point precision. The top weights of review 3 are tied: they belong to words that appear once in this review and in no other sample review. quality also appears in review 2, so its idf and its weight are lower. the is missing from review 3, so its weight is 0.

Common mistakes:

  • Using np.log10 or log2. scikit-learn uses the natural log.
  • Forgetting the final + 1 or the smoothing 1 + terms. The weights then differ slightly from TfidfVectorizer, and allclose fails.
  • Normalizing the columns instead of the rows. Each document gets length 1, so use axis=1.

Example 4 — Classify positive and negative reviews

Section titled “Example 4 — Classify positive and negative reviews”

Goal: Train a model that tells positive from negative reviews, so a support team sees unhappy customers first. Compare it with a baseline, cross-validate it and read its errors in a confusion matrix.

Step 1 — Split the data and score a baseline

Section titled “Step 1 — Split the data and score a baseline”
from sklearn.dummy import DummyClassifier
from sklearn.model_selection import train_test_split
binary = reviews[reviews["sentiment"] != "neutral"]
X_train, X_test, y_train, y_test = train_test_split(
binary["clean"], binary["sentiment"],
test_size=0.25, stratify=binary["sentiment"], random_state=42,
)
dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print(len(X_train), len(X_test))
print(f"baseline accuracy: {dummy.score(X_test, y_test):.3f}")
Output
1996 666
baseline accuracy: 0.776

The neutral reviews are left out for now. stratify keeps the share of each class equal in both parts. A model that always says “positive” is right 77.6% of the time. Every real model must beat that clearly.

Step 2 — Fit a TF-IDF + logistic regression pipeline

Section titled “Step 2 — Fit a TF-IDF + logistic regression pipeline”
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.pipeline import make_pipeline
sentiment_model = make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=1000))
sentiment_model.fit(X_train, y_train)
y_pred = sentiment_model.predict(X_test)
print(classification_report(y_test, y_pred, digits=3))
Output
precision recall f1-score support
negative 0.820 0.705 0.758 149
positive 0.918 0.956 0.936 517
accuracy 0.899 666
macro avg 0.869 0.830 0.847 666
weighted avg 0.896 0.899 0.897 666

The input of the pipeline is a Series of strings: the vectorizer is the first step, so fit and predict accept raw text. Accuracy rises from 0.776 to about 0.90. Recall on the negative class is lower than on the positive class. The negative class is smaller, so the model sees fewer examples of it.

Step 3 — Compare models with cross-validation

Section titled “Step 3 — Compare models with cross-validation”
from sklearn.model_selection import cross_val_score
from sklearn.naive_bayes import MultinomialNB
candidates = {
"tfidf + LR (C=1)": make_pipeline(
TfidfVectorizer(), LogisticRegression(max_iter=1000)
),
"tfidf + LR (C=10)": make_pipeline(
TfidfVectorizer(), LogisticRegression(C=10, max_iter=1000)
),
"tfidf 1-2 + LR (C=10)": make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=2),
LogisticRegression(C=10, max_iter=1000),
),
"counts + NB": make_pipeline(CountVectorizer(), MultinomialNB()),
"counts 1-2 + NB": make_pipeline(
CountVectorizer(ngram_range=(1, 2)), MultinomialNB()
),
}
for name, model in candidates.items():
scores = cross_val_score(model, X_train, y_train, cv=5)
print(f"{name:22} {scores.mean():.3f} ± {scores.std():.3f}")
Output
tfidf + LR (C=1) 0.889 ± 0.018
tfidf + LR (C=10) 0.900 ± 0.014
tfidf 1-2 + LR (C=10) 0.908 ± 0.016
counts + NB 0.907 ± 0.010
counts 1-2 + NB 0.917 ± 0.013

Cross-validation scores each pipeline on 5 splits of the training set, and the vectorizer is refitted inside every split. The test set stays untouched. Three findings. C=10 beats the default C=1, because TF-IDF values are small and the default penalty shrinks the weights too much. Naive Bayes on counts is as good as the tuned logistic regression, and it trains faster. Bigrams help both models a little. The top three scores differ by less than one standard deviation, so treat them as equal. The next steps use the bigram logistic regression, because its probabilities and weights are easier to read.

Step 4 — Plot the confusion matrix of the tuned model

Section titled “Step 4 — Plot the confusion matrix of the tuned model”
from sklearn.metrics import ConfusionMatrixDisplay
best_binary = candidates["tfidf 1-2 + LR (C=10)"].fit(X_train, y_train)
print(f"test accuracy: {best_binary.score(X_test, y_test):.3f}")
ConfusionMatrixDisplay.from_estimator(best_binary, X_test, y_test, cmap="Blues")
plt.title("Positive vs negative reviews (test set)")
plt.tight_layout()
plt.show()
Output
test accuracy: 0.917
Confusion matrix of the tuned sentiment model: 123 negative and 488 positive test reviews are correct; 26 negative reviews are predicted positive and 29 positive reviews negative.
Confusion matrix of TF-IDF (1-2 grams) + logistic regression on 666 test reviews.

Rows are the true classes, columns the predictions. The diagonal holds the correct answers. The two error cells are about the same size: 26 negative reviews called positive and 29 positive reviews called negative. Negative recall is now 123 / 149 ≈ 0.83, up from 0.705 with the default model. Example 5 reads the errors.

Common mistakes:

  • Passing a DataFrame with one column (binary[["clean"]]) to the pipeline. Iterating over a DataFrame gives its column names, so the vectorizer learns the one-word vocabulary {'clean': 0} from one “document”, and fit fails with ValueError: Found input variables with inconsistent numbers of samples. Pass a Series or a list of strings.
  • Reporting accuracy only. With 78% positive reviews, accuracy hides a weak negative class. Read recall and F1 per class.
  • Tuning on the test set. Choose models with cross-validation on the training set and look at the test set once, at the end.

Example 5 — Read the classifier: informative n-grams and errors

Section titled “Example 5 — Read the classifier: informative n-grams and errors”

Goal: Find which words and phrases drive the predictions, and read the reviews that the model gets wrong. A model you can explain is a model you can trust and fix.

Step 1 — List the strongest weights with their document frequency

Section titled “Step 1 — List the strongest weights with their document frequency”
vectorizer = best_binary.named_steps["tfidfvectorizer"]
classifier = best_binary.named_steps["logisticregression"]
coefs = pd.Series(classifier.coef_[0], index=vectorizer.get_feature_names_out())
train_docs = (vectorizer.transform(X_train) > 0).sum(axis=0).A1 # reviews per term
docs = pd.Series(train_docs, index=coefs.index)
print(classifier.classes_)
for term in [*coefs.nsmallest(5).index, *coefs.nlargest(5).index]:
print(f"{term:14} {coefs[term]:+.2f} in {docs[term]:3} training reviews")
Output
['negative' 'positive']
avoid -4.62 in 70 training reviews
not -3.92 in 255 training reviews
disappointing -3.76 in 20 training reviews
confusing -3.56 in 15 training reviews
never -3.39 in 94 training reviews
premium +4.20 in 92 training reviews
one wore +3.45 in 4 training reviews
excellent +3.23 in 92 training reviews
quickly +3.16 in 59 training reviews
not cheap +3.01 in 41 training reviews

classes_ is sorted alphabetically, so the second class (positive) is the “1” class. A positive weight pushes towards positive, a negative weight towards negative. Most strong terms are plausible and frequent: avoid, not and disappointing on the negative side, premium and excellent on the positive side. Two cases need a closer look:

  • one wore has the second-largest positive weight, but it appears in only 4 training reviews. It comes from “this one wore out after a month”, a complaint inside mixed 4-star reviews. The model memorized those few reviews; the weight is noise.
  • drains (a battery that drains fast) is a real complaint, but it rests on only 7 reviews.

With min_df=2 and C=10, the model is free to give large weights to terms seen in a handful of reviews. Such weights fit the training labels, including the noisy ones, and say little about the language. Always read weights next to the document frequency.

for term in ["not worth", "worth", "not cheap", "cheap", "never", "again never"]:
print(f"{term:12} {coefs[term]:+.2f} in {docs[term]:3} training reviews")
Output
not worth -1.52 in 49 training reviews
worth +0.97 in 132 training reviews
not cheap +3.01 in 41 training reviews
cheap -1.63 in 122 training reviews
never -3.39 in 94 training reviews
again never +2.76 in 2 training reviews

The bigram not worth has a strong negative weight, while worth alone leans positive. not cheap (from “not cheap quality at all”) is positive, while cheap is negative. A unigram model cannot express that. This is what the bigrams buy.

The last line shows a side effect. The tokenizer drops punctuation, so bigrams cross sentence ends: “never again. never again!!!” yields the bigram again never. It appears in only 2 training reviews, both rated positive although their text is a complaint (mis-clicked ratings), so the model gives it a positive weight. Rare bigrams like this one fit label noise.

Step 3 — Refit for reading and plot the top weights

Section titled “Step 3 — Refit for reading and plot the top weights”
readable = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=10),
LogisticRegression(C=3, max_iter=1000),
).fit(X_train, y_train)
print(f"test accuracy: {readable.score(X_test, y_test):.3f}")
readable_coefs = pd.Series(
readable[-1].coef_[0], index=readable[0].get_feature_names_out()
)
top_terms = pd.concat(
[readable_coefs.nsmallest(10), readable_coefs.nlargest(10)]
).sort_values()
colors = ["#c0392b" if w < 0 else "#2471a3" for w in top_terms]
plt.figure(figsize=(7, 5))
plt.barh(top_terms.index, top_terms.to_numpy(), color=colors)
plt.axvline(0, color="gray", linewidth=0.8)
plt.xlabel("logistic regression weight (positive class)")
plt.title("The 20 strongest terms (min_df=10, C=3)")
plt.tight_layout()
plt.show()
Output
test accuracy: 0.914
Horizontal bar chart of the 20 strongest weights of the refitted model: avoid, not, never and disappointing on the left in red; premium, great, impressive and love it on the right in blue.
The 10 most negative and 10 most positive terms of a sentiment model refitted with min_df=10 and C=3.

The refitted model keeps only terms that appear in at least 10 training reviews, and C=3 shrinks the weights more. Its test accuracy, 0.914, is almost the same as before (0.917), but the noise terms are gone. Every term in the chart is backed by many reviews. Some are still fragments: way comes from “way too high” and five from “five stars”. Use the strict model to read and explain; use cross-validation to choose the model you deploy.

test_view = pd.DataFrame({"text": X_test, "true": y_test})
test_view["pred"] = best_binary.predict(X_test)
test_view["p_positive"] = best_binary.predict_proba(X_test)[:, 1]
errors = test_view[test_view["true"] != test_view["pred"]]
print(len(errors), "errors")
worst = errors.assign(confidence=(errors["p_positive"] - 0.5).abs())
for _, row in worst.nlargest(4, "confidence").iterrows():
print(f"{row['true']}, p_positive={row['p_positive']:.3f}")
print(textwrap.indent(textwrap.fill(row["text"], width=88), " "))
Output
55 errors
negative, p_positive=0.997
the seller was quite helpful. mine is sturdy and built to last. the price is hard to
beat. highly recommend!
negative, p_positive=0.997
sturdy and built to last. the price is great for what you get.
negative, p_positive=0.995
i've been using it for 7 weeks now. the overall quality is excellent. customer service
went above and beyond. highly recommend!
negative, p_positive=0.991
the delivery arrived in perfect condition. this one shows no signs of wear after months.
very happy with this purchase.

The most confident errors are not model failures. Their texts are clearly positive, but their label is negative: these are the mis-clicked ratings that the data dictionary describes. The model is right and the label is wrong. In a real project, you would send such reviews for a second look instead of training harder on them.

Common mistakes:

  • Reading weights of a model whose features have very different scales. TF-IDF rows have length 1, so the weights are comparable; raw counts of a long text are not.
  • Reading a weight as “the effect of a word” in isolation. Correlated terms share the weight: refund and refund processed split it between them.
  • Treating every error as a model problem. Read the errors first. Label noise sets a ceiling on accuracy.

Goal: A dashboard needs three groups: positive, neutral and negative. Train a three-class model on all 3,000 reviews and see which classes it confuses.

Step 1 — Split all reviews into three classes

Section titled “Step 1 — Split all reviews into three classes”
X3_train, X3_test, y3_train, y3_test = train_test_split(
reviews["clean"], reviews["sentiment"],
test_size=0.25, stratify=reviews["sentiment"], random_state=42,
)
print(y3_train.value_counts(normalize=True).round(3).to_dict())
Output
{'positive': 0.689, 'negative': 0.199, 'neutral': 0.112}

The neutral class is the smallest: about 11% of the reviews.

Step 2 — Fit the same pipeline with three classes

Section titled “Step 2 — Fit the same pipeline with three classes”
three_class = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=2),
LogisticRegression(C=10, max_iter=1000),
)
three_class.fit(X3_train, y3_train)
y3_pred = three_class.predict(X3_test)
print(classification_report(y3_test, y3_pred, digits=3))
neutral_texts = reviews.loc[reviews["sentiment"] == "neutral", "clean"]
print(neutral_texts.str.contains("not bad, not great").sum(), "of", len(neutral_texts))
Output
precision recall f1-score support
negative 0.800 0.779 0.789 149
neutral 0.867 0.765 0.812 85
positive 0.915 0.940 0.927 516
accuracy 0.888 750
macro avg 0.861 0.828 0.843 750
weighted avg 0.887 0.888 0.887 750
67 of 338

The code does not change: LogisticRegression handles more than two classes by itself (with a multinomial loss, one weight vector per class). Neutral reviews are easier here than in most real data: the last line shows that 67 of the 338 neutral reviews contain the set phrase “not bad, not great”. Negative recall is the weak spot.

Step 3 — Read the three-class confusion matrix

Section titled “Step 3 — Read the three-class confusion matrix”
from sklearn.metrics import confusion_matrix
labels = ["negative", "neutral", "positive"]
cm = confusion_matrix(y3_test, y3_pred, labels=labels)
print(pd.DataFrame(cm, index=[f"true {c}" for c in labels], columns=labels))
neg_as_pos = (y3_test == "negative") & (y3_pred == "positive")
for text in X3_test[neg_as_pos].head(3):
print(textwrap.fill(text, width=90, initial_indent="- ", subsequent_indent=" "))
Output
negative neutral positive
true negative 116 4 29
true neutral 4 65 16
true positive 25 6 485
- the price is super high for what it is. the qualty of the book is quite poor.
- replaced my old one with this. not easy to use at all. the overall quality is not what i
expected. never again.
- this is my second one. delivery was quite late. the mat broke on the second use. but not
cheap quality at all. never again.

Most errors are between negative and positive, not with neutral. The three printed reviews are rated negative but predicted positive, and all three are real complaints: these are model errors, not label errors. The first hides quality behind the typo qualty. The second negates positive words (not easy to use, not what i expected). The third contains the positive phrase not cheap quality at all next to a broken mat. A bag of n-grams reads phrases, not the argument of a whole review. (textwrap.fill only wraps the long texts for printing.)

balanced = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=2),
LogisticRegression(C=10, max_iter=1000, class_weight="balanced"),
)
balanced.fit(X3_train, y3_train)
y3_bal = balanced.predict(X3_test)
report = classification_report(y3_test, y3_bal, output_dict=True)
for label in labels:
print(f"{label:9} recall {report[label]['recall']:.3f}")
print(f"macro F1 {report['macro avg']['f1-score']:.3f}")
Output
negative recall 0.866
neutral recall 0.882
positive recall 0.901
macro F1 0.857

class_weight="balanced" weights each class by the inverse of its size, so errors on the small classes cost more. Negative and neutral recall rise; positive recall falls a little. Which model is better depends on the use: a support team that wants to catch every unhappy customer prefers the balanced model.

Common mistakes:

  • Training a binary model and calling every uncertain prediction “neutral”. A probability near 0.5 means “mixed or unclear”, which is not the same as a neutral opinion. Train on real neutral labels when you have them.
  • Comparing three-class accuracy with binary accuracy. The tasks differ; compare per-class recall and macro F1.
  • Forgetting stratify. With a small class, an unlucky split can leave very few neutral reviews in the test set.

Example 7 — Discover topics with NMF and LDA

Section titled “Example 7 — Discover topics with NMF and LDA”

Goal: A product team asks: “What do customers write about?” Find the main themes of the reviews without any labels, and check how they differ by product category.

Step 1 — Build a TF-IDF matrix for topics

Section titled “Step 1 — Build a TF-IDF matrix for topics”
topic_vec = TfidfVectorizer(stop_words="english", min_df=5, max_df=0.5)
topic_tfidf = topic_vec.fit_transform(reviews["clean"])
topic_terms = topic_vec.get_feature_names_out()
print(topic_tfidf.shape)
Output
(3000, 279)

For topics, stop words go out: not and the would only blur the themes. min_df=5 drops rare words (frequent typos such as qualty and teh stay), and max_df=0.5 drops anything that appears in more than half of the reviews. The vocabulary shrinks to a few hundred content words.

from sklearn.decomposition import NMF
def top_words(components: np.ndarray, terms: np.ndarray, n: int = 6) -> list[str]:
"""Return the n heaviest words of each topic as one string per topic."""
return [" ".join(terms[np.argsort(row)[::-1][:n]]) for row in components]
nmf = NMF(n_components=10, init="nndsvda", random_state=42, max_iter=1000)
doc_topics = nmf.fit_transform(topic_tfidf)
for i, words in enumerate(top_words(nmf.components_, topic_terms)):
print(i, words)
Output
0 money value delivery worth excellent time
1 battery charge holds days fast charges
2 sturdy built far long say early
3 feels material quality premium cheap solid
4 price point beat lower stores hard
5 great customer service question looks attention
6 months lasted durable use daily wear
7 day refund seller processed weeks ve
8 size true fit fits perfect glove
9 recommend friends definitely highly helpful package

fit_transform returns WW, the topic weights per review. components_ is HH, the word weights per topic. init="nndsvda" starts from a (randomized) SVD. With a fixed random_state the result is reproducible, and it converges faster than a random start. Most topics are easy to name: value and delivery, battery, sturdiness, material quality, price, customer service, durability, refunds, size and fit, recommendation.

Step 3 — Name the topics and profile the categories

Section titled “Step 3 — Name the topics and profile the categories”
topic_names = [
"value", "battery", "sturdy", "material", "price",
"service", "durability", "refund", "size/fit", "recommend",
]
reviews["topic"] = [topic_names[i] for i in doc_topics.argmax(axis=1)]
share = pd.crosstab(reviews["category"], reviews["topic"], normalize="index")
print(share[["battery", "size/fit", "durability", "refund"]].round(2))
Output
topic battery size/fit durability refund
category
Beauty 0.09 0.00 0.01 0.13
Books 0.02 0.00 0.00 0.11
Clothing 0.02 0.41 0.10 0.05
Electronics 0.32 0.00 0.14 0.07
Home 0.09 0.01 0.15 0.10
Sports 0.13 0.12 0.16 0.06

argmax(axis=1) gives each review its strongest topic. The names are your interpretation, so read a few reviews per topic before you trust them. The cross-table shows that the topics follow the products: battery talk comes from Electronics, size and fit from Clothing (and from the shoes in Sports). Books have neither. The topic model found this structure without seeing the categories.

ks = [4, 6, 8, 10, 12, 14]
errors_k = [
NMF(n_components=k, init="nndsvda", random_state=42, max_iter=1000)
.fit(topic_tfidf)
.reconstruction_err_
for k in ks
]
plt.figure(figsize=(6, 3.5))
plt.plot(ks, errors_k, marker="o")
plt.xlabel("number of topics (n_components)")
plt.ylabel("reconstruction error")
plt.title("NMF: the error falls steadily, with no clear elbow")
plt.tight_layout()
plt.show()
print([round(float(e), 1) for e in errors_k])
Output
[51.4, 50.2, 49.1, 48.1, 47.1, 46.2]
Line chart of NMF reconstruction error against the number of topics from 4 to 14: the error falls almost linearly, with no elbow.
NMF reconstruction error for 4 to 14 topics.

The error falls almost linearly. More topics always fit better, so the curve cannot choose for you. Choose by reading the top words of each fit.

Step 5 — Read the fits with 8, 12 and 14 topics

Section titled “Step 5 — Read the fits with 8, 12 and 14 topics”
for k in [8, 12, 14]:
fit = NMF(n_components=k, init="nndsvda", random_state=42, max_iter=1000)
words = top_words(fit.fit(topic_tfidf).components_, topic_terms, n=4)
print(f"k={k}")
for start in range(0, k, 3):
print(" " + " | ".join(words[start : start + 3]))
Output
k=8
months lasted durable use | battery charge holds days | sturdy built recommend friends
feels material quality premium | price point beat stores | great customer service question
money value delivery worth | day refund seller processed
k=12
months lasted durable use | battery charge holds days | sturdy built say far
feels material quality premium | price point beat lower | great customer service question
money value worth excellent | day seller refund processed | size true fit fits
recommend friends definitely highly | delivery time driver friendly | weeks using ve waiting
k=14
months lasted durable use | battery charge holds days | sturdy built say long
feels material quality premium | price point beat lower | great customer service question
money value worth excellent | day seller refund processed | size true fit fits
recommend friends definitely highly | delivery time driver friendly | weeks using ve waiting
package shipping fast packed | purchase happy setup instructions

With 8 topics, there is no size-and-fit topic, although Step 3 showed that 41% of the clothing reviews are about size and fit. With 12, delivery gets its own topic (delivery time driver friendly), but a vague topic appears too: weeks using ve waiting. With 14, the two new topics (package shipping fast packed and purchase happy setup instructions) mix themes that other topics already cover. Ten is the smallest number in which every topic has a clear name, so it is a good choice for this corpus.

from sklearn.decomposition import LatentDirichletAllocation
lda_vec = CountVectorizer(stop_words="english", min_df=5, max_df=0.5)
lda_counts = lda_vec.fit_transform(reviews["clean"])
lda = LatentDirichletAllocation(n_components=10, random_state=42)
lda_doc_topics = lda.fit_transform(lda_counts)
for i, words in enumerate(top_words(lda.components_, lda_vec.get_feature_names_out())):
print(i, words)
print(lda_doc_topics[0].round(2), lda_doc_topics[0].sum().round(3))
Output
0 package arrived day seller refund processed
1 price quality point beat high build
2 recommend sturdy built friends definitely gift
3 battery charge use setup took easy
4 feels material quality delivery cheap premium
5 months lasted durable early signs shows
6 money value excellent worth quality delivery
7 size customer service great weeks using
8 purchase happy quality old replaced great
9 price stores lower broke good days
[0.01 0.28 0.01 0.61 0.01 0.01 0.01 0.01 0.01 0.01] 1.0

LDA works on raw counts, so it gets a CountVectorizer. Its topics are less clean on these short reviews: several mix two themes, such as price with quality, or size with customer service. A review of 16 words gives LDA little evidence about its topic mixture. Each row of lda_doc_topics is a probability distribution: the values sum to 1.

Common mistakes:

  • Running LDA on TF-IDF. LDA models word counts; TF-IDF weights break its assumptions. Use CountVectorizer.
  • Keeping stop words for topic modeling. Topics then fill with the, it and was.
  • Trusting topic names without reading reviews. A topic is a list of words; the name is your hypothesis about it.

Example 8 — Find similar reviews with LSA embeddings

Section titled “Example 8 — Find similar reviews with LSA embeddings”

Goal: Build a “similar reviews” feature: for a review or a free-text query, show the reviews that say the same thing, even with different words.

from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import Normalizer
lsa_vec = TfidfVectorizer(stop_words="english", min_df=2)
lsa_tfidf = lsa_vec.fit_transform(reviews["clean"])
lsa = make_pipeline(TruncatedSVD(n_components=50, random_state=42), Normalizer())
doc_vectors = lsa.fit_transform(lsa_tfidf)
svd = lsa.named_steps["truncatedsvd"]
print(lsa_tfidf.shape, "->", doc_vectors.shape)
print(f"variance kept: {svd.explained_variance_ratio_.sum():.2f}")
print(doc_vectors[0][:6].round(3))
Output
(3000, 291) -> (3000, 50)
variance kept: 0.61
[ 0.256 0.13 -0.207 0.059 -0.045 0.059]

Each review is now a dense vector of 50 numbers instead of a sparse vector of hundreds. The 50 directions keep about 60% of the variance of the TF-IDF matrix. Normalizer scales each vector to length 1, so a dot product is a cosine similarity.

Step 2 — Find the nearest neighbors of a review

Section titled “Step 2 — Find the nearest neighbors of a review”
def most_similar(query_vector: np.ndarray, k: int = 3) -> pd.DataFrame:
"""Return the k reviews whose LSA vectors are closest to the query vector."""
sims = doc_vectors @ query_vector
best = np.argsort(-sims, kind="stable")[:k]
texts = reviews["clean"].iloc[best]
return pd.DataFrame({"cosine": sims[best].round(3), "text": texts})
print(reviews.loc[158, "clean"])
print(most_similar(doc_vectors[158], k=4))
Output
battery life drains fast. the price is way too high.
cosine text
158 1.000 battery life drains fast. the price is way too high.
542 0.832 the price is really high for what it is. the battery is ...
2810 0.788 the battery takes forever to charge. the price is way to...
1398 0.724 battery life is very amazing. really high quality materi...

The matrix-vector product doc_vectors @ query_vector computes the cosine similarity with all 3,000 reviews at once (all rows have length 1). The first hit is the review itself, with cosine 1. The next two complain about the same two aspects: a weak battery and a high price. The fourth hit praises the battery. LSA captures what a review is about, not what it thinks of it. kind="stable" breaks ties in the same way on every run.

Section titled “Step 3 — Compare LSA search with plain TF-IDF search”
def compare_search(query: str, k: int = 2) -> None:
"""Print the k best reviews by TF-IDF cosine and by LSA cosine."""
sparse_query = lsa_vec.transform([clean_text(query)])
tfidf_sims = (lsa_tfidf @ sparse_query.T).toarray().ravel()
lsa_sims = doc_vectors @ lsa.transform(sparse_query)[0]
known = [str(term) for term in lsa_vec.inverse_transform(sparse_query)[0]]
print(f"query {query!r}, known terms {known}")
for name, sims in [("TF-IDF", tfidf_sims), ("LSA", lsa_sims)]:
for i in np.argsort(-sims, kind="stable")[:k]:
text = reviews.loc[i, "clean"][:60]
print(f" {name:6} shares words: {tfidf_sims[i] > 0!s:5} {text}")
compare_search("It drains overnight")
compare_search("The seller ignored me")
Output
query 'It drains overnight', known terms ['drains']
TF-IDF shares words: True the battery drains fast.
TF-IDF shares words: True cheaply made, it broke within days. the battery drains very
LSA shares words: True battery life drains super fast. very disappointed.
LSA shares words: False the battery life is much worse than advertised.
query 'The seller ignored me', known terms ['ignored', 'seller']
TF-IDF shares words: True the seller ignored my refund request. the price is not justi
TF-IDF shares words: True customer service ignored my refund request.
LSA shares words: True the seller answered eventually.
LSA shares words: True the seller went above and beyond.

A new text goes through the same fitted steps: clean, transform with the vectorizer, transform with the LSA pipeline. The column “shares words” says whether a hit has any query term in common with the query (a TF-IDF cosine above 0). Do not compare cosine values across the two spaces; compare the hits.

For It drains overnight, only drains is in the vocabulary. TF-IDF can only return reviews that contain drains. LSA returns one of those too, and also “the battery life is much worse than advertised”, which shares no word with the query but means the same: LSA has learned that drains goes with battery life.

For The seller ignored me, TF-IDF finds the right complaints. LSA returns “the seller answered eventually” and “the seller went above and beyond”: the same topic with the opposite meaning. LSA blurs a rare, decisive word such as ignored into the general seller topic. On this small, repetitive corpus, plain TF-IDF search is often as good or better. LSA helps when the matching reviews use other words. It captures what a review is about, not what it says about it, so combine it with the sentiment model when the tone matters.

word_vectors = svd.components_.T # one row of 50 numbers per term
word_vectors = word_vectors / np.linalg.norm(word_vectors, axis=1, keepdims=True)
lsa_terms = lsa_vec.get_feature_names_out()
lsa_index = {term: i for i, term in enumerate(lsa_terms)}
for word in ["battery", "refund", "delivery", "durable"]:
sims = word_vectors @ word_vectors[lsa_index[word]]
neighbors = [lsa_terms[i] for i in np.argsort(-sims, kind="stable")[1:6]]
print(f"{word:9} {neighbors}")
Output
battery ['life', 'amazing', 'died', 'worse', 'lasts']
refund ['processed', 'realy', 'waiting', 'seller', 'ignored']
delivery ['late', 'address', 'right', 'quick', 'quicker']
durable ['lasted', 'months', 'extremely', 'really', 'delivary']

The columns of components_ give a dense vector for each word too. Words that appear in the same reviews get close vectors: battery sits near life, died and lasts, refund near processed and waiting, durable near lasted and months. The neighbors also show the noise of a small corpus: the typos realy and delivary appear, and amazing is close to battery because every review that uses amazing uses it about the battery. This is the distributional hypothesis at work, learned from 3,000 short reviews in a fraction of a second.

print("charging" in lsa_index, "charge" in lsa_index)
print(np.abs(lsa.transform(lsa_vec.transform(["charging"]))).sum())
Output
False True
0.0

charging never appears in the corpus, so the query has an all-zero TF-IDF vector and an all-zero embedding. It matches nothing. Pretrained subword models such as fastText and transformers solve this, because they build vectors from parts of words learned on huge corpora.

Common mistakes:

  • Using PCA with its full or randomized solver on a sparse TF-IDF matrix. It raises a TypeError. TruncatedSVD accepts any sparse input and needs no centering.
  • Fitting a new vectorizer for the query. The query must use the fitted vectorizer and SVD (transform, not fit_transform), or its vector lives in a different space.
  • Comparing vectors without normalizing them. Without Normalizer, the dot product favors long reviews.
Mistake Symptom Fix
Fitting the vectorizer on all data before the split Optimistic CV and test scores Put the vectorizer inside a Pipeline
fit_transform on the test set ValueError: X has ... features, but LogisticRegression is expecting ... features as input Use transform on new data
stop_words="english" for sentiment “not worth it” and “worth it” get the same vector Keep stop words, or pass a short custom list
No html.unescape amp and 39 appear as top words or topic words Decode entities before tokenizing
Passing a one-column DataFrame to a vectorizer Vocabulary {'clean': 0}; ValueError: Found input variables with inconsistent numbers of samples Pass a Series or a list of strings
Calling .toarray() on the whole corpus Memory grows by orders of magnitude Keep the matrix sparse; densify a few rows only
Default LogisticRegression(C=1) on TF-IDF Underfits; weak minority class Tune C with cross-validation
Bigrams without min_df Vocabulary grows about 9 times, often with one-off phrases Add min_df=2 or max_features
LDA on TF-IDF Muddled topics LDA gets counts from CountVectorizer
Choosing topics by reconstruction error alone Always “more topics” Read the top words; pick the smallest distinct set
PCA(svd_solver="randomized") on a sparse matrix TypeError: PCA only support sparse inputs with the "arpack" and "covariance_eigh" solvers Use TruncatedSVD (LSA)
Expecting the default tokenizer to keep i, a or 2 Single characters vanish Pass token_pattern=r"(?u)\b\w+\b"
Reporting accuracy on imbalanced classes 0.78 looks fine but predicts no negatives Compare with DummyClassifier; read per-class recall
  • Web search and site search: a shop’s search box ranks products by TF-IDF or BM25 (a refined TF-IDF) scores; Elasticsearch and Lucene build on the same counts.
  • Automation: an email or ticket router classifies incoming messages (“billing”, “bug”, “refund”) with a TF-IDF + linear model pipeline and sends each one to the right queue.
  • Tooling: log analysis tools cluster error messages by their tokens, and “did you mean” features compare character n-grams to catch typos.
  • Security and moderation: spam filters started as multinomial naive Bayes on word counts, and many still use it as a first, fast stage.
  • Text needs a fixed-length numeric representation. Clean, tokenize, vectorize, then use any model.
  • Clean with html.unescape, lowercasing and whitespace collapsing. Keep the raw text. Typos survive cleaning; min_df drops only the rare ones, and character n-grams make the frequent ones similar to the right word.
  • A regex tokenizer beats str.split(). scikit-learn’s default pattern keeps words of 2+ characters. The built-in English stop-word list removes not, no and never: never use it for sentiment.
  • A bag of words counts words per document. CountVectorizer learns the vocabulary in fit and ignores unknown words in transform. The result is a sparse CSR matrix: keep it sparse.
  • TF-IDF weights a count by ln⁡1+n1+df⁡+1\ln\frac{1+n}{1+\operatorname{df}} + 1 and normalizes each row to length 1, so rare, specific words count most.
  • N-grams let a linear model learn phrases such as not worth. Control the vocabulary with min_df, max_df and max_features.
  • A Pipeline of a vectorizer and a linear model is the standard text classifier. Cross-validate it, tune C, compare with a baseline, read per-class metrics, the top weights and the errors.
  • NMF on TF-IDF and LDA on counts find topics without labels. Choose n_components by reading the topics.
  • Embeddings are dense vectors in which similar texts are close. LSA (TruncatedSVD on TF-IDF) is the simplest one; pretrained word and sentence embeddings are the next step.

Q1. Why does a classifier need a vectorizer before it can learn from reviews?

Answer

A model needs every example as a feature vector of the same length, made of numbers. Reviews are strings of different lengths. A vectorizer maps each review to a vector with one position per vocabulary term, so all reviews get the same length.

Q2. What does html.unescape("Sturdy &amp; built") return, and why clean entities before tokenizing?

Answer

"Sturdy & built". Without decoding, the tokenizer turns &amp; into the token amp, which becomes a frequent fake word in the vocabulary, the top words and the topics.

Q3. Why is stop_words="english" a bad choice for a sentiment classifier?

Answer

scikit-learn’s English list contains negations and contrast words such as not, no, never and but. Removing them makes “not worth the money” and “worth the money” identical, so the model cannot tell a complaint from praise.

Q4. A CountVectorizer was fitted on training reviews. A new review contains the word drone, which never appeared in training. What happens in transform?

Answer

Nothing visible: drone is out of vocabulary, so it is ignored. The vector has no column for it, and no error is raised. If all words of a text are unknown, its vector is all zeros.

Q5. In a corpus of 3 documents, refund appears in 1 document. What is its smooth idf in scikit-learn?

Answer

ln⁡1+31+1+1=ln⁡2+1≈1.693\ln\frac{1+3}{1+1} + 1 = \ln 2 + 1 \approx 1.693.

Q6. Why does TfidfVectorizer normalize every row to length 1?

Answer

So that long and short documents are comparable. Without it, a long review has larger values just because it has more words, and similarity scores and model weights favor long texts. With unit rows, a dot product between two rows is their cosine similarity.

Q7. What does ngram_range=(1, 2) add, and what is its cost?

Answer

It adds every pair of consecutive tokens (bigrams) to the single words, so the model can learn phrases such as not worth or not cheap. The cost is a much larger vocabulary (about 9 times here), mostly made of rare phrases; min_df controls it.

Q8. Why must the vectorizer sit inside the Pipeline during cross-validation?

Answer

The vocabulary and the idf values are learned from data. In a pipeline, they are refitted on each training fold, so the validation fold stays unseen. A vectorizer fitted on all data first leaks the validation documents’ words and document frequencies into training.

Q9. When would you choose NMF over LDA for topic modeling?

Answer

For short texts such as reviews, tweets or support tickets: NMF on TF-IDF is fast and usually gives cleaner, easier-to-name topics. LDA, a probabilistic model on raw counts, shines on longer documents and gives topic probabilities that sum to 1.

Q10. Two reviews share no words, yet LSA gives them a cosine similarity of 0.8. How is that possible?

Answer

LSA maps each review to a dense vector built from the main directions of the TF-IDF matrix. Words that appear in similar reviews, such as battery, life and lasts, load on the same directions. Two reviews that use different words from the same group get similar dense vectors. In the sparse TF-IDF space, their cosine is 0.

Q11. Your sentiment model’s most confident errors read clearly positive, but their label is negative. What do you conclude?

Answer

The labels are noisy: these reviews have a rating that contradicts their text (a mis-clicked rating). The model is probably right. Label noise limits the reachable accuracy; review or relabel such cases instead of tuning the model to fit them.

Your progress

0 / 4 done

  • Exercises: 26 exercises with hints and full solutions, from cleaning one review to aspect-based sentiment.
  • Mini-project: build a review insights report that combines a sentiment model with complaint topics per product.
  • Cheat sheet: cleaning, tokenizing, vectorizer options, the TF-IDF formula, text pipelines, topic models and embeddings on one page.
  • Next module: 42. Deep learning with PyTorch builds neural networks with tensors, autograd and nn.Module, the foundation of modern NLP models.