41. NLP fundamentals — Exercises
These exercises practice every idea of the NLP fundamentals lesson. They all use the 3,000 product reviews in data/reviews.csv (see the data dictionary) or a few short texts typed by hand.
How to work:
- Read the task and the expected output.
- Copy the setup block and the starter code into a script, and replace each to-do comment with your code.
- Run the script. Compare your output with the expected output.
- Stuck? Open one hint at a time. Open the solution only after a real attempt.
Each solution ends with assert checks. Add the same checks to your own code.
Run this block first. Every exercise starts from its names: the cleaned reviews in reviews["clean"], the binary subset binary (positive and negative reviews only) and the clean_text function from the lesson.
import htmlimport refrom collections import Counter
import numpy as npimport pandas as pdfrom sklearn.feature_extraction.text import ( ENGLISH_STOP_WORDS, CountVectorizer, TfidfVectorizer,)from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_score, train_test_splitfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.pipeline import make_pipeline
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)
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()
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)reviews["clean"] = reviews["text"].map(clean_text)binary = reviews[reviews["sentiment"] != "neutral"]Warm-up
Section titled “Warm-up”M41-W01 · Clean one review
Section titled “M41-W01 · Clean one review”A review arrives from a web form with an HTML entity, shouting, a blank line and extra spaces. Write a function clean_review(text) that decodes the HTML entities, lowercases the text and collapses every run of whitespace into one space, with no spaces at the ends. Print the repr() of the raw text and of the cleaned text.
' GREAT battery & FAST charging!!!\n\nWould buy again. ''great battery & fast charging!!! would buy again.'import htmlimport re
raw = " GREAT battery & FAST charging!!!\n\nWould buy again. "
def clean_review(text: str) -> str: # TODO: decode entities, lowercase, collapse whitespace, strip ...
print(repr(raw))print(repr(clean_review(raw)))Hint 1
html.unescape decodes &. str.lower() lowercases. The regex \s+ matches any run of spaces, tabs and line breaks.
Hint 2
re.sub(r"\s+", " ", text) replaces each run with one space. strip() removes the spaces that remain at the ends.
Solution
import htmlimport re
raw = " GREAT battery & FAST charging!!!\n\nWould buy again. "
def clean_review(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()
cleaned = clean_review(raw)print(repr(raw))print(repr(cleaned))assert cleaned == "great battery & fast charging!!! would buy again."assert " " not in cleaned and "\n" not in cleaned' GREAT battery & FAST charging!!!\n\nWould buy again. ''great battery & fast charging!!! would buy again.'How it works:
html.unescapeturns&into&. Do it first, before any other step changes the text.lower()makesGREATandgreatthe same token later.\s+matches the two line breaks and the double spaces in one go, so onere.subcall handles every kind of whitespace.strip()removes the single spaces that the substitution leaves at both ends.
Alternative: " ".join(text.split()) collapses whitespace without a regex, because split() with no argument splits on any run of whitespace and drops the empty pieces at the ends.
import html
raw = " GREAT battery & FAST charging!!!\n\nWould buy again. "print(repr(" ".join(html.unescape(raw).lower().split())))'great battery & fast charging!!! would buy again.'M41-W02 · Tokenize with a regular expression
Section titled “M41-W02 · Tokenize with a regular expression”Write a function tokenize(text) that lowercases a text and returns the runs of letters, digits and apostrophes as a list. Then tokenize the same text with scikit-learn’s default tokenizer, which you get from CountVectorizer().build_analyzer(). Print both lists and the tokens that only your function keeps.
["doesn't", 'fit', 'size', 'm', 'runs', '2', 'sizes', 'small']['doesn', 'fit', 'size', 'runs', 'sizes', 'small']["doesn't", 'm', '2']import re
from sklearn.feature_extraction.text import CountVectorizer
text = "Doesn't fit. Size M runs 2 sizes small!!!"
def tokenize(text: str) -> list[str]: # TODO: lowercase and find the runs of letters, digits and apostrophes ...
mine = tokenize(text)# TODO: build scikit-learn's analyzer and apply it to text# TODO: print both lists and the tokens only in mine (keep their order)Hint 1
The character class [a-z0-9'] matches one letter, digit or apostrophe. Add + to match a run of them.
Hint 2
analyzer = CountVectorizer().build_analyzer() returns a function. analyzer(text) gives the tokens scikit-learn would count.
Solution
import re
from sklearn.feature_extraction.text import CountVectorizer
text = "Doesn't fit. Size M runs 2 sizes small!!!"
def tokenize(text: str) -> list[str]: """Lowercase a text and return its runs of letters, digits and apostrophes.""" return re.findall(r"[a-z0-9']+", text.lower())
mine = tokenize(text)analyzer = CountVectorizer().build_analyzer()sklearn_tokens = analyzer(text)only_mine = [token for token in mine if token not in sklearn_tokens]print(mine)print(sklearn_tokens)print(only_mine)assert mine == ["doesn't", "fit", "size", "m", "runs", "2", "sizes", "small"]assert only_mine == ["doesn't", "m", "2"]["doesn't", 'fit', 'size', 'm', 'runs', '2', 'sizes', 'small']['doesn', 'fit', 'size', 'runs', 'sizes', 'small']["doesn't", 'm', '2']How it works:
re.findallreturns every non-overlapping match. Punctuation such as.and!is not in the class, so it separates tokens and disappears.- scikit-learn’s default
token_pattern,(?u)\b\w\w+\b, keeps only tokens of two or more word characters. It drops the sizemand the number2. - The apostrophe is not a word character, so scikit-learn splits
doesn'tintodoesnandt, and drops thet. - For size data,
mmatters. Passtoken_pattern=r"[a-z0-9']+"to the vectorizer to use your rule.
M41-W03 · Predict the output of CountVectorizer
Section titled “M41-W03 · Predict the output of CountVectorizer”Predict the output: what do the two print calls show? Write down the vocabulary and the count matrix before you run the code.
from sklearn.feature_extraction.text import CountVectorizer
docs = ["I've got 2 TVs & a PC.", "A PC is a PC."]vec = CountVectorizer()counts = vec.fit_transform(docs)print(vec.get_feature_names_out())print(counts.toarray())Acceptance criteria: write your prediction for both lines, then run the code. Your prediction matches the Output in the solution.
Hint 1
The default tokenizer lowercases the text and keeps only tokens of two or more letters or digits.
Hint 2
I've loses its I and keeps ve. 2, & and a disappear. The columns are in alphabetical order.
Solution
from sklearn.feature_extraction.text import CountVectorizer
docs = ["I've got 2 TVs & a PC.", "A PC is a PC."]vec = CountVectorizer()counts = vec.fit_transform(docs)print(vec.get_feature_names_out())print(counts.toarray())assert list(vec.get_feature_names_out()) == ["got", "is", "pc", "tvs", "ve"]assert counts.toarray()[1].tolist() == [0, 1, 2, 0, 0]['got' 'is' 'pc' 'tvs' 've'][[1 0 1 1 1] [0 1 2 0 0]]How it works:
CountVectorizerlowercases first, soPCbecomespcandTVsbecomestvs.- The pattern
\b\w\w+\bneeds at least two word characters.i,2,aand&are dropped.I'vesplits at the apostrophe intoiandve, and onlyvesurvives. - The vocabulary is sorted alphabetically, which gives the column order.
- The second document contains
pctwice andisonce;ais not counted at all.
M41-W04 · Find the most common content words of negative reviews
Section titled “M41-W04 · Find the most common content words of negative reviews”Tokenize the cleaned negative reviews with the regex [a-z']+, drop the words in scikit-learn’s ENGLISH_STOP_WORDS and print the 8 most common remaining words with their counts.
596 negative reviews, 4747 content tokensprice 179quality 178broke 119delivery 81buy 77bought 76battery 75avoid 75negative_texts = reviews.loc[reviews["sentiment"] == "negative", "clean"]# TODO: collect the tokens of all negative texts, skipping stop words# TODO: count them with Counter and print the 8 most commonHint 1
A nested comprehension visits every token of every text: [t for text in texts for t in re.findall(pattern, text)]. Add an if at the end to skip stop words.
Hint 2
Counter(tokens).most_common(8) returns a list of (word, count) pairs, largest first.
Solution
negative_texts = reviews.loc[reviews["sentiment"] == "negative", "clean"]tokens = [ token for text in negative_texts for token in re.findall(r"[a-z']+", text) if token not in ENGLISH_STOP_WORDS]top = Counter(tokens).most_common(8)print(len(negative_texts), "negative reviews,", len(tokens), "content tokens")for word, count in top: print(f"{word:9} {count}")assert top[0][1] >= top[-1][1]assert all(word not in ENGLISH_STOP_WORDS for word, _ in top)596 negative reviews, 4747 content tokensprice 179quality 178broke 119delivery 81buy 77bought 76battery 75avoid 75How it works:
- The comprehension reads like two nested
forloops with a filter at the end. - Membership tests on
ENGLISH_STOP_WORDSare fast, because it is afrozenset. most_commonsorts by count. Ties keep the order in which the words were first seen, which is fixed for a fixed file.
Alternative: CountVectorizer(stop_words="english") counts the same words in one step. Sum its matrix down the columns to get the corpus counts. Its default tokenizer differs slightly (it drops one-letter tokens), but the top words are the same.
vec = CountVectorizer(stop_words="english")counts = vec.fit_transform(reviews.loc[reviews["sentiment"] == "negative", "clean"])totals = pd.Series(counts.sum(axis=0).A1, index=vec.get_feature_names_out())print(list(totals.sort_values(ascending=False, kind="stable").head(8).index))['price', 'quality', 'broke', 'delivery', 'buy', 'bought', 'avoid', 'battery']M41-W05 · Fix the bug: fit_transform on the test set
Section titled “M41-W05 · Fix the bug: fit_transform on the test set”Fix the bug: this code trains a classifier on the binary reviews and then fails on the test set with ValueError: X has ... features, but LogisticRegression is expecting ... features as input. Find the line that causes it, fix it and print the test accuracy.
(1996, 371) (666, 371)test accuracy: 0.917X_train, X_test, y_train, y_test = train_test_split( binary["clean"], binary["sentiment"], test_size=0.25, stratify=binary["sentiment"], random_state=42,)vec = TfidfVectorizer()X_train_tfidf = vec.fit_transform(X_train)X_test_tfidf = vec.fit_transform(X_test) # TODO: the bug is on this linemodel = LogisticRegression(C=10, max_iter=1000).fit(X_train_tfidf, y_train)print(f"test accuracy: {model.score(X_test_tfidf, y_test):.3f}")Hint 1
fit_transform learns a new vocabulary. How many columns does the test matrix get, and what does each column mean?
Hint 2
New data must go through the vectorizer that was fitted on the training data, with transform only.
Solution
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,)vec = TfidfVectorizer()X_train_tfidf = vec.fit_transform(X_train)X_test_tfidf = vec.transform(X_test)model = LogisticRegression(C=10, max_iter=1000).fit(X_train_tfidf, y_train)accuracy = model.score(X_test_tfidf, y_test)print(X_train_tfidf.shape, X_test_tfidf.shape)print(f"test accuracy: {accuracy:.3f}")assert X_train_tfidf.shape[1] == X_test_tfidf.shape[1]assert accuracy > 0.88(1996, 371) (666, 371)test accuracy: 0.917How it works:
fit_transform(X_test)built a second vocabulary from the test reviews. It had a different size and a different column order, so the model could not use it. TheValueErrorcaught the size mismatch.- The worse version of this bug raises no error: if both vocabularies happen to have the same size, the columns mean different words and the predictions are silently wrong.
transformmaps the test reviews onto the training vocabulary and the training idf values. Unknown test words are ignored.
Alternative: put the vectorizer and the model in a pipeline. pipeline.score(X_test, y_test) calls transform for you, so this bug cannot happen.
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,)pipe = make_pipeline(TfidfVectorizer(), LogisticRegression(C=10, max_iter=1000))print(f"test accuracy: {pipe.fit(X_train, y_train).score(X_test, y_test):.3f}")test accuracy: 0.917M41-W06 · Compute an idf by hand
Section titled “M41-W06 · Compute an idf by hand”For the four short reviews in the starter, compute the smooth idf of battery and of refund with the formula . Then fit a TfidfVectorizer and print its idf_ values for the same two words.
battery df=3 idf=1.223refund df=1 idf=1.916battery TfidfVectorizer idf=1.223refund TfidfVectorizer idf=1.916import math
docs = [ "battery died fast", "battery holds a charge", "great battery and fast shipping", "still waiting for my refund",]# TODO: count n and the document frequency of each word# TODO: compute the two idf values with math.log# TODO: compare with TfidfVectorizer().fit(docs).idf_Hint 1
is 4. battery appears in 3 documents and refund in 1. math.log is the natural logarithm.
Hint 2
vec.vocabulary_["refund"] gives the column index of refund, and vec.idf_[index] its idf.
Solution
import math
docs = [ "battery died fast", "battery holds a charge", "great battery and fast shipping", "still waiting for my refund",]n = len(docs)by_hand = {}for word in ["battery", "refund"]: df = sum(word in doc.split() for doc in docs) by_hand[word] = math.log((1 + n) / (1 + df)) + 1 print(f"{word:8} df={df} idf={by_hand[word]:.3f}")
vec = TfidfVectorizer().fit(docs)for word, value in by_hand.items(): library = vec.idf_[vec.vocabulary_[word]] print(f"{word:8} TfidfVectorizer idf={library:.3f}") assert math.isclose(value, library)battery df=3 idf=1.223refund df=1 idf=1.916battery TfidfVectorizer idf=1.223refund TfidfVectorizer idf=1.916How it works:
word in doc.split()isTrueorFalse;sumcounts theTruevalues, which is the document frequency.batteryis in 3 of 4 documents: .refundis in 1: . The rare word gets the larger weight.math.isclosecompares floats safely (module 01).
M41-W07 · Build bigrams with zip
Section titled “M41-W07 · Build bigrams with zip”Write a function ngrams(tokens, n) that returns the n-grams of a token list as strings joined by a space. Print the bigrams and trigrams of "not worth the money at all", and check the bigrams against CountVectorizer(ngram_range=(2, 2)).
['not worth', 'worth the', 'the money', 'money at', 'at all']['not worth the', 'worth the money', 'the money at', 'money at all']['not worth', 'worth the', 'the money', 'money at', 'at all']tokens = "not worth the money at all".split()
def ngrams(tokens: list[str], n: int) -> list[str]: # TODO: zip n shifted copies of the list and join each tuple ...
# TODO: print the bigrams and the trigrams# TODO: compare with CountVectorizer(ngram_range=(2, 2)).build_analyzer()Hint 1
zip(tokens, tokens[1:]) pairs each token with the next one. For n-grams, zip tokens[i:] for every i in range(n).
Hint 2
zip(*[tokens[i:] for i in range(n)]) unpacks the list of shifted copies into separate arguments. " ".join(gram) turns each tuple into a string.
Solution
tokens = "not worth the money at all".split()
def ngrams(tokens: list[str], n: int) -> list[str]: """Return the n-grams of a token list as space-joined strings.""" return [" ".join(gram) for gram in zip(*[tokens[i:] for i in range(n)])]
bigrams = ngrams(tokens, 2)print(bigrams)print(ngrams(tokens, 3))analyzer = CountVectorizer(ngram_range=(2, 2)).build_analyzer()print(analyzer("Not worth the money at all."))assert bigrams == analyzer("Not worth the money at all.")assert len(ngrams(tokens, 3)) == len(tokens) - 2['not worth', 'worth the', 'the money', 'money at', 'at all']['not worth the', 'worth the money', 'the money at', 'money at all']['not worth', 'worth the', 'the money', 'money at', 'at all']How it works:
[tokens[i:] for i in range(n)]buildsncopies of the list, each shifted by one more token.zipwalks them in step and stops at the shortest copy, so a list of tokens has n-grams.- scikit-learn’s analyzer lowercases, tokenizes and then builds the same n-grams, so the lists match.
M41-W08 · Measure the sparse document-term matrix
Section titled “M41-W08 · Measure the sparse document-term matrix”Fit a CountVectorizer on all cleaned reviews. Print the shape of the matrix, its number of stored values (nnz), its density and the mean number of distinct words per review.
(3000, 376) 44216density: 3.92%distinct words per review: 14.7counts = CountVectorizer().fit_transform(reviews["clean"])# TODO: print the shape and nnz# TODO: density = nnz / (rows * columns); print it as a percentage# TODO: mean distinct words per review = nnz / rowsHint 1
A sparse matrix has .shape and .nnz like a NumPy array has .shape and .size.
Hint 2
Each stored value is one (review, word) pair with a count of at least 1, so nnz / rows is the mean number of distinct words per review.
Solution
counts = CountVectorizer().fit_transform(reviews["clean"])rows, cols = counts.shapedensity = counts.nnz / (rows * cols)print(counts.shape, counts.nnz)print(f"density: {density:.2%}")print(f"distinct words per review: {counts.nnz / rows:.1f}")assert counts.nnz == (counts > 0).sum()assert density < 0.05(3000, 376) 44216density: 3.92%distinct words per review: 14.7How it works:
- A CSR matrix stores three arrays: the non-zero values, their column indices and where each row starts.
nnzis the length of the first one. - The density is about 4%: each review uses about 15 of the 376 vocabulary words.
(counts > 0).sum()counts the cells with a value, which must equalnnzhere, because a count matrix stores no explicit zeros.
M41-C01 · Measure each cleaning step
Section titled “M41-C01 · Measure each cleaning step”Apply the three cleaning steps one at a time to the raw text column: decode HTML entities, then lowercase, then collapse whitespace and strip. For each step, print how many reviews it changed. Check that no & remains at the end.
unescape changed 62 reviewslowercase changed 3,000 reviewswhitespace changed 214 reviewsentities left: 0steps = { "unescape": html.unescape, # TODO: add "lowercase" and "whitespace" steps as functions of one string}current = reviews["text"]for name, step in steps.items(): # TODO: apply the step, count the changed rows, keep the result ...Hint 1
str.lower is a function that takes one string. For the whitespace step, write a lambda.
Hint 2
changed = (new != current).sum() compares two Series row by row and counts the differences.
Solution
steps = { "unescape": html.unescape, "lowercase": str.lower, "whitespace": lambda text: re.sub(r"\s+", " ", text).strip(),}current = reviews["text"]for name, step in steps.items(): new = current.map(step) print(f"{name:10} changed {(new != current).sum():5,} reviews") current = newprint("entities left:", current.str.contains("&", regex=False).sum())assert current.equals(reviews["clean"])unescape changed 62 reviewslowercase changed 3,000 reviewswhitespace changed 214 reviewsentities left: 0How it works:
- A dictionary of functions keeps the steps in order and gives each one a name for the report.
- Each step works on the output of the one before, so the counts show what that step adds.
- Lowercasing changes every review, because every review starts with a capital letter. Unescaping and whitespace fixes touch only the quirky rows.
- The final
assertproves that the three steps reproduceclean_textexactly.
M41-C02 · Control the vocabulary size
Section titled “M41-C02 · Control the vocabulary size”Fit a CountVectorizer on the cleaned reviews with six settings and print a table of their vocabulary sizes: the default, min_df=5, max_df=0.5, stop_words="english", max_features=100 and ngram_range=(1, 2) with min_df=5. Which setting keeps the most terms?
1-2 grams, min_df=5 1413default 376max_df=0.5 375min_df=5 360stop words 295max_features=100 100dtype: int64settings = { "default": {}, "min_df=5": {"min_df": 5}, # TODO: add the four other settings}# TODO: fit one vectorizer per setting and collect len(vec.vocabulary_)# TODO: print a Series sorted from the largest vocabulary to the smallestHint 1
CountVectorizer(**params) passes a dictionary of settings as keyword arguments.
Hint 2
Collect the sizes in a dictionary, wrap it in pd.Series and call sort_values(ascending=False).
Solution
settings = { "default": {}, "min_df=5": {"min_df": 5}, "max_df=0.5": {"max_df": 0.5}, "stop words": {"stop_words": "english"}, "max_features=100": {"max_features": 100}, "1-2 grams, min_df=5": {"ngram_range": (1, 2), "min_df": 5},}sizes = { name: len(CountVectorizer(**params).fit(reviews["clean"]).vocabulary_) for name, params in settings.items()}table = pd.Series(sizes).sort_values(ascending=False, kind="stable")print(table)assert table["max_features=100"] == 100assert table["min_df=5"] < table["default"]1-2 grams, min_df=5 1413default 376max_df=0.5 375min_df=5 360stop words 295max_features=100 100dtype: int64How it works:
- Each vectorizer is fitted once;
vocabulary_holds the terms it kept. min_df=5drops only 16 rare words here. Most typos appear 5 times or more (qualty51 times), so they survive.max_df=0.5drops a single word: only one word appears in more than half of the reviews.- The stop-word list removes far more words than
max_df=0.5, because it is a fixed list of 318 words, not a measure of this corpus. - Bigrams with
min_df=5keep the most terms, even after the cut-off: frequent phrases add many more features than they lose.
M41-C03 · Find the top TF-IDF terms of three reviews
Section titled “M41-C03 · Find the top TF-IDF terms of three reviews”Fit a TfidfVectorizer on all cleaned reviews. For the reviews R00008, R00012 and R00159, print the review id and its 3 terms with the highest weight, rounded to 3 decimals.
R00008 [('purifier', 0.398), ('while', 0.346), ('worked', 0.346)]R00012 [('polite', 0.307), ('only', 0.286), ('slow', 0.284)]R00159 [('drains', 0.537), ('way', 0.361), ('life', 0.35)]vec = TfidfVectorizer()matrix = vec.fit_transform(reviews["clean"])terms = vec.get_feature_names_out()for review_id in ["R00008", "R00012", "R00159"]: # TODO: find the row of this review # TODO: get its weights as a dense 1-D array and take the 3 largest ...Hint 1
The row position is reviews.index[reviews["review_id"] == review_id][0], because the index is a default RangeIndex.
Hint 2
matrix[row].toarray().ravel() gives a 1-D array of one review’s weights. np.argsort(-weights, kind="stable")[:3] gives the positions of the 3 largest.
Solution
vec = TfidfVectorizer()matrix = vec.fit_transform(reviews["clean"])terms = vec.get_feature_names_out()results = {}for review_id in ["R00008", "R00012", "R00159"]: row = reviews.index[reviews["review_id"] == review_id][0] weights = matrix[row].toarray().ravel() top = np.argsort(-weights, kind="stable")[:3] results[review_id] = [(terms[i], round(float(weights[i]), 3)) for i in top] print(review_id, results[review_id])assert all(len(pairs) == 3 for pairs in results.values())assert results["R00008"][0][1] >= results["R00008"][2][1]R00008 [('purifier', 0.398), ('while', 0.346), ('worked', 0.346)]R00012 [('polite', 0.307), ('only', 0.286), ('slow', 0.284)]R00159 [('drains', 0.537), ('way', 0.361), ('life', 0.35)]How it works:
matrix[row]slices one row of the sparse matrix;.toarray().ravel()makes it a flat dense array of a few hundred numbers. Densifying one row is cheap.- Sorting the negated weights gives a descending order.
kind="stable"keeps ties in column order. - The top terms are specific words such as product parts and complaints, not
theoris: the idf pushes common words down.
Alternative: turn the sparse row into a pandas Series and use nlargest.
vec = TfidfVectorizer()matrix = vec.fit_transform(reviews["clean"])row = reviews.index[reviews["review_id"] == "R00008"][0]weights = pd.Series(matrix[row].toarray().ravel(), index=vec.get_feature_names_out())print(weights.nlargest(3).round(3).to_dict()){'purifier': 0.398, 'while': 0.346, 'worked': 0.346}M41-C04 · Beat the baseline with naive Bayes
Section titled “M41-C04 · Beat the baseline with naive Bayes”Split the binary reviews (25% test, stratified, random_state=42). Train a pipeline of CountVectorizer and MultinomialNB. Print the accuracy of a majority-class baseline, the accuracy of the pipeline and the recall of the negative class.
baseline accuracy: 0.776naive Bayes: 0.922negative recall: 0.926from sklearn.dummy import DummyClassifierfrom sklearn.metrics import recall_score
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,)# TODO: fit a DummyClassifier(strategy="most_frequent") and score it# TODO: fit make_pipeline(CountVectorizer(), MultinomialNB()) and score it# TODO: recall of the negative class with recall_score(..., pos_label="negative")Hint 1
Both the dummy model and the pipeline have fit and score. score returns the accuracy.
Hint 2
recall_score(y_test, y_pred, pos_label="negative") is the share of negative reviews that the model finds.
Solution
from sklearn.dummy import DummyClassifierfrom sklearn.metrics import recall_score
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,)baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)nb = make_pipeline(CountVectorizer(), MultinomialNB()).fit(X_train, y_train)y_pred = nb.predict(X_test)base_acc = baseline.score(X_test, y_test)nb_acc = nb.score(X_test, y_test)neg_recall = recall_score(y_test, y_pred, pos_label="negative")print(f"baseline accuracy: {base_acc:.3f}")print(f"naive Bayes: {nb_acc:.3f}")print(f"negative recall: {neg_recall:.3f}")assert nb_acc > base_acc + 0.1assert neg_recall > 0.7baseline accuracy: 0.776naive Bayes: 0.922negative recall: 0.926How it works:
- The baseline always predicts “positive”, the larger class, so its negative recall would be 0.
MultinomialNBworks on counts, so it gets aCountVectorizer, not TF-IDF. It trains in milliseconds.- The pipeline beats the baseline by more than 10 points, and it finds most negative reviews.
M41-C05 · Choose a classifier with cross-validation
Section titled “M41-C05 · Choose a classifier with cross-validation”Choose a method and justify it: compare four pipelines on the binary reviews with 5-fold cross-validation: TF-IDF + LogisticRegression with C=1 and with C=10, counts + MultinomialNB, and TF-IDF + LinearSVC. Print the mean and standard deviation of each. Then write two sentences: which one would you deploy for a support dashboard that shows a confidence per review, and why?
LR C=1 0.896 ± 0.007LR C=10 0.909 ± 0.009MultinomialNB 0.905 ± 0.008LinearSVC 0.913 ± 0.010from sklearn.svm import LinearSVC
candidates = { "LR C=1": make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=1000)), # TODO: add "LR C=10", "MultinomialNB" and "LinearSVC"}# TODO: cross_val_score(model, binary["clean"], binary["sentiment"], cv=5)# TODO: print the mean and the standard deviation per modelHint 1
Use the whole binary set: cross-validation creates its own train and validation parts.
Hint 2
Look at the differences between the means and compare them with the standard deviations. Then think about which model gives a probability.
Solution
from sklearn.svm import LinearSVC
candidates = { "LR C=1": make_pipeline(TfidfVectorizer(), LogisticRegression(max_iter=1000)), "LR C=10": make_pipeline( TfidfVectorizer(), LogisticRegression(C=10, max_iter=1000) ), "MultinomialNB": make_pipeline(CountVectorizer(), MultinomialNB()), "LinearSVC": make_pipeline(TfidfVectorizer(), LinearSVC()),}means = {}for name, model in candidates.items(): scores = cross_val_score(model, binary["clean"], binary["sentiment"], cv=5) means[name] = scores.mean() print(f"{name:14} {scores.mean():.3f} ± {scores.std():.3f}")assert means["LR C=10"] > means["LR C=1"]assert max(means.values()) - min(means.values()) < 0.05LR C=1 0.896 ± 0.007LR C=10 0.909 ± 0.009MultinomialNB 0.905 ± 0.008LinearSVC 0.913 ± 0.010How it works:
cross_val_scorerefits each whole pipeline, vectorizer included, on 4 folds and scores it on the fifth.- The default
C=1is the weakest. WithC=10, logistic regression is as good as naive Bayes andLinearSVC: the gaps are smaller than the standard deviations. - A justified choice: logistic regression with
C=10. It ties for the best score, andpredict_probagives the confidence per review that the dashboard needs.LinearSVChas nopredict_proba, and naive Bayes probabilities are overconfident (most are near 0 or 1).
M41-C06 · Read the most informative words of naive Bayes
Section titled “M41-C06 · Read the most informative words of naive Bayes”Fit make_pipeline(CountVectorizer(), MultinomialNB()) on all binary reviews. For every word, compute the log-ratio from feature_log_prob_. Print the 6 most negative and the 6 most positive words.
['negative' 'positive']negative: ['drains', 'confusing', 'do', 'runs', 'disappointing', 'small']positive: ['friends', 'definitely', 'friendly', 'time', 'stars', 'love']nb_pipe = make_pipeline(CountVectorizer(), MultinomialNB())nb_pipe.fit(binary["clean"], binary["sentiment"])vec = nb_pipe.named_steps["countvectorizer"]nb = nb_pipe.named_steps["multinomialnb"]# TODO: nb.classes_ tells you which row of feature_log_prob_ is which class# TODO: compute the log-ratio per word as a Series indexed by the words# TODO: print the 6 smallest and the 6 largestHint 1
feature_log_prob_ has one row per class and one column per word. Row 0 belongs to nb.classes_[0].
Hint 2
ratio = pd.Series(nb.feature_log_prob_[1] - nb.feature_log_prob_[0], index=vec.get_feature_names_out()). Then ratio.nsmallest(6) and ratio.nlargest(6).
Solution
nb_pipe = make_pipeline(CountVectorizer(), MultinomialNB())nb_pipe.fit(binary["clean"], binary["sentiment"])vec = nb_pipe.named_steps["countvectorizer"]nb = nb_pipe.named_steps["multinomialnb"]print(nb.classes_)log_ratio = pd.Series( nb.feature_log_prob_[1] - nb.feature_log_prob_[0], index=vec.get_feature_names_out(),)negative_words = list(log_ratio.nsmallest(6).index)positive_words = list(log_ratio.nlargest(6).index)print("negative:", negative_words)print("positive:", positive_words)assert log_ratio[negative_words].max() < 0 < log_ratio[positive_words].min()['negative' 'positive']negative: ['drains', 'confusing', 'do', 'runs', 'disappointing', 'small']positive: ['friends', 'definitely', 'friendly', 'time', 'stars', 'love']How it works:
classes_is sorted, so row 0 isnegativeand row 1 ispositive. Some top words are parts of phrases:docomes from “Do not buy”,runsandsmallfrom “runs small”.- A word with a log-ratio of +3 is times more likely in positive reviews than in negative ones. Each occurrence of the word adds 3 to the positive class’s score.
- The extremes are words that appear almost only in one class. Laplace smoothing (
alpha=1) keeps words that never appear in one class from getting an infinite ratio.
M41-C07 · Refactor a lexicon loop into a matrix product
Section titled “M41-C07 · Refactor a lexicon loop into a matrix product”Refactor: the starter scores every review with a small sentiment lexicon in a Python loop. Rewrite it with CountVectorizer(vocabulary=...) and one matrix-vector product, check that both give the same scores, and print the mean score per star rating.
(3000, 10) [ 1 2 -1 0 2 1 0 -1]{1: -0.45, 2: -0.36, 3: 0.34, 4: 0.44, 5: 0.45}LEXICON = { "great": 1, "excellent": 1, "love": 1, "sturdy": 1, "durable": 1, "broke": -1, "awful": -1, "refund": -1, "disappointed": -1, "avoid": -1,}
def loop_scores(texts: pd.Series) -> list[int]: scores = [] for text in texts: score = 0 for token in re.findall(r"(?u)\b\w\w+\b", text): score += LEXICON.get(token, 0) scores.append(score) return scores
slow = loop_scores(reviews["clean"])# TODO: build a CountVectorizer with vocabulary=list(LEXICON)# TODO: weights = np.array(list(LEXICON.values())); fast = counts @ weights# TODO: check slow == fast, then print the mean fast score per ratingHint 1
With a fixed vocabulary, CountVectorizer needs no fitting: transform counts exactly those words, in that column order.
Hint 2
A sparse matrix times a NumPy vector (counts @ weights) returns a dense 1-D array: the weighted sum of each row.
Solution
LEXICON = { "great": 1, "excellent": 1, "love": 1, "sturdy": 1, "durable": 1, "broke": -1, "awful": -1, "refund": -1, "disappointed": -1, "avoid": -1,}
def loop_scores(texts: pd.Series) -> list[int]: scores = [] for text in texts: score = 0 for token in re.findall(r"(?u)\b\w\w+\b", text): score += LEXICON.get(token, 0) scores.append(score) return scores
slow = loop_scores(reviews["clean"])lexicon_vec = CountVectorizer(vocabulary=list(LEXICON))counts = lexicon_vec.transform(reviews["clean"])weights = np.array(list(LEXICON.values()))fast = counts @ weightsprint(counts.shape, fast[:8])print(reviews.assign(score=fast).groupby("rating")["score"].mean().round(2).to_dict())assert fast.tolist() == slow(3000, 10) [ 1 2 -1 0 2 1 0 -1]{1: -0.45, 2: -0.36, 3: 0.34, 4: 0.44, 5: 0.45}How it works:
CountVectorizer(vocabulary=...)counts only the 10 lexicon words, with the same default tokenizer as the loop.counts @ weightsmultiplies each count by its word’s score and sums each row: the whole loop in one compiled operation.- The mean score rises with the rating, so even 10 words carry a signal. The lexicon misses
refund processed the same day(praise that containsrefund), which is why learned weights do better.
M41-C08 · Fix the bug: keyword selection leaks into cross-validation
Section titled “M41-C08 · Fix the bug: keyword selection leaks into cross-validation”Fix the bug: a colleague keeps the 30 most informative words with SelectKBest(chi2, k=30) and reports a 5-fold CV accuracy on a sample of 400 reviews. The selection and the vectorizer are fitted on all 400 reviews before cross-validation, so the score is too optimistic. Rewrite the code so that every fitted step runs inside the folds, and print both scores.
leaky CV accuracy: 0.857honest CV accuracy: 0.830from sklearn.feature_selection import SelectKBest, chi2
sample = binary.sample(400, random_state=42)X = TfidfVectorizer(ngram_range=(1, 2)).fit_transform(sample["clean"])X_selected = SelectKBest(chi2, k=30).fit_transform(X, sample["sentiment"])leaky = cross_val_score( LogisticRegression(C=10, max_iter=1000), X_selected, sample["sentiment"], cv=5)print(f"leaky CV accuracy: {leaky.mean():.3f}")# TODO: build one pipeline with the vectorizer, the selector and the model# TODO: cross-validate it on the raw texts and print the honest scoreHint 1
SelectKBest(chi2) looks at the labels to choose words. Fitted on all rows, it has already seen the labels of every validation fold.
Hint 2
make_pipeline(TfidfVectorizer(...), SelectKBest(chi2, k=30), LogisticRegression(...)) and pass sample["clean"] to cross_val_score.
Solution
from sklearn.feature_selection import SelectKBest, chi2
sample = binary.sample(400, random_state=42)X = TfidfVectorizer(ngram_range=(1, 2)).fit_transform(sample["clean"])X_selected = SelectKBest(chi2, k=30).fit_transform(X, sample["sentiment"])leaky = cross_val_score( LogisticRegression(C=10, max_iter=1000), X_selected, sample["sentiment"], cv=5)honest_model = make_pipeline( TfidfVectorizer(ngram_range=(1, 2)), SelectKBest(chi2, k=30), LogisticRegression(C=10, max_iter=1000),)honest = cross_val_score(honest_model, sample["clean"], sample["sentiment"], cv=5)print(f"leaky CV accuracy: {leaky.mean():.3f}")print(f"honest CV accuracy: {honest.mean():.3f}")assert honest.mean() < leaky.mean()leaky CV accuracy: 0.857honest CV accuracy: 0.830How it works:
- The leaky version chose the 30 words that best separate the classes in all 400 reviews, including each validation fold. The model is then validated on rows that helped choose its features.
- In the pipeline, the vectorizer and the selector are refitted on the 4 training folds of each split. The validation fold is truly unseen.
- The honest score is a few points lower. That gap is the optimism of the leak. The smaller the data and the more the selection uses the labels, the larger it gets.
M41-C09 · Tune C and the n-gram range with GridSearchCV
Section titled “M41-C09 · Tune C and the n-gram range with GridSearchCV”Split the binary reviews (25% test, stratified, random_state=42). Tune a TF-IDF + logistic regression pipeline with GridSearchCV over ngram_range in (1, 1) and (1, 2) and C in 1, 3, 10, 30, with 5-fold CV. Print the best parameters, the best CV score and the test accuracy of the refitted best model.
{'logisticregression__C': 10, 'tfidfvectorizer__ngram_range': (1, 2)}best CV accuracy: 0.908test accuracy: 0.917from sklearn.model_selection import GridSearchCV
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,)pipe = make_pipeline(TfidfVectorizer(min_df=2), LogisticRegression(max_iter=1000))param_grid = { # TODO: "stepname__parameter": [values]}# TODO: fit GridSearchCV(pipe, param_grid, cv=5) and print the resultsHint 1
make_pipeline names each step after its class in lowercase: tfidfvectorizer and logisticregression.
Hint 2
The keys are "tfidfvectorizer__ngram_range" and "logisticregression__C", with two underscores.
Solution
from sklearn.model_selection import GridSearchCV
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,)pipe = make_pipeline(TfidfVectorizer(min_df=2), LogisticRegression(max_iter=1000))param_grid = { "tfidfvectorizer__ngram_range": [(1, 1), (1, 2)], "logisticregression__C": [1, 3, 10, 30],}search = GridSearchCV(pipe, param_grid, cv=5).fit(X_train, y_train)test_acc = search.score(X_test, y_test)print(search.best_params_)print(f"best CV accuracy: {search.best_score_:.3f}")print(f"test accuracy: {test_acc:.3f}")assert search.best_params_["logisticregression__C"] > 1assert test_acc > 0.9{'logisticregression__C': 10, 'tfidfvectorizer__ngram_range': (1, 2)}best CV accuracy: 0.908test accuracy: 0.917How it works:
- The grid has 2 × 4 = 8 combinations; with 5 folds, that is 40 fits plus one refit on the whole training set.
- Each fit refits the vectorizer, so the n-gram range is tuned without leakage.
search.scoreuses the refitted best pipeline on the test set, which was not used for any choice.
M41-C10 · Interpret a three-class confusion matrix
Section titled “M41-C10 · Interpret a three-class confusion matrix”Interpret a result: train the three-class model from the lesson (TF-IDF 1-2 grams with min_df=2, logistic regression with C=10) on a stratified 75/25 split of all reviews. Compute the confusion matrix, then compute precision and recall per class from the matrix with NumPy. Print them and the class pair that the model confuses most often.
precision recallnegative 0.800 0.779neutral 0.867 0.765positive 0.915 0.940most common error: negative as positive (29 reviews)from sklearn.metrics import confusion_matrix
labels = ["negative", "neutral", "positive"]# TODO: split, fit the pipeline, predict, build the confusion matrix with labels# TODO: recall = diagonal / row sums; precision = diagonal / column sums# TODO: zero the diagonal and find the largest off-diagonal cellHint 1
Rows are the true classes and columns the predicted classes. cm.sum(axis=1) gives the true count per class.
Hint 2
off = cm.copy(); np.fill_diagonal(off, 0). Then np.unravel_index(off.argmax(), off.shape) gives the (row, column) of the largest error.
Solution
from sklearn.metrics import confusion_matrix
labels = ["negative", "neutral", "positive"]X_train, X_test, y_train, y_test = train_test_split( reviews["clean"], reviews["sentiment"], test_size=0.25, stratify=reviews["sentiment"], random_state=42,)model = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), min_df=2), LogisticRegression(C=10, max_iter=1000),).fit(X_train, y_train)cm = confusion_matrix(y_test, model.predict(X_test), labels=labels)recall = cm.diagonal() / cm.sum(axis=1)precision = cm.diagonal() / cm.sum(axis=0)print(pd.DataFrame({"precision": precision, "recall": recall}, index=labels).round(3))off = cm.copy()np.fill_diagonal(off, 0)true_i, pred_i = np.unravel_index(off.argmax(), off.shape)print(f"most common error: {labels[true_i]} as {labels[pred_i]} ({off.max()} reviews)")assert np.isclose(recall @ cm.sum(axis=1), cm.diagonal().sum()) precision recallnegative 0.800 0.779neutral 0.867 0.765positive 0.915 0.940most common error: negative as positive (29 reviews)How it works:
- Recall divides each correct count by its row total: the share of a true class that the model finds.
- Precision divides by the column total: the share of a predicted class that is right.
- The interpretation: the most common error is between the two opinionated classes, not with neutral. Those reviews are probably mixed (a positive and a negative sentence) or have a mis-clicked rating; Example 6 of the lesson prints some of them. More neutral data would not fix such errors; better labels or sentence-level models might.
M41-C11 · Rank products by predicted sentiment
Section titled “M41-C11 · Rank products by predicted sentiment”Train a binary pipeline (TF-IDF 1-2 grams with min_df=2, logistic regression with C=10) on all binary reviews. Use it to predict the probability of “positive” for every review, including the neutral ones. Per product, compute the mean rating and the mean predicted probability. Print the 3 products with the lowest mean probability and the correlation between the two columns across products.
reviews rating p_posproductRobot Vacuum 67 3.09 0.64Slim Fit Jeans 131 3.34 0.66Smartwatch Series 5 106 3.47 0.68correlation across 30 products: 0.92model = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), min_df=2), LogisticRegression(C=10, max_iter=1000),)# TODO: fit on binary, predict_proba on reviews["clean"], keep the positive column# TODO: group by product: mean rating and mean probability# TODO: print the 3 lowest and the correlationHint 1
model.classes_ is ['negative', 'positive'], so column 1 of predict_proba is the positive probability.
Hint 2
reviews.assign(p_pos=...).groupby("product").agg(rating=("rating", "mean"), p_pos=("p_pos", "mean")) builds both columns at once. table["rating"].corr(table["p_pos"]) gives the correlation.
Solution
model = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), min_df=2), LogisticRegression(C=10, max_iter=1000),)model.fit(binary["clean"], binary["sentiment"])p_pos = model.predict_proba(reviews["clean"])[:, 1]table = ( reviews.assign(p_pos=p_pos) .groupby("product") .agg(reviews=("rating", "size"), rating=("rating", "mean"), p_pos=("p_pos", "mean")) .sort_values("p_pos", kind="stable"))corr = table["rating"].corr(table["p_pos"])print(table.head(3).round(2))print(f"correlation across {len(table)} products: {corr:.2f}")assert corr > 0.8 reviews rating p_posproductRobot Vacuum 67 3.09 0.64Slim Fit Jeans 131 3.34 0.66Smartwatch Series 5 106 3.47 0.68correlation across 30 products: 0.92How it works:
- The model never saw the neutral reviews, but it still scores them. A neutral review gets a probability somewhere in between, which pulls a product’s mean towards the middle. The binary reviews are scored by a model that trained on them, so their probabilities are a little too confident; M41-X04 shows out-of-fold scoring.
- Grouping turns 3,000 review scores into one score per product.
- The correlation is high: the text alone ranks the products almost like the stars do. This is how you score sources that have no star rating, such as support emails or social media posts.
M41-C12 · Find what unhappy customers complain about
Section titled “M41-C12 · Find what unhappy customers complain about”Run NMF with 6 topics on the negative reviews only (TF-IDF with English stop words, min_df=3, max_df=0.5). Print the 6 top words of each topic and the number of negative reviews whose strongest topic it is.
0 ( 55 reviews): material cheap feels quality looks photos1 ( 54 reviews): days broke cheaply buy size large2 ( 84 reviews): terrible avoid customer service seller month3 (203 reviews): battery arrived delivery quality charge poor4 (116 reviews): price way high point worth justified5 ( 84 reviews): weeks refund waiting ve using recommendfrom sklearn.decomposition import NMF
negative = reviews.loc[reviews["sentiment"] == "negative", "clean"]vec = TfidfVectorizer(stop_words="english", min_df=3, max_df=0.5)# TODO: fit_transform the negative texts# TODO: NMF(n_components=6, init="nndsvda", random_state=42, max_iter=1000)# TODO: print the top 6 words per topic and the count of reviews per strongest topicHint 1
nmf.components_ has one row per topic. np.argsort(row)[::-1][:6] gives the positions of its 6 heaviest words.
Hint 2
doc_topics.argmax(axis=1) gives the strongest topic of each review. np.bincount(..., minlength=6) counts them.
Solution
from sklearn.decomposition import NMF
negative = reviews.loc[reviews["sentiment"] == "negative", "clean"]vec = TfidfVectorizer(stop_words="english", min_df=3, max_df=0.5)matrix = vec.fit_transform(negative)terms = vec.get_feature_names_out()nmf = NMF(n_components=6, init="nndsvda", random_state=42, max_iter=1000)doc_topics = nmf.fit_transform(matrix)sizes = np.bincount(doc_topics.argmax(axis=1), minlength=6)for i, row in enumerate(nmf.components_): print(f"{i} ({sizes[i]:3} reviews): {' '.join(terms[np.argsort(row)[::-1][:6]])}")assert sizes.sum() == len(negative)0 ( 55 reviews): material cheap feels quality looks photos1 ( 54 reviews): days broke cheaply buy size large2 ( 84 reviews): terrible avoid customer service seller month3 (203 reviews): battery arrived delivery quality charge poor4 (116 reviews): price way high point worth justified5 ( 84 reviews): weeks refund waiting ve using recommendHow it works:
- Fitting on negative reviews only gives topics of complaints, not of praise.
- Each review counts once, for its strongest topic. Reviews about two problems still count once, so the sizes are a rough guide.
- Read the topics as a to-do list for the product team: cheap materials, items that broke, bad service, high prices and refunds. Topic 3 mixes battery, delivery and quality and holds the most reviews, a sign that 6 topics are too few for this subset. Name each topic only after you have read a few of its reviews.
M41-C13 · Make typos harmless with character n-grams
Section titled “M41-C13 · Make typos harmless with character n-grams”Fit two vectorizers on the cleaned reviews: a word-level TfidfVectorizer() and a character-level TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5)). For each pair of texts in the starter, print the cosine similarity under both. What does the character model do with the typos?
'qualty' vs 'quality' word 0.00 char 0.22'batery died' vs 'battery died' word 0.63 char 0.72'quality' vs 'refund' word 0.00 char 0.00376 word and 4013 char featuresfrom sklearn.metrics.pairwise import cosine_similarity
pairs = [ ("qualty", "quality"), ("batery died", "battery died"), ("quality", "refund"),]word_vec = TfidfVectorizer().fit(reviews["clean"])# TODO: fit the character vectorizer# TODO: for each pair, transform both texts and print the two cosine similaritiesHint 1
analyzer="char_wb" builds character n-grams inside word boundaries, padded with a space, so " qu" and "ty " mark the start and end of a word.
Hint 2
cosine_similarity(vec.transform([a]), vec.transform([b]))[0, 0] returns one number.
Solution
from sklearn.metrics.pairwise import cosine_similarity
pairs = [ ("qualty", "quality"), ("batery died", "battery died"), ("quality", "refund"),]word_vec = TfidfVectorizer().fit(reviews["clean"])char_vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5))char_vec.fit(reviews["clean"])results = {}for a, b in pairs: word_sim = cosine_similarity(word_vec.transform([a]), word_vec.transform([b]))[0, 0] char_sim = cosine_similarity(char_vec.transform([a]), char_vec.transform([b]))[0, 0] results[(a, b)] = (word_sim, char_sim) print(f"{a!r:14} vs {b!r:15} word {word_sim:.2f} char {char_sim:.2f}")print(len(word_vec.vocabulary_), "word and", len(char_vec.vocabulary_), "char features")assert results[("qualty", "quality")][0] == 0assert results[("qualty", "quality")][1] > results[("quality", "refund")][1]'qualty' vs 'quality' word 0.00 char 0.22'batery died' vs 'battery died' word 0.63 char 0.72'quality' vs 'refund' word 0.00 char 0.00376 word and 4013 char featuresHow it works:
- At word level,
qualtyandqualityare two unrelated columns, so their cosine is 0. The typo makes the word invisible to everything the model learned aboutquality. - At character level, they share several 3- to 5-letter pieces (
" qu","qua","ual"), so their cosine is above 0.qualityandrefundshare no piece, so their cosine stays 0. In a longer text, the other words add shared pieces too:batery diedandbattery diedscore higher with characters than with words. - The price is size: the character vectorizer has many more features. Use it when typos, spelling variants or unseen word forms are common (user comments, product names, short messages).
Challenge
Section titled “Challenge”M41-X01 · Build TF-IDF from scratch as a class
Section titled “M41-X01 · Build TF-IDF from scratch as a class”Refactor from procedural code to a class: write SimpleTfidf with fit(texts), transform(texts) and fit_transform(texts). Use the default scikit-learn token pattern, the smooth idf and L2 row normalization, and return a dense NumPy array. transform must ignore unknown words and return an all-zero row for a text with no known word. Check it against TfidfVectorizer on the first 200 cleaned reviews, and on two new texts.
325 (200, 325)TrueTrue0.0class SimpleTfidf: """A minimal TF-IDF vectorizer that matches scikit-learn's defaults."""
token_pattern = re.compile(r"(?u)\b\w\w+\b")
def fit(self, texts): # TODO: tokenize, build a sorted vocabulary and a word -> column dict # TODO: count document frequencies and compute self.idf_ return self
def transform(self, texts): # TODO: count tokens per text (skip unknown words), multiply by idf_, # TODO: divide each row by its norm (leave all-zero rows as zeros) ...
def fit_transform(self, texts): return self.fit(texts).transform(texts)Hint 1
In fit, a document frequency counts each word once per document: loop over set(tokens).
Hint 2
To avoid dividing by zero, replace zero norms with 1 before dividing: norms[norms == 0] = 1. A zero row divided by 1 stays zero.
Hint 3
Compare with np.allclose(mine, sklearn_vec.fit_transform(texts).toarray()), and check the vocabularies with list(sklearn_vec.get_feature_names_out()).
Solution
class SimpleTfidf: """A minimal TF-IDF vectorizer that matches scikit-learn's defaults."""
token_pattern = re.compile(r"(?u)\b\w\w+\b")
def _tokens(self, text: str) -> list[str]: return self.token_pattern.findall(text.lower())
def fit(self, texts: list[str]) -> "SimpleTfidf": doc_freq: Counter[str] = Counter() for text in texts: doc_freq.update(set(self._tokens(text))) self.vocabulary_ = {word: i for i, word in enumerate(sorted(doc_freq))} df = np.array([doc_freq[word] for word in self.vocabulary_]) self.idf_ = np.log((1 + len(texts)) / (1 + df)) + 1 return self
def transform(self, texts: list[str]) -> np.ndarray: counts = np.zeros((len(texts), len(self.vocabulary_))) for row, text in enumerate(texts): for token in self._tokens(text): col = self.vocabulary_.get(token) if col is not None: counts[row, col] += 1 weights = counts * self.idf_ norms = np.linalg.norm(weights, axis=1, keepdims=True) norms[norms == 0] = 1 return weights / norms
def fit_transform(self, texts: list[str]) -> np.ndarray: return self.fit(texts).transform(texts)
texts = reviews["clean"].head(200).tolist()mine = SimpleTfidf().fit(texts)reference = TfidfVectorizer().fit(texts)new_texts = ["The battery is great", "zzz qqq"]print(len(mine.vocabulary_), mine.transform(texts).shape)print(np.allclose(mine.transform(texts), reference.transform(texts).toarray()))print(np.allclose(mine.transform(new_texts), reference.transform(new_texts).toarray()))print(mine.transform(new_texts)[1].sum())assert list(mine.vocabulary_) == list(reference.get_feature_names_out())assert np.allclose(mine.idf_, reference.idf_)325 (200, 325)TrueTrue0.0How it works:
fitcounts each word once per document withCounter.update(set(tokens)), then builds the sorted vocabulary and the idf array in the same order.transformfills a count matrix row by row and skips unknown tokens, which is exactly what scikit-learn does with out-of-vocabulary words.- Broadcasting multiplies every row by the idf and divides by the row norms. Replacing zero norms by 1 keeps an all-unknown text as a zero row instead of a row of
nan. - A class keeps the fitted state (
vocabulary_,idf_) together with the code that uses it, and follows the scikit-learn convention of a trailing underscore for learned attributes (module 34).
Alternative: in production, keep the output sparse. Build the counts with scipy.sparse.csr_matrix((data, (rows, cols))) and normalize with sklearn.preprocessing.normalize, which supports sparse input.
M41-X02 · Score each aspect of one product
Section titled “M41-X02 · Score each aspect of one product”Aspect-based sentiment rates each aspect of a product separately. For the Robot Vacuum, split every review into sentences, give each sentence an aspect by keyword (table below; a sentence with no keyword gets no aspect), and score the sentence with a binary sentiment model trained on all binary reviews. Print, per aspect, the number of sentences and the share predicted negative, sorted from the worst aspect down.
| Aspect | Keywords |
|---|---|
| battery | battery, charge |
| quality | quality, material, made |
| price | price, money, value |
| delivery | delivery, package, shipping, arrived |
| service | service, support, seller, refund |
| durability | broke, lasted, months, durable |
| ease of use | setup, easy, instructions |
67 reviews, 175 sentences, 108 with aspect sentences negative_shareaspectdurability 10 0.50quality 18 0.44price 7 0.43battery 34 0.38service 5 0.20delivery 11 0.18ease of use 23 0.13ASPECTS = { "battery": ["battery", "charge"], # TODO: the other aspects from the table}model = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), min_df=2), LogisticRegression(C=10, max_iter=1000),).fit(binary["clean"], binary["sentiment"])vacuum = reviews.loc[reviews["product"] == "Robot Vacuum", "clean"]# TODO: split each review into sentences with re.split(r"(?<=[.!?])\s+", text)# TODO: find the first aspect whose keyword appears in each sentence# TODO: predict each sentence, then group by aspectHint 1
The pattern (?<=[.!?])\s+ splits at whitespace that follows a sentence end, and keeps the punctuation with the sentence.
Hint 2
Build a list of (aspect, sentence) pairs, make a DataFrame from it, add the predictions as a column and use groupby("aspect") with agg.
Hint 3
Match whole words: re.search(rf"\b{keyword}\b", sentence), so made does not match inside homemade.
Solution
ASPECTS = { "battery": ["battery", "charge"], "quality": ["quality", "material", "made"], "price": ["price", "money", "value"], "delivery": ["delivery", "package", "shipping", "arrived"], "service": ["service", "support", "seller", "refund"], "durability": ["broke", "lasted", "months", "durable"], "ease of use": ["setup", "easy", "instructions"],}
def find_aspect(sentence: str) -> str | None: """Return the first aspect whose keyword appears in the sentence.""" for aspect, keywords in ASPECTS.items(): if any(re.search(rf"\b{word}\b", sentence) for word in keywords): return aspect return None
model = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), min_df=2), LogisticRegression(C=10, max_iter=1000),).fit(binary["clean"], binary["sentiment"])vacuum = reviews.loc[reviews["product"] == "Robot Vacuum", "clean"]rows = [ (find_aspect(sentence), sentence) for text in vacuum for sentence in re.split(r"(?<=[.!?])\s+", text)]sentences = pd.DataFrame(rows, columns=["aspect", "sentence"]).dropna()sentences["negative"] = model.predict(sentences["sentence"]) == "negative"summary = ( sentences.groupby("aspect") .agg(sentences=("sentence", "size"), negative_share=("negative", "mean")) .sort_values("negative_share", ascending=False, kind="stable"))print(len(vacuum), "reviews,", len(rows), "sentences,", len(sentences), "with aspect")print(summary.round(2))assert summary["sentences"].sum() == len(sentences)assert summary["negative_share"].between(0, 1).all()67 reviews, 175 sentences, 108 with aspect sentences negative_shareaspectdurability 10 0.50quality 18 0.44price 7 0.43battery 34 0.38service 5 0.20delivery 11 0.18ease of use 23 0.13How it works:
- The lookbehind
(?<=[.!?])splits after the sentence end without consuming it. find_aspectreturns the first matching aspect, so the dictionary order sets the priority when a sentence mentions two aspects.- The model was trained on whole reviews, but a sentence is just a short text, so the same pipeline scores it. Short sentences give less evidence, so expect more errors than on whole reviews.
- The table turns one star rating into a profile of the product’s aspects. Read it as a rough guide: with 5 to 34 sentences per aspect, one sentence moves a share by several points, and the model trained on these same Robot Vacuum reviews, so it scores sentences that it saw during training.
Alternative: instead of keywords, give each sentence the strongest topic of the NMF model from the lesson. Topics find aspects you did not think of, but their names and boundaries are less precise.
M41-X03 · Choose the number of topics by stability
Section titled “M41-X03 · Choose the number of topics by stability”Choose a method and justify it: the reconstruction error cannot choose n_components. A second criterion is stability: a good topic appears again when you refit with another random start. For k in 6, 8, 10, 12 and 14, fit NMF with init="random" and three seeds (0, 1, 2) on the topic TF-IDF matrix of the lesson. For each pair of fits, match each topic to its most similar topic in the other fit (cosine of the rows of components_) and average those similarities. Print the mean stability per k, then choose k.
k= 6 stability 0.768k= 8 stability 0.934k=10 stability 0.948k=12 stability 0.930k=14 stability 0.917from itertools import combinations
from sklearn.decomposition import NMF
vec = TfidfVectorizer(stop_words="english", min_df=5, max_df=0.5)matrix = vec.fit_transform(reviews["clean"])
def unit_rows(h: np.ndarray) -> np.ndarray: return h / np.linalg.norm(h, axis=1, keepdims=True)
for k in [6, 8, 10, 12, 14]: # TODO: fit three NMF models (random_state 0, 1, 2) and keep unit_rows(components_) # TODO: for each pair, (a @ b.T).max(axis=1).mean() is the matching similarity # TODO: print the mean over the three pairs ...Hint 1
a @ b.T is a k × k matrix of cosine similarities between the topics of two fits (the rows have length 1).
Hint 2
combinations(fits, 2) yields the three pairs of a list of three fits.
Solution
from itertools import combinations
from sklearn.decomposition import NMF
vec = TfidfVectorizer(stop_words="english", min_df=5, max_df=0.5)matrix = vec.fit_transform(reviews["clean"])
def unit_rows(h: np.ndarray) -> np.ndarray: return h / np.linalg.norm(h, axis=1, keepdims=True)
stability = {}for k in [6, 8, 10, 12, 14]: fits = [ unit_rows( NMF(n_components=k, init="random", random_state=seed, max_iter=1000) .fit(matrix) .components_ ) for seed in (0, 1, 2) ] pair_scores = [(a @ b.T).max(axis=1).mean() for a, b in combinations(fits, 2)] stability[k] = float(np.mean(pair_scores)) print(f"k={k:2} stability {stability[k]:.3f}")assert min(stability, key=stability.get) == 6k= 6 stability 0.768k= 8 stability 0.934k=10 stability 0.948k=12 stability 0.930k=14 stability 0.917How it works:
init="random"makes each seed start from a different point, so unstable topics come out differently each time. (nndsvdastarts from a randomized SVD. With a fixedrandom_stateit is reproducible, and it varies much less across seeds thaninit="random", so it would understate the instability.)- For each topic of fit
a,max(axis=1)finds its best match in fitb. A mean near 1 means that the fits found the same topics. - A justified choice: 10 topics. With 6, the topics are unstable: the model must merge real themes, and it merges them differently each time. From 8 to 14, the values are all about equally stable: the differences are small for only three seeds. Stability rules out 6, and reading the topics picks 10, the smallest value whose topics all have clear names (Example 7 of the lesson).
M41-X04 · Flag mis-clicked ratings
Section titled “M41-X04 · Flag mis-clicked ratings”About 6% of the 1-, 2-, 4- and 5-star reviews have a text whose tone contradicts the rating (see the data dictionary). Find candidates on the binary reviews: get out-of-fold probabilities with cross_val_predict(..., cv=5, method="predict_proba") for a TF-IDF 1-2 grams + logistic regression (C=10) pipeline. Flag a review when the probability of its own label is below 0.1. Print the number and share of flagged reviews, the counts per label, and the 3 flagged reviews with the lowest probability.
62 flagged (2.3%){'negative': 37, 'positive': 25}p_own below 0.5 (misclassified): 242 rating p_own clean2306 1 0.001 this one is still going strong after 9 months. the batte...2014 1 0.002 this is my second one. well made with great attention to...867 1 0.002 the seller was quite helpful. mine is sturdy and built t...from sklearn.model_selection import cross_val_predict
model = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), min_df=2), LogisticRegression(C=10, max_iter=1000),)# TODO: out-of-fold probabilities for binary["clean"]# TODO: probability of each review's own label (column 0 = negative, 1 = positive)# TODO: flag < 0.1, print the counts and the 3 most suspicious reviewsHint 1
Out-of-fold means that each review is scored by a model that did not train on it. A model that has memorized a review cannot flag it.
Hint 2
np.where(labels == "positive", proba[:, 1], proba[:, 0]) picks the probability of each row’s own label.
Solution
from sklearn.model_selection import cross_val_predict
model = make_pipeline( TfidfVectorizer(ngram_range=(1, 2), min_df=2), LogisticRegression(C=10, max_iter=1000),)labels = binary["sentiment"].to_numpy()proba = cross_val_predict(model, binary["clean"], labels, cv=5, method="predict_proba")p_own = np.where(labels == "positive", proba[:, 1], proba[:, 0])flagged = binary.assign(p_own=p_own)[p_own < 0.1]print(f"{len(flagged)} flagged ({len(flagged) / len(binary):.1%})")print(flagged["sentiment"].value_counts().to_dict())print(f"p_own below 0.5 (misclassified): {(p_own < 0.5).sum()}")print(flagged.nsmallest(3, "p_own")[["rating", "p_own", "clean"]].round(3))assert len(flagged) < 0.06 * len(binary)62 flagged (2.3%){'negative': 37, 'positive': 25}p_own below 0.5 (misclassified): 242 rating p_own clean2306 1 0.001 this one is still going strong after 9 months. the batte...2014 1 0.002 this is my second one. well made with great attention to...867 1 0.002 the seller was quite helpful. mine is sturdy and built t...How it works:
cross_val_predictwithmethod="predict_proba"returns, for every review, the probabilities from the fold model that did not see it.- A probability below 0.1 for the review’s own label means: the model is at least 90% sure that the text says the opposite.
- Fewer reviews are flagged than the 6% that are mislabeled. The model gets more reviews wrong (
p_ownbelow 0.5) than it flags, so many errors are not confident ones. Probably many mis-clicked reviews are short or mixed, and the model is unsure about them. The flag is a cautious shortlist for a human to check, not a relabeling rule.
M41-X05 · Build a reusable review search class
Section titled “M41-X05 · Build a reusable review search class”Write a class ReviewSearch that wraps the LSA pipeline of the lesson. fit(texts) cleans the texts, fits a TF-IDF vectorizer (English stop words, min_df=2), a TruncatedSVD with n_components (default 50, random_state=42) and a Normalizer, and stores the document vectors. search(query, k=3) returns a list of (index, cosine) pairs for the k most similar documents. A query with no known word returns an empty list. Fit it on all reviews and run the three queries in the starter.
'refund never arrived' 0.770 the seller ignored my refund request. the delivery arrived late and th 0.745 i've been using it for 7 weeks now. the seller processed my refund the'charging''runs small' 0.832 runs small, the size is wrong. 0.747 too large even in a small size.from sklearn.decomposition import TruncatedSVDfrom sklearn.preprocessing import Normalizer
class ReviewSearch: def __init__(self, n_components: int = 50) -> None: self.n_components = n_components
def fit(self, texts: pd.Series) -> "ReviewSearch": # TODO: clean, vectorize, reduce, normalize; store the document vectors return self
def search(self, query: str, k: int = 3) -> list[tuple[int, float]]: # TODO: return [] when the query has no known word # TODO: embed the query and return the k best (index, cosine) pairs ...
engine = ReviewSearch().fit(reviews["text"])for query in ["refund never arrived", "charging", "runs small"]: # TODO: print the query and its hits with the review text ...Hint 1
Store the vectorizer and an LSA pipeline (make_pipeline(TruncatedSVD(...), Normalizer())) as attributes, so search can call their transform methods.
Hint 2
self.vectorizer.transform([query]).nnz == 0 is True when no word of the query is in the vocabulary.
Solution
from sklearn.decomposition import TruncatedSVDfrom sklearn.preprocessing import Normalizer
class ReviewSearch: """Find similar texts with LSA embeddings and cosine similarity."""
def __init__(self, n_components: int = 50) -> None: self.n_components = n_components
def fit(self, texts: pd.Series) -> "ReviewSearch": cleaned = [clean_text(text) for text in texts] self.vectorizer_ = TfidfVectorizer(stop_words="english", min_df=2) self.lsa_ = make_pipeline( TruncatedSVD(n_components=self.n_components, random_state=42), Normalizer(), ) self.doc_vectors_ = self.lsa_.fit_transform( self.vectorizer_.fit_transform(cleaned) ) return self
def search(self, query: str, k: int = 3) -> list[tuple[int, float]]: sparse = self.vectorizer_.transform([clean_text(query)]) if sparse.nnz == 0: return [] sims = self.doc_vectors_ @ self.lsa_.transform(sparse)[0] best = np.argsort(-sims, kind="stable")[:k] return [(int(i), round(float(sims[i]), 3)) for i in best]
engine = ReviewSearch().fit(reviews["text"])results = {}for query in ["refund never arrived", "charging", "runs small"]: results[query] = engine.search(query, k=2) print(repr(query)) for index, cosine in results[query]: print(f" {cosine:.3f} {reviews.loc[index, 'clean'][:70]}")assert results["charging"] == []assert len(results["runs small"]) == 2'refund never arrived' 0.770 the seller ignored my refund request. the delivery arrived late and th 0.745 i've been using it for 7 weeks now. the seller processed my refund the'charging''runs small' 0.832 runs small, the size is wrong. 0.747 too large even in a small size.How it works:
fitstores every fitted step as an attribute with a trailing underscore, the scikit-learn convention for learned state.searchuses onlytransform, so the query lands in the same space as the documents.nnz == 0catches out-of-vocabulary queries before they produce a zero vector, whose cosine with every document is 0. The “best” hits would be arbitrary: with a stable sort, just the first rows of the corpus.chargingis not in the vocabulary, so it returns no hits. A production search would fall back to character n-grams or a pretrained embedding model here.- The second hit for
refund never arrivedpraises a fast refund. The search finds the topic, not the tone; filter by a sentiment model when the tone matters.