Capstone 7 — Review sentiment
The customer-support lead of the online shop wants every unhappy customer message in the support queue within a day. The shop is adding a free-text feedback form, and agents paste chat messages into the same tool. These texts have no star rating, so a model must read the text. The 3,000 product reviews have stars, so they are the training data: their stars give the labels.
The data team has two proposals: a classic TF-IDF + logistic regression model and a small neural network in PyTorch. The lead asks three questions:
- Which model should we put behind the routing rule, and why? “Better” includes accuracy, but also simplicity, cost and how easy it is to explain a decision to an agent.
- What happens to lukewarm texts? New messages will include “it’s okay”-type texts, like the 3-star reviews. The routing must handle them on purpose, not by accident.
- What do unhappy customers complain about? The product managers want the main complaint aspects per category, how severe they are and whether they change over time.
The model comparison uses the clear cases: negative (rating 1 or 2) versus positive (rating 4 or 5). The 3-star reviews get an explicit, measured decision in Milestone 3.
Deliverables:
- one script or notebook that runs top to bottom in under a minute on a laptop CPU;
- a tested
clean_textfunction and a split where no text appears in two parts; - a tuned baseline and a tuned PyTorch model, a choice made on validation data, and one read of the test set;
- a short written recommendation: which model to ship, with which classes, and why;
- a table and a chart of complaint aspects.
Skills practiced: text cleaning with regular expressions (module 09, module 26), tests with assert (module 14), pipelines (module 34), classification metrics (module 36), group-aware splits and tuning (module 37), TF-IDF and NMF (module 41), PyTorch training with early stopping (module 42) and the bootstrap (module 29).
Dataset
Section titled “Dataset”data/reviews.csv: 3,000 product reviews from 2023 and 2024. Read it with keep_default_na=False. The full description is in the data dictionary.
| Column | Use in this capstone |
|---|---|
text |
the review text: the only model input |
sentiment |
the label: positive (rating 4 or 5, 2,066 reviews), negative (rating 1 or 2, 596), neutral (rating 3, 338) |
rating |
stars from 1 to 5, to read the errors and the severity of complaints |
category |
6 product categories, for the aspect table |
review_date |
the date, for the aspect trend |
Known quirks, as the data dictionary lists them:
- HTML entities (
&,'), whole texts in upper case, double spaces, leading and trailing spaces and line breaks inside the text. - Typos such as
recieved,definately,qualty,teh,recomendandbateryin 170 reviews. - About 6% of the reviews with rating 1, 2, 4 or 5 have text with the opposite tone (a mis-clicked rating), so accuracy cannot reach 1.0.
- Rating 3 mixes a positive and a negative sentence, or is neutral. Ratings 2 and 4 are often mixed (“But …”, “However, …”).
Milestone 2 finds one more quirk that matters for every score: many reviews share the exact same text.
The reference scores in the data dictionary use a plain random 75/25 split. Your numbers will differ.
Milestones
Section titled “Milestones”Milestone 1 — Clean the text, with tests
Section titled “Milestone 1 — Clean the text, with tests”Goal: One function turns every raw review into one standard form.
Acceptance criteria:
clean_text(text: str) -> strdecodes HTML entities, lowercases, fixes the known typos as whole words only and collapses whitespace.- At least 5
assertcases, including an empty string and a word that only contains a typo (tehranmust staytehran). - A check that the function is idempotent on the whole column:
clean_text(clean_text(t)) == clean_text(t). - The raw
textcolumn stays unchanged.
Review: module 09 (re), module 14, module 41 (cleaning text).
Milestone 2 — Find repeated texts and split by text
Section titled “Milestone 2 — Find repeated texts and split by text”Goal: Make sure that no text can be learned in one part and scored in another.
Acceptance criteria:
- The number of reviews whose cleaned text appears more than once, and the number of repeated texts that carry two different labels.
- A 60/20/20 train/validation/test split of all 3,000 reviews, stratified by
sentiment, with the cleaned text as the group (StratifiedGroupKFold),random_state=42. assertchecks that no cleaned text appears in two parts. Print the class shares of each part.- The positive and negative subsets of each part, with their size and negative share.
Review: module 37 (group leakage, StratifiedGroupKFold).
Milestone 3 — Tune a baseline and decide on the neutral class
Section titled “Milestone 3 — Tune a baseline and decide on the neutral class”Goal: Build the strongest simple model, and measure whether neutral texts need their own class.
Acceptance criteria:
- A majority-class reference score.
- One
PipelinewithTfidfVectorizerandLogisticRegression, tuned withGridSearchCVon the training rows only. Use grouped, stratified 5-fold CV. The grid coversngram_range, at least 4 values ofCandclass_weight. Score with F1 for the negative class. - The validation scores of the chosen model.
- A grouped CV check on the training rows with all three classes: per-class scores of a 3-class model, and the negative precision and recall of the binary and the 3-class model when neutral texts are present.
- A decision for the neutral class, based on those numbers.
Review: module 34, module 37, module 41.
Milestone 4 — Read the errors and the n-grams
Section titled “Milestone 4 — Read the errors and the n-grams”Goal: Understand what the baseline gets wrong before you try a bigger model.
Acceptance criteria:
- On the validation set (never the test set): the number of false alarms and missed negatives.
- A count of the errors by cause (for example: confident, mixed wording, mild rating, other), with two examples per cause.
- The 8 strongest terms in each direction, each with its document frequency.
- Conclusions that match the printed counts.
Milestone 5 — Train and tune a PyTorch model
Section titled “Milestone 5 — Train and tune a PyTorch model”Goal: Give the neural network a fair chance on the same training rows.
Acceptance criteria:
- An
nn.Modulebuilt onnn.EmbeddingBag, with an optional hidden layer. Its vocabulary comes from the training texts only. torch.manual_seed(42)andtorch.set_num_threads(1), with a sentence that explains the second one.BCEWithLogitsLosswithpos_weight; early stopping on the validation loss, at most 20 epochs, best weights restored.- A small tuning grid on the validation set: with and without a hidden layer, 2 embedding sizes, 2 learning rates.
- A loss-curve figure, and the final network as the average of 3 seeds.
Review: module 42.
Milestone 6 — Choose on validation, then read the test set once
Section titled “Milestone 6 — Choose on validation, then read the test set once”Goal: A fair comparison and a decision that the test set confirms but does not make.
Acceptance criteria:
- A decision rule written down before the test read, applied to the validation scores. Print the choice.
- The shipped model refitted on the training and validation rows, before the test read.
- One code block that reads the test set. Accuracy, F1 (negative) and ROC-AUC for both binary models on the same test reviews, threshold 0.5.
- A paired bootstrap interval for each difference, with at least 2,000 resamples, and a sentence on what it does not cover.
- Confusion matrices as one figure; the scores of the shipped model on all test texts.
- The cost of each model: parameters and training time (printed next to a comparison, because times vary between machines).
Review: module 36, module 37, module 29.
Milestone 7 — Recommend a model
Section titled “Milestone 7 — Recommend a model”Goal: Answer the support lead in one paragraph.
Acceptance criteria:
- Name the model and its classes. Support the choice with the validation decision, the test confirmation, the cost and how easy each model is to explain.
- Say how the routing treats negative, neutral and positive texts.
- Show the shipped model on a few new texts.
Milestone 8 — Measure the complaint aspects
Section titled “Milestone 8 — Measure the complaint aspects”Goal: Go beyond module 41’s topic list: measure how often each aspect occurs, how severe it is and whether it changes.
Acceptance criteria:
- NMF on the TF-IDF matrix of the negative reviews (start from module 41’s topic step). Print the top terms and the most typical review of each topic.
- Check what a topic really holds with keyword shares before you name it.
- Count a review for every aspect whose weight is at least half of its strongest one, not only for the top topic.
- Per aspect: number of reviews, share of 1-star reviews and share in 2023 versus 2024.
- A category × aspect heatmap, and findings that match the printed shares.
Review: module 41 (topic modeling), module 28.
Grading rubric
Section titled “Grading rubric”| Criterion | Needs work | Meets | Excellent | Points |
|---|---|---|---|---|
| 1. Cleaning and tests | 0–3: cleaning spread over several places, no tests | 4–7: one function, a few asserts | 8–10: edge cases (empty text, whole-word typos) and an idempotency check | 10 |
| 2. Leak-free split | 0–3: random split; identical texts in train and test | 4–7: stratified split, repeats counted | 8–10: grouped and stratified split of all classes; asserts; label conflicts found | 10 |
| 3. Baseline and neutral decision | 0–5: default settings, or neutral reviews dropped without a check | 6–11: grouped CV tuning; a stated neutral decision | 12–15: the neutral decision rests on a printed 3-class versus binary comparison | 15 |
| 4. Error analysis | 0–3: accuracy only | 4–7: misclassified reviews and top terms shown | 8–10: errors counted by cause; conclusions match the counts; validation only | 10 |
| 5. PyTorch model | 0–7: no early stopping, or not reproducible | 8–15: seeded model with early stopping and restored weights | 16–20: tuned on validation, seed average, and a clear view of what the model can express | 20 |
| 6. Choice and test read | 0–5: model chosen on test, or the test set read several times | 6–11: same test set, three metrics, confusion matrices | 12–15: rule fixed on validation, one test read, bootstrap with its limits, cost | 15 |
| 7. Recommendation | 0–3: “the neural network is better” without evidence | 4–7: a choice backed by scores | 8–10: scores, uncertainty, cost and explainability weighed; routing for all three classes | 10 |
| 8. Aspect insight | 0–3: topic numbers without names | 4–7: named topics with counts | 8–10: names checked with keyword shares; multi-aspect counts; severity and trend; claims match the numbers | 10 |
| Total | 100 |
Reference solution
Section titled “Reference solution”Try each milestone yourself first. The solution runs top to bottom in one namespace, in about 10 seconds on a laptop CPU. Your numbers can differ if you choose other settings; the numbers for the same settings must not.
Reference solution — Milestone 1: Clean the text
Load the reviews and check how the labels relate to the stars.
import htmlimport reimport textwrap
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)print(reviews.shape)print(reviews.groupby("sentiment")["rating"].agg(["min", "max", "size"]))(3000, 9) min max sizesentimentnegative 1 2 596neutral 3 3 338positive 4 5 2066The label is a function of the stars: negative is 1–2, neutral is exactly 3, positive is 4–5. The model learns stars from text, so a mis-clicked star is a wrong label.
The cleaning function has four steps. Entities are decoded first, because entity names are case-sensitive. The typo fix runs after lowercasing, so Teh and teh both match. \b (a word boundary) makes the fix apply to whole words only.
TYPOS = { "recieved": "received", "definately": "definitely", "qualty": "quality", "teh": "the", "recomend": "recommend", "batery": "battery",}TYPO_RE = re.compile(r"\b(?:" + "|".join(TYPOS) + r")\b") # whole words only
def clean_text(text: str) -> str: """Decode HTML entities, lowercase, fix known typos, collapse whitespace.""" text = html.unescape(text).lower() text = TYPO_RE.sub(lambda match: TYPOS[match.group(0)], text) return re.sub(r"\s+", " ", text).strip()The tests are plain assert statements: a dictionary of input → expected output. Each case covers one rule. Tehran and qualtys check the word boundary: they contain a typo but are not one. The last check runs the function twice on every review. A cleaning step must be idempotent (applying it twice gives the same result as once). Otherwise, text that is cleaned again in production would not match the training data.
cases = { " Sturdy & WELL MADE!!! ": "sturdy & well made!!!", "I've used it\ndaily.": "i've used it daily.", "Great qualty. Teh price is fair.": "great quality. the price is fair.", "Tehran is far. The qualtys": "tehran is far. the qualtys", "": "",}for raw, expected in cases.items(): result = clean_text(raw) assert result == expected, f"{raw!r} -> {result!r}, expected {expected!r}"once = reviews["text"].map(clean_text)assert once.equals(once.map(clean_text)), "clean_text must be idempotent"print(f"{len(cases)} cases pass; idempotent on all {len(reviews):,} reviews")5 cases pass; idempotent on all 3,000 reviewsreviews["clean"] = oncehas_typo = reviews["text"].str.lower().str.contains(TYPO_RE)print(f"{has_typo.sum()} reviews had a known typo")example = reviews.loc[has_typo, ["text", "clean"]].iloc[0]print(repr(example["text"]))print(repr(example["clean"]))144 reviews had a known typo'Delivery was quicker than promised. However, the purifier arrived scratched, poor qualty control.''delivery was quicker than promised. however, the purifier arrived scratched, poor quality control.'The six listed typos occur in 144 reviews. The data dictionary counts 170 reviews with typos, so some rarer typos remain. min_df=2 in the vectorizer drops any term found in only one training review, so a one-off typo does no harm. The example shows three fixes at once: the double space, the capital letters and qualty.
Reference solution — Milestone 2: Find repeated texts and split by text
Short reviews can repeat word for word. Count them on the cleaned text.
group_size = reviews.groupby("clean")["clean"].transform("size")repeated = reviews[group_size > 1]labels_per_text = repeated.groupby("clean")["sentiment"].nunique()print(f"{len(repeated)} reviews share their text with another review")two_labels = labels_per_text[labels_per_text > 1]print(f"{labels_per_text.size} repeated texts, {two_labels.size} with two labels")same_text = reviews.loc[reviews["clean"] == two_labels.index[0], ["rating", "clean"]]print(same_text.to_string(index=False))267 reviews share their text with another review104 repeated texts, 7 with two labels rating clean 2 customer service ignored my refund request. 5 customer service ignored my refund request.267 reviews (9%) share their text with at least one other review. With a random split, a model could see a text in training and be scored on the same text in the test set. That measures memory, not reading. 7 repeated texts carry two labels: the same complaint with 2 stars and with 5 stars. No model can get both right.
The fix is a grouped split: all reviews with the same cleaned text go to the same part. StratifiedGroupKFold keeps groups together and the class shares stable. Its first fold of 5 gives the 20% test set. The first fold of 4 on the rest gives the validation set (20% of the total). The split covers all three classes, so the neutral reviews are split in the same way and Milestone 3 can use them.
from sklearn.model_selection import StratifiedGroupKFold
outer = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42)dev_rows, test_rows = next(outer.split(reviews, reviews["sentiment"], reviews["clean"]))dev, test = reviews.iloc[dev_rows], reviews.iloc[test_rows]inner = StratifiedGroupKFold(n_splits=4, shuffle=True, random_state=42)train_rows, val_rows = next(inner.split(dev, dev["sentiment"], dev["clean"]))train, val = dev.iloc[train_rows], dev.iloc[val_rows]
shares = pd.DataFrame({ name: part["sentiment"].value_counts(normalize=True) for name, part in [("train", train), ("validation", val), ("test", test)]})print(shares.round(3).to_string())print("rows:", len(train), len(val), len(test))assert not set(train["clean"]) & set(val["clean"])assert not set(dev["clean"]) & set(test["clean"])print("texts shared between parts: 0") train validation testsentimentpositive 0.689 0.688 0.688negative 0.199 0.198 0.198neutral 0.112 0.113 0.113rows: 1800 600 600texts shared between parts: 0The parts have 1,800, 600 and 600 reviews with the same class shares, and the asserts prove that no text crosses a border. The model comparison uses the positive and negative reviews of each part. Negative is coded as 1, so F1 and ROC-AUC measure how well a model finds the texts that support must see.
def binary(part: pd.DataFrame) -> tuple[pd.Series, pd.Series]: """Positive and negative reviews only; 1 = negative, the class we act on.""" rows = part[part["sentiment"] != "neutral"] return rows["clean"], (rows["sentiment"] == "negative").astype(int)
X_train, y_train = binary(train)X_val, y_val = binary(val)X_test, y_test = binary(test)for name, y_part in [("train", y_train), ("validation", y_val), ("test", y_test)]: print(f"{name:10} {len(y_part):5,} reviews, {y_part.mean():.3f} negative")train 1,598 reviews, 0.224 negativevalidation 532 reviews, 0.224 negativetest 532 reviews, 0.224 negativeReference solution — Milestone 3: Tune a baseline and decide on the neutral class
First, the score of a model that always says “positive”. Every CV in this capstone uses grouped, stratified folds, with the text itself as the group.
from sklearn.dummy import DummyClassifierfrom sklearn.model_selection import cross_validate
cv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42)dummy = cross_validate( DummyClassifier(strategy="most_frequent"), X_train, y_train, groups=X_train, cv=cv, scoring=["accuracy", "f1"],)print(f"majority class: accuracy {dummy['test_accuracy'].mean():.3f}, " f"F1 {dummy['test_f1'].mean():.3f}")majority class: accuracy 0.776, F1 0.00077.6% accuracy with no skill at all, and an F1 of 0 because it never finds a negative review. This is why the search optimizes F1 for the negative class, not accuracy.
The search tunes the n-gram range, the penalty strength C (a small C means strong regularization) and class_weight. class_weight="balanced" gives each negative review more weight in the loss, in proportion to how rare the class is. The vectorizer sits inside the pipeline, so each fold fits its own vocabulary on its own training part. groups=X_train keeps identical texts in one fold.
from sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import GridSearchCVfrom sklearn.pipeline import Pipeline
pipe = Pipeline([ ("tfidf", TfidfVectorizer(min_df=2)), ("logreg", LogisticRegression(max_iter=2000)),])grid = { "tfidf__ngram_range": [(1, 1), (1, 2)], "logreg__C": [0.3, 1, 3, 10, 30], "logreg__class_weight": [None, "balanced"],}search = GridSearchCV(pipe, grid, cv=cv, scoring="f1")search.fit(X_train, y_train, groups=X_train) # identical texts stay in one foldresults = pd.DataFrame(search.cv_results_).sort_values("rank_test_score")results["ngrams"] = results["param_tfidf__ngram_range"].astype(str)cols = ["ngrams", "param_logreg__C", "param_logreg__class_weight", "mean_test_score", "std_test_score"]print(results[cols].head(6).to_string(index=False))print(search.best_params_)ngrams param_logreg__C param_logreg__class_weight mean_test_score std_test_score(1, 1) 3.0 balanced 0.808 0.029(1, 2) 1.0 balanced 0.807 0.039(1, 1) 1.0 balanced 0.805 0.034(1, 2) 0.3 balanced 0.805 0.037(1, 2) 3.0 balanced 0.805 0.034(1, 1) 10.0 balanced 0.800 0.016{'logreg__C': 3, 'logreg__class_weight': 'balanced', 'tfidf__ngram_range': (1, 1)}All six top configurations use balanced class weights. The top five differ by 0.003, far less than their standard deviations (0.029–0.039). Unigrams and bigrams tie here. The search picks unigrams with C=3, the simplest of the tied models.
GridSearchCV refits the best pipeline on all 1,598 training rows. Score it on the validation set. The validation set played no part in the search, so this score is honest.
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
baseline = search.best_estimator_p_val_lr = baseline.predict_proba(X_val)[:, 1] # P(negative)print(f"validation: accuracy {accuracy_score(y_val, p_val_lr > 0.5):.3f}, " f"F1 {f1_score(y_val, p_val_lr > 0.5):.3f}, " f"ROC-AUC {roc_auc_score(y_val, p_val_lr):.3f}")assert search.best_score_ > dummy["test_f1"].mean() + 0.5validation: accuracy 0.904, F1 0.810, ROC-AUC 0.929The validation F1 (0.810) matches the cross-validated F1 (0.808).
The neutral question. In production, lukewarm texts will arrive too. A binary model has never seen one, but it must still give it a probability. Two designs are possible:
- binary: train on positive and negative only; every text is “negative” or “not negative”;
- 3-class: train with neutral as its own class; route only “negative” to the support queue.
Compare them with the same grouped folds on the 1,800 training reviews, neutral ones included. Both use the tuned settings. In each fold, the binary model trains on the fold’s positive and negative reviews, and both models score all of the fold’s held-out texts.
from sklearn.base import clonefrom sklearn.metrics import classification_report, precision_recall_fscore_support
folds = []for fit_rows, score_rows in cv.split(train, train["sentiment"], train["clean"]): fit_part, score_part = train.iloc[fit_rows], train.iloc[score_rows] two = clone(baseline).fit(*binary(fit_part)) three = clone(baseline).fit(fit_part["clean"], fit_part["sentiment"]) folds.append(pd.DataFrame({ "true": score_part["sentiment"], "binary": np.where(two.predict(score_part["clean"]) == 1, "negative", "other"), "three": three.predict(score_part["clean"]), }))oof = pd.concat(folds)print(classification_report(oof["true"], oof["three"], digits=3)) precision recall f1-score support
negative 0.732 0.855 0.789 358 neutral 0.724 0.881 0.795 202 positive 0.961 0.881 0.919 1240
accuracy 0.876 1800 macro avg 0.806 0.872 0.834 1800weighted avg 0.889 0.876 0.879 1800The 3-class model finds 88.1% of the neutral reviews, with F1 0.795. Neutral texts have their own wording, so a third class is learnable. Now the number that matters for routing: how well does each design find negative texts when neutral texts are in the stream?
is_negative = oof["true"] == "negative"is_neutral = oof["true"] == "neutral"for name in ["binary", "three"]: flagged = oof[name] == "negative" precision, recall, f1, _ = precision_recall_fscore_support( is_negative, flagged, average="binary" ) print(f"{name:6} model, all texts: negative precision {precision:.3f}, " f"recall {recall:.3f}, F1 {f1:.3f}; " f"neutral flagged {flagged[is_neutral].mean():.0%}")binary model, all texts: negative precision 0.566, recall 0.888, F1 0.691; neutral flagged 62%three model, all texts: negative precision 0.732, recall 0.855, F1 0.789; neutral flagged 5%The binary model sends 62% of the neutral texts to the support queue, and its negative precision drops to 0.566. The 3-class model sends 5%, keeps precision at 0.732 and gives up only 0.033 of recall (0.855 against 0.888).
Decision: compare the two model families on the positive and negative reviews, where the labels are clear. Then ship the winner with three classes: negative texts go to the support queue, neutral texts to a second, lower-priority queue. This decision comes from CV on the training rows; the test set is still untouched.
Reference solution — Milestone 4: Read the errors and the n-grams
Count the errors on the validation set, then sort each error into one cause. The causes are checked in order, so each error gets exactly one:
- confident: the probability for the wrong class is above 0.9;
- mixed wording: the text contains
but,however,that saidoron the other hand; - mild rating: the rating is 2 or 4;
- other.
from sklearn.metrics import confusion_matrix
val_view = pd.DataFrame({"text": X_val, "true": y_val, "p_neg": p_val_lr})val_view["rating"] = val.loc[X_val.index, "rating"]val_view["pred"] = (val_view["p_neg"] > 0.5).astype(int)tn, fp, fn, tp = confusion_matrix(val_view["true"], val_view["pred"]).ravel()print(f"validation errors: {fp} false alarms, {fn} missed negatives")errors = val_view[val_view["true"] != val_view["pred"]].copy()errors["margin"] = (errors["p_neg"] - 0.5).abs()mixed_re = r"\b(?:but|however|that said|on the other hand)\b"errors["cause"] = np.select( [errors["margin"] > 0.4, errors["text"].str.contains(mixed_re), errors["rating"].isin([2, 4])], ["confident (P > 0.9 wrong way)", "mixed wording", "mild rating (2 or 4)"], default="other",)print(errors["cause"].value_counts().to_string())mixed_all = val_view["text"].str.contains(mixed_re).mean()print(f"mixed wording in all validation reviews: {mixed_all:.0%}")validation errors: 41 false alarms, 10 missed negativescausemixed wording 20confident (P > 0.9 wrong way) 16mild rating (2 or 4) 9other 6mixed wording in all validation reviews: 13%False alarms (41) outnumber missed negatives (10) four to one. That is the trade that class_weight="balanced" makes: the boundary moves toward the negative class. For a support queue it is a sensible trade. An agent skips a false alarm in seconds, but a missed angry customer is lost.
Of the 51 errors, 16 are confident errors and 20 more have mixed wording, although only 13% of all validation reviews have mixed wording. Read two examples of the three largest groups.
def show(rows: pd.DataFrame) -> None: for _, row in rows.iterrows(): label = "negative" if row["true"] else "positive" print(f"label {label} (rating {row['rating']}),", f"P(negative) = {row['p_neg']:.2f}") print(textwrap.indent(textwrap.fill(row["text"], width=86), " "))
for cause in ["confident (P > 0.9 wrong way)", "mixed wording", "other"]: print(f"-- {cause}") show(errors[errors["cause"] == cause].nlargest(2, "margin"))-- confident (P > 0.9 wrong way)label negative (rating 1), P(negative) = 0.01 this is my second one. well made with great attention to detail. great value for the money. sturdy and built to last. would buy again. love it!!!label positive (rating 5), P(negative) = 0.98 the battery won't hold a charge anymore. the tracker broke on the second use. the material quality feels so cheap. avoid.-- mixed wordinglabel negative (rating 2), P(negative) = 0.13 shipping was a nightmare. but great customer service when i had a question.label positive (rating 4), P(negative) = 0.86 ordered this as a gift. the battery life easily lasts 2 hours. but way too expensive, not worth the price.-- otherlabel positive (rating 5), P(negative) = 0.90 bought this for my office. hard to use, nothing about the setup is intuitive. the price point is way too high. very disappointed.label positive (rating 5), P(negative) = 0.86 the material quality feels flimsy.- Confident errors: a 1-star review full of praise and a 5-star review that says “avoid”. The text and the stars disagree: these are the mis-clicked ratings that the data dictionary describes. The model reads them correctly; the labels are wrong.
- Mixed wording: one good and one bad sentence. The model must guess which one decided the rating, and the customer’s own weighting is not in the text.
- Other: both examples are clear complaints with 5 stars, just below the 0.9 cut. They look like mis-clicks too.
So the label, not the model, explains most of the errors we read. The weights show what the model learned. With class 1 = negative, a positive weight pushes toward negative. Each weight is printed next to its document frequency: the number of training reviews that contain the term.
tfidf, logreg = baseline.named_steps["tfidf"], baseline.named_steps["logreg"]weights = pd.Series(logreg.coef_[0], index=tfidf.get_feature_names_out())doc_freq = pd.Series( (tfidf.transform(X_train) > 0).sum(axis=0).A1, index=weights.index)print(f"{len(weights):,} features")for title, terms in [("Toward negative", weights.nlargest(8)), ("Toward positive", weights.nsmallest(8))]: print(title) for term, w in terms.items(): print(f" {term:18} {w:+.2f} in {doc_freq[term]:3} training reviews")354 featuresToward negative not +5.47 in 200 training reviews avoid +4.04 in 53 training reviews never +3.43 in 68 training reviews photos +3.23 in 14 training reviews slow +3.15 in 17 training reviews broke +2.99 in 101 training reviews poor +2.83 in 47 training reviews way +2.69 in 57 training reviewsToward positive premium -3.79 in 67 training reviews love -3.64 in 131 training reviews great -2.95 in 245 training reviews quickly -2.50 in 49 training reviews holds -2.32 in 72 training reviews amazing -2.12 in 17 training reviews definitely -2.06 in 115 training reviews friends -2.06 in 115 training reviewsThe model has only 354 unigram features. Most strong terms are frequent and plausible: not, avoid, never, broke against premium, love, great. Three rest on fewer than 20 reviews (photos, slow, amazing), so read them with care. way comes from “way too high”. An agent who reads this list can see why the model decided. Keep that in mind for Milestone 7.
What the errors say: a larger model cannot fix wrong labels (the confident group, and probably the “other” group). It might help with mixed wording, the largest group, but only if it can weigh one sentence against another.
Reference solution — Milestone 5: Train and tune a PyTorch model
The network uses the same tokens as the baseline: the tuned vectorizer’s analyzer (lowercasing and tokenizing) and its vocabulary of 354 terms, learned on the training texts only. So the comparison tests the model, not the preprocessing.
torch.set_num_threads(1) makes PyTorch use one CPU thread. With several threads, PyTorch splits large sums into parts and adds the parts in an order that depends on the thread count. Float addition is not exactly associative, so the last digits can change between machines with different core counts. One thread gives the same sums in the same order everywhere. For a model this small, one thread is not slower (module 42).
import copy
import torchfrom torch import nn
torch.set_num_threads(1) # one thread: the same sums in the same order everywheretorch.manual_seed(42)
analyzer = tfidf.build_analyzer() # the baseline's tokens (and n-grams, if any)vocab = tfidf.vocabulary_ # term -> id, learned on the training texts only
def encode(texts: list[str]) -> tuple[torch.Tensor, torch.Tensor]: """Turn texts into one flat tensor of term ids plus the start of each text.""" ids: list[int] = [] offsets: list[int] = [] for text in texts: offsets.append(len(ids)) ids.extend(vocab[term] for term in analyzer(text) if term in vocab) return torch.tensor(ids, dtype=torch.long), torch.tensor(offsets, dtype=torch.long)
ids, offsets = encode(["battery died fast", "great value"])print(ids.tolist(), offsets.tolist())print([term for term in analyzer("battery died fast") if term in vocab])[31, 76, 101, 123, 325] [0, 3]['battery', 'died', 'fast']The two texts become one flat list of 5 term ids. offsets says where each text starts: the first at position 0, the second at position 3. Reviews have different lengths, and this format needs no padding (filler ids that make all rows equally long). dtype=torch.long matters for a text with no known term: its list is empty, and an empty torch.tensor([]) would be a float tensor, which EmbeddingBag rejects.
nn.EmbeddingBag is a table with one learned vector (an embedding) per vocabulary term. For each review it looks up the vectors of the review’s terms and averages them, in one fast call. A head then turns the average into one logit. Without a hidden layer this is the design of the fastText classifier. With hidden > 0, the head gets a hidden layer with ReLU and dropout, so it can learn interactions between terms.
class BagModel(nn.Module): """Average the embeddings of a review's terms, then score the average."""
def __init__(self, n_terms: int, dim: int = 32, hidden: int = 0) -> None: super().__init__() self.embed = nn.EmbeddingBag(n_terms, dim, mode="mean") if hidden: self.head = nn.Sequential( nn.Linear(dim, hidden), nn.ReLU(), nn.Dropout(0.2), nn.Linear(hidden, 1) ) else: self.head = nn.Linear(dim, 1)
def forward(self, ids: torch.Tensor, offsets: torch.Tensor) -> torch.Tensor: return self.head(self.embed(ids, offsets)).squeeze(1) # one logit per review
for hidden in [0, 32]: net = BagModel(len(vocab), dim=64, hidden=hidden) print(f"hidden={hidden:2}: {sum(p.numel() for p in net.parameters()):,} parameters")hidden= 0: 22,721 parametershidden=32: 24,769 parametersWith 64 dimensions, the table alone has 354 × 64 = 22,656 weights. The logistic regression has 355 parameters.
The training function follows the loop of module 42:
pos_weight= (share of positives) / (share of negatives). It plays the role ofclass_weight="balanced", so both models trade false alarms for missed negatives in the same way.- A seeded
torch.Generatorfixes the shuffle order of the mini-batches. - After each epoch, the function computes the validation loss in eval mode. It keeps a deep copy of the best weights and stops after
patience=3epochs without improvement. - At the end it restores the best weights, not the last ones.
def train_bag( seed: int, dim: int = 32, hidden: int = 0, lr: float = 0.01, batch_size: int = 32, max_epochs: int = 20, patience: int = 3,) -> tuple[BagModel, list[float], list[float], int]: """Train on X_train with early stopping on the validation loss.""" torch.manual_seed(seed) gen = torch.Generator().manual_seed(seed) # the shuffle order net = BagModel(len(vocab), dim, hidden) optimizer = torch.optim.Adam(net.parameters(), lr=lr) pos_weight = torch.tensor((1 - y_train.mean()) / y_train.mean()) loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight) texts = X_train.tolist() targets = torch.tensor(y_train.to_numpy(), dtype=torch.float32) val_ids, val_off = encode(X_val.tolist()) val_y = torch.tensor(y_val.to_numpy(), dtype=torch.float32) best_loss, best_state, best_epoch, bad = float("inf"), {}, 0, 0 train_hist, val_hist = [], [] for epoch in range(1, max_epochs + 1): net.train() total = 0.0 for batch in torch.randperm(len(texts), generator=gen).split(batch_size): b_ids, b_off = encode([texts[i] for i in batch.tolist()]) optimizer.zero_grad() loss = loss_fn(net(b_ids, b_off), targets[batch]) loss.backward() optimizer.step() total += loss.item() * len(batch) net.eval() with torch.no_grad(): val_loss = loss_fn(net(val_ids, val_off), val_y).item() train_hist.append(total / len(texts)) val_hist.append(val_loss) if val_loss < best_loss: best_loss, best_epoch, bad = val_loss, epoch, 0 best_state = copy.deepcopy(net.state_dict()) else: bad += 1 if bad == patience: break net.load_state_dict(best_state) return net, train_hist, val_hist, best_epoch
def predict_neg(net: BagModel, texts: pd.Series) -> np.ndarray: """P(negative) for each text, in eval mode without gradients.""" net.eval() with torch.no_grad(): return torch.sigmoid(net(*encode(texts.tolist()))).numpy()The baseline had a grid of 20 settings. The network gets a grid of 8 on the validation set: with or without a hidden layer, embedding size 16 or 64, learning rate 0.003 or 0.01. It is ranked by validation F1, the metric that chose the baseline.
rows = []for hidden in [0, 32]: for dim in [16, 64]: for lr in [0.003, 0.01]: net, _, hist, best = train_bag(seed=42, dim=dim, hidden=hidden, lr=lr) p = predict_neg(net, X_val) rows.append({"hidden": hidden, "dim": dim, "lr": lr, "best epoch": best, "val loss": min(hist), "val F1": f1_score(y_val, p > 0.5), "val AUC": roc_auc_score(y_val, p)})tuning = pd.DataFrame(rows).sort_values("val F1", ascending=False)print(tuning.round(3).to_string(index=False))best_cfg = tuning.iloc[0][["dim", "hidden", "lr"]].to_dict()best_cfg = {"dim": int(best_cfg["dim"]), "hidden": int(best_cfg["hidden"]), "lr": float(best_cfg["lr"])}print("chosen:", best_cfg) hidden dim lr best epoch val loss val F1 val AUC 0 64 0.003 9 0.498 0.809 0.928 32 64 0.003 4 0.485 0.806 0.928 0 16 0.010 6 0.503 0.803 0.931 0 16 0.003 17 0.503 0.800 0.929 32 16 0.003 8 0.491 0.799 0.929 0 64 0.010 4 0.501 0.799 0.929 32 16 0.010 4 0.488 0.794 0.931 32 64 0.010 2 0.514 0.791 0.922chosen: {'dim': 64, 'hidden': 0, 'lr': 0.003}All 8 settings land between 0.791 and 0.809 validation F1, and between 0.922 and 0.931 ROC-AUC. Three of the four hidden-layer settings give the lowest validation losses (0.485 to 0.491), but no better F1 or ROC-AUC. The chosen setting is the linear head with 64 dimensions and a learning rate of 0.003. Train it again and plot its loss curves.
bag, train_hist, val_hist, best_epoch = train_bag(seed=42, **best_cfg)epochs = range(1, len(val_hist) + 1)plt.figure(figsize=(6, 3.5))plt.plot(epochs, train_hist, marker="o", label="train")plt.plot(epochs, val_hist, marker="o", label="validation")plt.axvline(best_epoch, color="gray", linestyle="--", label="best epoch")plt.xlabel("epoch")plt.ylabel("weighted BCE loss")plt.title("EmbeddingBag model: early stopping")plt.legend()plt.tight_layout()plt.show()print(f"ran {len(val_hist)} epochs, best epoch {best_epoch}, " f"best validation loss {min(val_hist):.3f}")ran 12 epochs, best epoch 9, best validation loss 0.498
The validation loss flattens after epoch 5 and is lowest at epoch 9. Three epochs without improvement end the run after epoch 12. The training loss keeps falling, so the gap between the curves grows: the model starts to fit the training reviews more closely than new ones.
The chosen network has no nonlinearity: it averages vectors and applies one linear layer. The average of linear scores equals the linear score of the average. So each term really has one score (its vector times the output weights, plus the bias), and a review’s logit is the mean of its terms’ scores. The next block checks this on the validation texts. (An empty text is the one exception: the network gives it the bias, the lookup gives 0.)
with torch.no_grad(): term_scores = bag.head(bag.embed.weight).squeeze(1) # one score per term lookup = nn.EmbeddingBag.from_pretrained(term_scores[:, None], mode="mean") val_ids, val_off = encode(X_val.tolist()) same = torch.allclose( lookup(val_ids, val_off).squeeze(1), bag(val_ids, val_off), atol=1e-5 )print(f"logit = mean of {len(term_scores):,} per-term scores: {same}")term_score = pd.Series(term_scores.numpy(), index=weights.index)print(f"correlation with the baseline weights: {term_score.corr(weights):.2f}")logit = mean of 354 per-term scores: Truecorrelation with the baseline weights: 0.87The 22,721 parameters collapse into 354 term scores. The chosen network is a linear classifier on the averaged bag of words, the same family as the baseline. It differs in how each term is weighted (a plain average instead of TF-IDF) and how it is regularized (early stopping instead of an L2 penalty). Its term scores correlate 0.87 with the baseline weights. So the final comparison is linear against linear. The nonlinear version was in the grid and did not win on validation.
Last, average 3 seeds. One seed can be lucky or unlucky. The average of the probabilities of 3 networks is more stable. This choice is made now, before the test read.
seeds = [42, 1, 2]nets = [bag] + [train_bag(seed=s, **best_cfg)[0] for s in seeds[1:]]p_val_seeds = [predict_neg(net, X_val) for net in nets]for seed, p in zip(seeds, p_val_seeds): print(f"seed {seed:2}: validation F1 {f1_score(y_val, p > 0.5):.3f}")p_val_bag = np.mean(p_val_seeds, axis=0) # the network = average of 3 seedsprint(f"3-seed average: validation F1 {f1_score(y_val, p_val_bag > 0.5):.3f}")seed 42: validation F1 0.809seed 1: validation F1 0.807seed 2: validation F1 0.8003-seed average: validation F1 0.804The seeds differ by up to 0.009 in validation F1. That is the size of the noise from training alone.
Reference solution — Milestone 6: Choose on validation, then read the test set once
The decision rule, fixed before the test read: ship the network only if its validation F1 beats the baseline by more than the seed spread. Otherwise ship the simpler model. The validation score of the network is slightly optimistic, because the validation set also chose its stopping epoch and its setting. The rule is still a fair test: an optimistic score that cannot beat the baseline is a clear answer.
val_scores = pd.DataFrame({ name: {"accuracy": accuracy_score(y_val, p > 0.5), "F1 (negative)": f1_score(y_val, p > 0.5), "ROC-AUC": roc_auc_score(y_val, p)} for name, p in [("logistic regression", p_val_lr), ("network", p_val_bag)]}).Tprint(val_scores.to_string(float_format="{:.3f}".format))seed_spread = np.ptp([f1_score(y_val, p > 0.5) for p in p_val_seeds])gain = val_scores.loc["network", "F1 (negative)"] - val_scores.loc[ "logistic regression", "F1 (negative)"]print(f"network F1 gain {gain:+.3f}, seed spread {seed_spread:.3f}")family = "network" if gain > seed_spread else "logistic regression"print("chosen model family:", family) accuracy F1 (negative) ROC-AUClogistic regression 0.904 0.810 0.929network 0.898 0.804 0.930network F1 gain -0.006, seed spread 0.009chosen model family: logistic regressionOn validation the two models tie: the network is 0.006 lower in F1 and 0.001 higher in ROC-AUC. The rule picks logistic regression. With the 3-class decision from Milestone 3, the shipped model is the tuned TF-IDF + logistic regression pipeline, trained with three classes. Refit it on all 2,400 training and validation reviews now, before the test read.
shipped = clone(baseline).fit(dev["clean"], dev["sentiment"]) # 3 classesprint(f"shipped model: {len(dev):,} reviews, classes {shipped.classes_.tolist()}")shipped model: 2,400 reviews, classes ['negative', 'neutral', 'positive']Everything is frozen. The next block is the only one that touches the test texts. It stores the predictions, and every later block reuses them.
# The only block that reads the test set.p_test = { "logistic regression": baseline.predict_proba(X_test)[:, 1], "network": np.mean([predict_neg(net, X_test) for net in nets], axis=0),}shipped_test = shipped.predict(test["clean"])
scores = pd.DataFrame({ name: {"accuracy": accuracy_score(y_test, p > 0.5), "F1 (negative)": f1_score(y_test, p > 0.5), "ROC-AUC": roc_auc_score(y_test, p)} for name, p in p_test.items()}).Tprint(scores.to_string(float_format="{:.3f}".format)) accuracy F1 (negative) ROC-AUClogistic regression 0.934 0.857 0.960network 0.934 0.859 0.960On the 532 positive and negative test reviews, the two binary models tie: same accuracy (0.934), same ROC-AUC (0.960), and F1 0.857 against 0.859. Both scores are higher than on validation (F1 0.810 and 0.804). Neither model saw the test set, so the jump is most likely test-set noise: 532 reviews is a small sample, and this test set happens to be easier.
A paired bootstrap shows how large that noise is. It resamples the test reviews with replacement 2,000 times, scores both models on each resample and records the difference. Pairing matters: both models are judged on the same reviews each time, so easy and hard reviews cancel out.
rng = np.random.default_rng(42)truth = y_test.to_numpy()p_lr, p_bag = p_test["logistic regression"], p_test["network"]diffs = {"accuracy": [], "F1 (negative)": [], "ROC-AUC": []}
def f1_np(t: np.ndarray, pred: np.ndarray) -> float: tp = np.sum(pred & (t == 1)) return 2 * tp / (np.sum(pred) + np.sum(t == 1))
for _ in range(2000): i = rng.integers(0, len(truth), len(truth)) t, a, b = truth[i], p_lr[i], p_bag[i] diffs["accuracy"].append(np.mean((b > 0.5) == t) - np.mean((a > 0.5) == t)) diffs["F1 (negative)"].append(f1_np(t, b > 0.5) - f1_np(t, a > 0.5)) diffs["ROC-AUC"].append(roc_auc_score(t, b) - roc_auc_score(t, a))print("network minus logistic regression, 95% bootstrap interval (test sampling):")for metric, values in diffs.items(): low, high = np.percentile(values, [2.5, 97.5]) print(f" {metric:14} {np.mean(values):+.3f} [{low:+.3f}, {high:+.3f}]")network minus logistic regression, 95% bootstrap interval (test sampling): accuracy -0.000 [-0.008, +0.008] F1 (negative) +0.002 [-0.013, +0.019] ROC-AUC +0.000 [-0.005, +0.005]f1_np computes F1 with NumPy as 2·TP / (predicted positives + actual positives), the same formula as f1_score but much faster inside a loop. Every interval contains zero. The test set confirms the validation decision: no detectable difference. Note what the interval covers: only the choice of test reviews. It does not cover training randomness (the seed noise of Milestone 5) or a different split. Those would make the intervals wider, not narrower.
from sklearn.metrics import ConfusionMatrixDisplay
fig, axes = plt.subplots(1, 3, figsize=(13, 4))for ax, (name, p) in zip(axes, p_test.items()): ConfusionMatrixDisplay.from_predictions( y_test, (p > 0.5).astype(int), display_labels=["positive", "negative"], cmap="Blues", colorbar=False, ax=ax, ) ax.set_title(f"{name} (positive vs negative)")ConfusionMatrixDisplay.from_predictions( test["sentiment"], shipped_test, cmap="Blues", colorbar=False, ax=axes[2])axes[2].set_title("shipped 3-class model (all texts)")plt.tight_layout()plt.show()for name, p in p_test.items(): tn, fp, fn, tp = confusion_matrix(y_test, p > 0.5).ravel() print(f"{name:19} TN {tn}, FP {fp}, FN {fn}, TP {tp}")logistic regression TN 392, FP 21, FN 14, TP 105network TN 390, FP 23, FN 12, TP 107
The binary models differ by two reviews per cell: the network catches 2 more negative reviews and raises 2 more false alarms. The right panel shows the shipped model on all 600 test texts, neutral ones included.
print(classification_report(test["sentiment"], shipped_test, digits=3))flagged = shipped_test == "negative"precision, recall, f1, _ = precision_recall_fscore_support( test["sentiment"] == "negative", flagged, average="binary")print(f"negative vs rest, all {len(test)} test texts: precision {precision:.3f}, " f"recall {recall:.3f}, F1 {f1:.3f}") precision recall f1-score support
negative 0.785 0.891 0.835 119 neutral 0.716 0.853 0.779 68 positive 0.977 0.908 0.941 413
accuracy 0.898 600 macro avg 0.826 0.884 0.851 600weighted avg 0.909 0.898 0.902 600
negative vs rest, all 600 test texts: precision 0.785, recall 0.891, F1 0.835On the full test stream, the shipped model finds 89.1% of the negative texts, and 78.5% of the texts it sends to support are really negative. It finds 85.3% of the neutral texts for the second queue. Of the 135 texts it calls negative, 9 are neutral (right panel), so lukewarm texts rarely reach the main queue.
Last, the cost. Training times depend on the machine, so the block prints a comparison next to them.
import time
start = time.perf_counter()clone(baseline).fit(X_train, y_train)lr_seconds = time.perf_counter() - startstart = time.perf_counter()train_bag(seed=42, **best_cfg)bag_seconds = time.perf_counter() - startprint(f"logistic regression fit: {lr_seconds:.2f} s, {weights.size + 1:,} parameters")n_bag = 3 * sum(p.numel() for p in bag.parameters())print(f"network, one seed: {bag_seconds:.2f} s, {n_bag:,} parameters (3 seeds)")print(f"logistic regression is faster: {lr_seconds < bag_seconds}")logistic regression fit: 0.01 s, 355 parametersnetwork, one seed: 0.19 s, 68,163 parameters (3 seeds)logistic regression is faster: TrueBoth train in well under a second on this data. The baseline is faster, and the 3-seed network has 68,163 parameters against 355. The larger cost is in deployment. The baseline is one scikit-learn pipeline in one file. The network needs PyTorch, the custom encode function, the vocabulary and three weight files, and all of them must match at prediction time.
Reference solution — Milestone 7: Recommend a model
Recommendation to the support lead: ship the TF-IDF + logistic regression pipeline with three classes (negative, neutral, positive).
- The choice was made on validation and confirmed on test. On validation the network did not beat the baseline by more than its own seed noise (F1 gain −0.006, seed spread 0.009), so the rule picked the simpler model. On the test set the two binary models tie on every metric, and every bootstrap interval contains zero.
- It is simpler and cheaper. 355 parameters instead of 68,163, faster training, one pipeline file and no PyTorch dependency at prediction time.
- It explains itself. Its weights (Milestone 4) tell an agent why a text was flagged:
not,avoid,never,broke. The tuned network turned out to be a linear model on the same words anyway (Milestone 5), and the nonlinear variant did not win on validation. - It handles lukewarm texts on purpose. The third class keeps neutral texts out of the support queue: in CV the binary design flagged 62% of them, the 3-class design 5%. On the test stream the shipped model has negative precision 0.785 and recall 0.891.
- The main error source is the labels. In Milestone 4, the confident errors and the “other” errors we read were complaints with 5 stars or praise with 1 star. A cleaner label set would help more than a bigger model. Stretch goal 5 measures this.
Routing: “negative” goes to the support queue, “neutral” to a weekly second queue, “positive” nowhere. When would the network be worth testing again? With much more data, with longer texts where sentence order matters, or with pretrained embeddings that know synonyms the training set never showed.
Here is the shipped model on three new texts. New text goes through clean_text first, because the model was trained on cleaned text.
new = pd.Series([ "Battery died after two days. Never again!!!", "It's okay. Not bad, not great.", "Arrived fast and works great. Would buy again.",]).map(clean_text)print(pd.DataFrame(shipped.predict_proba(new), columns=shipped.classes_).round(3)) negative neutral positive0 0.632 0.01 0.3581 0.000 1.00 0.0002 0.011 0.00 0.989The complaint goes to the support queue (0.632 negative), the lukewarm text to the second queue and the happy text nowhere. The complaint is the least certain of the three: it still gets 0.358 for positive.
Reference solution — Milestone 8: Measure the complaint aspects
Module 41 fitted NMF topics on reviews and listed their top words. This milestone starts there and goes further: it checks what each topic holds, counts every aspect a review mentions, and measures severity and change over time. Topic modeling describes the data and makes no scored predictions, so it can use all 596 negative reviews.
The TF-IDF matrix removes English stop words, keeps terms seen in at least 5 reviews and drops terms that appear in more than half of them. Bigrams keep phrases such as customer service together. 9 topics is a choice made by reading them; try 7 and 8 yourself.
from sklearn.decomposition import NMF
negative = reviews[reviews["sentiment"] == "negative"].copy()aspect_vec = TfidfVectorizer( stop_words="english", ngram_range=(1, 2), min_df=5, max_df=0.5)X_neg = aspect_vec.fit_transform(negative["clean"])nmf = NMF(n_components=9, init="nndsvda", random_state=42, max_iter=1000)W = nmf.fit_transform(X_neg)terms = aspect_vec.get_feature_names_out()for k, comp in enumerate(nmf.components_): top = [terms[i] for i in comp.argsort()[::-1][:5]] best = negative["clean"].iloc[W[:, k].argmax()] print(f"topic {k}: {', '.join(top)}") print(f" e.g. {textwrap.shorten(best, width=80)}")topic 0: price, point, price point, way, high e.g. the price point is way too high.topic 1: broke days, days, cheaply, cheaply broke, broke e.g. cheaply made, it broke within days.topic 2: service, customer service, customer, avoid seller, service avoid e.g. terrible customer service, avoid this seller. the price is fair.topic 3: month, durability terrible, broke month, terrible broke, durability e.g. overpriced for what it is. durability is terrible, it broke after a month.topic 4: cheap quality, photos, like, like photos, looks like e.g. cheap quality, looks nothing like the photos.topic 5: battery, charge, forever charge, takes forever, takes e.g. the battery takes forever to charge.topic 6: poor, arrived, poor quality, quality, arrived scratched e.g. the jacket arrived scratched, poor quality control.topic 7: weeks, waiting, refund weeks, waiting refund, refund e.g. still waiting for my refund after three weeks.topic 8: material, feels, material quality, quality feels, material feels e.g. bought it during the sale. the material quality feels flimsy. never again.The most typical review (the highest weight) names most topics at once. Topics 1 and 3 are both about breaking, but the timing differs: “within days” versus “after a month”. Topics 5 and 6 need a closer look before you name them: a typical review shows the center of a topic, not its spread.
def share_with(pattern: str, topic: int) -> float: rows = negative["clean"][W.argmax(axis=1) == topic] return rows.str.contains(pattern).mean()
print(f"topic 5: battery or charge {share_with('batter|charg', 5):.0%}, " f"setup or ease of use {share_with('setup|set up|easy to use|confusing', 5):.0%}")print(f"topic 6: arrival or damage {share_with('arriv|scratch|damag', 6):.0%}, " f"'poor quality' {share_with('poor quality', 6):.0%}")books = negative.loc[negative["category"] == "Books", "clean"]books_arrival = books.str.contains("arriv|scratch|damag").mean()print(f"Books negatives: arrival or damage {books_arrival:.0%}, " f"'poor quality' {books.str.contains('poor quality').mean():.0%}")topic 5: battery or charge 58%, setup or ease of use 44%topic 6: arrival or damage 43%, 'poor quality' 25%Books negatives: arrival or damage 28%, 'poor quality' 10%Topic 5 is two complaints in one: 58% of its reviews mention the battery or charging, 44% mention setup or ease of use. Its name must say both. Topic 6 is a general quality topic: 43% mention arrival or damage, the rest do not. And only 28% of all negative Books reviews mention arrival or damage. So the data does not support “Books have a shipping problem”; a packaging fix would address at most about a quarter of their complaints.
Now name the topics and count every aspect a review mentions. Reviews have one to three aspect sentences, so the top topic alone undercounts. A review counts for each topic whose weight is at least half of its strongest one.
ASPECTS = [ "price", "broke in days", "service", "broke in a month", "unlike photos", "battery, ease of use", "poor quality, damaged", "refund delay", "flimsy material",]row_max = W.max(axis=1, keepdims=True)mentions = pd.DataFrame((W >= 0.5 * row_max) & (W > 0), columns=ASPECTS, index=negative.index)n_aspects = mentions.sum(axis=1)print(f"reviews with 2+ aspects: {(n_aspects >= 2).mean():.0%}; " f"with none: {(n_aspects == 0).sum()}")one_star = negative["rating"] == 1year = negative["review_date"].str[:4]summary = pd.DataFrame({ "reviews": mentions.sum(), "share": mentions.mean(), "1-star share": [one_star[mentions[a]].mean() for a in ASPECTS], "2023": [mentions.loc[year == "2023", a].mean() for a in ASPECTS], "2024": [mentions.loc[year == "2024", a].mean() for a in ASPECTS],}).sort_values("reviews", ascending=False)print(f"1-star share of all negative reviews: {one_star.mean():.2f}")print(summary.round(2).to_string())reviews with 2+ aspects: 31%; with none: 01-star share of all negative reviews: 0.55 reviews share 1-star share 2023 2024poor quality, damaged 163 0.27 0.55 0.25 0.29battery, ease of use 143 0.24 0.54 0.24 0.24flimsy material 121 0.20 0.56 0.23 0.18refund delay 118 0.20 0.56 0.21 0.19price 91 0.15 0.54 0.17 0.14service 72 0.12 0.56 0.14 0.11broke in days 58 0.10 0.60 0.09 0.11broke in a month 51 0.09 0.67 0.08 0.09unlike photos 24 0.04 0.54 0.04 0.0431% of the negative reviews count for two or more aspects, so the shares add up to more than 1. Three findings:
- Frequency: poor quality or damage (27% of negative reviews), battery or ease of use (24%), flimsy material and refund delays (20% each) lead.
- Severity: products that broke draw the angriest reviews. 67% of the “broke in a month” reviews and 60% of the “broke in days” reviews have 1 star, against 55% of all negative reviews. These groups are small (51 and 58 reviews), so treat the gap as a lead to check, not a proven effect.
- Trend: no aspect moves by more than 5 points between 2023 and 2024. Flimsy material falls from 0.23 to 0.18 and poor quality rises from 0.25 to 0.29; with groups of this size, these moves are within noise.
by_category = mentions.groupby(negative["category"]).mean()for category, row in by_category.iterrows(): print(f"{category:12} top aspect {row.idxmax():22}", f"{row.max():.0%} of its negatives")
fig, ax = plt.subplots(figsize=(9, 4))im = ax.imshow(by_category.to_numpy(), cmap="Reds", vmin=0, vmax=0.7)ax.set_xticks(range(len(ASPECTS)), ASPECTS, rotation=35, ha="right")ax.set_yticks(range(len(by_category)), by_category.index)for r in range(by_category.shape[0]): for c in range(by_category.shape[1]): ax.text(c, r, f"{by_category.iat[r, c]:.0%}", ha="center", va="center", fontsize=8)fig.colorbar(im, ax=ax, label="share of the category's negative reviews")ax.set_title("Complaint aspects by category (negative reviews)")plt.tight_layout()plt.show()Beauty top aspect poor quality, damaged 29% of its negativesBooks top aspect poor quality, damaged 46% of its negativesClothing top aspect refund delay 29% of its negativesElectronics top aspect battery, ease of use 60% of its negativesHome top aspect battery, ease of use 27% of its negativesSports top aspect battery, ease of use 30% of its negatives
What to tell the product teams:
- Electronics: 60% of its negative reviews mention battery or ease of use. The topic holds two problems (battery 58%, setup 44% of the topic’s reviews), so the team needs two fixes, not one.
- Books: 46% fall into the general quality topic, but only 28% of Books complaints mention arrival or damage. Read a sample of the rest before choosing between a packaging fix and a supplier change.
- Clothing: refund delay is the top aspect (29%). The returns process is the first thing to look at.
Stretch goals
Section titled “Stretch goals”- Leakage on purpose. Repeat Milestones 2–3 with a plain
train_test_splitandStratifiedKFold. How many test texts appear in train, and how much do the CV and test scores change? - A stronger nonlinear model. Feed bigrams to the network, or give it pretrained word vectors. Does the hidden layer win on validation then?
- Choose the thresholds. Pick the negative threshold of the shipped model on the validation set for a target recall of 0.95, and report the false alarms it costs.
- Character n-grams. Add
analyzer="char_wb"features to the baseline and check whether they make the typo dictionary unnecessary. - Clean the labels. Drop the training reviews whose out-of-fold probability contradicts their stars most strongly (for example, the top 5%), retrain, and measure the change on the validation set. Does label cleaning beat a bigger model?
Next steps
Section titled “Next steps”- Capstone 8 — Deployment serves a model behind an API with tests. The shipped pipeline of Milestone 6 is a good candidate to serve the same way.
- Revisit module 43 to explain single predictions to the support agents.
- Revisit module 44 to monitor the share of texts in each queue after launch.