Skip to content

41. NLP fundamentals — Mini-project

The product team of an online shop reads reviews by hand. They want a short report, generated by a script, that answers four questions:

  1. How reliable is an automatic sentiment model on our reviews?
  2. What do unhappy customers complain about, and how often?
  3. Which products have the most negative reviews, and what is the main complaint for each?
  4. Which positive ratings come with a text that reads like a complaint? (Someone should check them: they are mis-clicks or hidden problems.)

Write a script, review_report.py, that prints this report from data/reviews.csv. The project uses every part of module 41: cleaning, TF-IDF, n-grams, a classification pipeline with cross-validation, out-of-fold probabilities and topic modeling.

data/reviews.csv has 3,000 product reviews (see the data dictionary). The columns you need:

Column Use
text the raw review text: HTML entities, upper case, odd whitespace and typos
product the product name, for the per-product table
rating stars from 1 to 5
sentiment positive (4–5 stars), negative (1–2) or neutral (3)

Read the file with keep_default_na=False. Train the sentiment model on the 2,662 positive and negative reviews. The 338 neutral reviews count in the per-product totals.

Your script must:

  1. Clean the texts with html.unescape, lowercasing and whitespace collapsing, in one function.
  2. Build the sentiment model as one Pipeline: TfidfVectorizer(ngram_range=(1, 2), min_df=2) and LogisticRegression(C=10, max_iter=1000).
  3. Report its 5-fold cross-validated accuracy and macro F1 next to a DummyClassifier baseline, with the same folds.
  4. Fit NMF with 8 topics on the TF-IDF matrix of the negative reviews only (English stop words, min_df=3, max_df=0.5, init="nndsvda", random_state=42). Print each topic’s top 5 words, a name you chose after reading them, and its number of reviews.
  5. For each product, compute the number of reviews, the mean rating, the share of negative reviews and the most frequent complaint topic among its negative reviews. Print the 5 products with the highest negative share.
  6. Get out-of-fold probabilities (cross_val_predict) for the binary reviews. Flag the reviews rated 4 or 5 whose probability of “positive” is below 0.1. Print their number and the 3 most extreme ones.
  7. Organize the code in small functions with type hints and docstrings, and run it from a main() function.
  8. End with assert checks: the model beats the baseline, every negative review has a topic, and the product table has 5 rows.

The report starts like this (your topic names can differ):

Expected report (first lines)
Review insights report: 3,000 reviews, 30 products
==================================================
1. Sentiment model (5-fold CV, 2,662 labeled reviews)
model accuracy 0.909 macro F1 0.867
baseline accuracy 0.776 macro F1 0.437
  1. Load and clean. Write clean_text and load_reviews(path), which adds a clean column. Print one raw and one cleaned text to check.

  2. Build and evaluate the model. Write build_model() and evaluate(model, texts, labels). Use cross_validate with scoring=["accuracy", "f1_macro"] and cv=5 for both the model and DummyClassifier(strategy="most_frequent"). Macro F1 shows what the baseline hides: it never predicts the negative class.

  3. Find the complaint topics. Write complaint_topics(texts, n_topics=8). It returns the top words of each topic and the strongest topic of each review. Run it once, read the top words, then write your topic names in a constant list.

  4. Build the product table. Put the topic of each negative review in a column (neutral and positive reviews get none). Group by product. The most frequent complaint is the mode of the topic column within each group.

  5. Flag suspicious ratings. Use cross_val_predict(..., method="predict_proba"), so every review is scored by a model that did not train on it. Keep the reviews with rating 4 or 5 and a probability of “positive” below 0.1.

  6. Print the report. Use f-strings with fixed widths so the columns line up. Shorten long review texts to 70 characters.

  7. Add the checks and run the script end to end with python review_report.py.

A skeleton to start from:

review_report.py (starter)
import html
import re
import numpy as np
import pandas as pd
from sklearn.decomposition import NMF
from sklearn.dummy import DummyClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict, cross_validate
from sklearn.pipeline import Pipeline, make_pipeline
TOPIC_NAMES: list[str] = [] # TODO: fill in after reading the topics
def clean_text(text: str) -> str:
"""Decode HTML entities, lowercase and collapse whitespace."""
# TODO
def load_reviews(path: str) -> pd.DataFrame:
"""Read the reviews and add a cleaned text column."""
# TODO
def build_model() -> Pipeline:
"""Return the TF-IDF + logistic regression sentiment pipeline."""
# TODO
def evaluate(model: Pipeline, texts: pd.Series, labels: pd.Series) -> dict[str, float]:
"""Cross-validate the model and a majority baseline."""
# TODO
def complaint_topics(texts: pd.Series, n_topics: int = 8) -> tuple[list[str], np.ndarray]:
"""Return the top words per topic and the strongest topic per text."""
# TODO
def main() -> None:
# TODO: load, evaluate, topics, product table, flags, report, asserts
...
main()
Criterion Points Full points when
Cleaning 2 One function with html.unescape, lowercasing and whitespace collapsing; raw text kept
Pipeline 2 Vectorizer and model in one Pipeline; no vectorizer fitted outside it
Evaluation 3 5-fold CV accuracy and macro F1 for the model and the baseline, on the same folds
Topics 3 NMF on negative reviews only, top words printed, names that match the words, counts that add up
Product table 3 Correct counts, mean rating, negative share and main complaint; sorted; 5 rows
Suspicious ratings 2 Out-of-fold probabilities, rating 4–5 and probability below 0.1; examples shown
Code quality 2 Small functions with type hints and docstrings; main(); ruff-clean
Self-checks 1 The three required assert checks
Total 18 15 or more: you are ready for module 42
  1. Add the neutral reviews: train a three-class model and report per-class recall with and without class_weight="balanced".
  2. Track the complaints over time: count the negative reviews per topic and per quarter of review_date, and print the topic that grew most from 2023 to 2024.
  3. Replace the keyword-free topics with aspect-based sentiment (exercise M41-X02) for the worst product, and compare the two views.
  4. Add a “similar complaints” section: for the worst product, embed its negative reviews with LSA (TruncatedSVD on TF-IDF) and print, for its most negative review, the 3 most similar negative reviews of other products.
  5. Save the product table to output/product_report.csv and the flagged reviews to output/flagged_reviews.csv for the team.

Try the project yourself first. Then compare your script with this one. Your topic names and layout can differ; the numbers for the same settings must not.

Reference solution
review_report.py
import html
import re
import numpy as np
import pandas as pd
from sklearn.decomposition import NMF
from sklearn.dummy import DummyClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict, cross_validate
from sklearn.pipeline import Pipeline, make_pipeline
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
# Named after reading the top words and a few reviews of each topic.
TOPIC_NAMES = [
"poor quality, delivery",
"broke quickly",
"bad service",
"battery",
"high price",
"refund delays",
"cheap material",
"wrong size",
]
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()
def load_reviews(path: str) -> pd.DataFrame:
"""Read the reviews and add a cleaned text column."""
reviews = pd.read_csv(path, keep_default_na=False)
reviews["clean"] = reviews["text"].map(clean_text)
return reviews
def build_model() -> Pipeline:
"""Return the TF-IDF + logistic regression sentiment pipeline."""
return make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=2),
LogisticRegression(C=10, max_iter=1000),
)
def evaluate(model: Pipeline, texts: pd.Series, labels: pd.Series) -> dict[str, float]:
"""Cross-validate the model and a majority baseline on the same 5 folds."""
metrics = ["accuracy", "f1_macro"]
results = {}
baseline = DummyClassifier(strategy="most_frequent")
for name, estimator in [("model", model), ("baseline", baseline)]:
scores = cross_validate(estimator, texts, labels, cv=5, scoring=metrics)
for metric in metrics:
results[f"{name}_{metric}"] = scores[f"test_{metric}"].mean()
return results
def complaint_topics(
texts: pd.Series, n_topics: int = 8
) -> tuple[list[str], np.ndarray]:
"""Return the top words per topic and the strongest topic per text."""
vec = TfidfVectorizer(stop_words="english", min_df=3, max_df=0.5)
matrix = vec.fit_transform(texts)
nmf = NMF(n_components=n_topics, init="nndsvda", random_state=42, max_iter=1000)
doc_topics = nmf.fit_transform(matrix)
terms = vec.get_feature_names_out()
top_words = [" ".join(terms[np.argsort(row)[::-1][:5]]) for row in nmf.components_]
return top_words, doc_topics.argmax(axis=1)
def product_table(reviews: pd.DataFrame) -> pd.DataFrame:
"""Reviews, mean rating, negative share and main complaint per product."""
table = reviews.groupby("product").agg(
reviews=("rating", "size"),
rating=("rating", "mean"),
negative=("sentiment", lambda s: (s == "negative").mean()),
main_complaint=("topic", lambda s: s.dropna().mode().iloc[0]),
)
return table.sort_values(["negative", "reviews"], ascending=False, kind="stable")
def main() -> None:
reviews = load_reviews("data/reviews.csv")
binary = reviews[reviews["sentiment"] != "neutral"]
title = (
f"Review insights report: {len(reviews):,} reviews, "
f"{reviews['product'].nunique()} products"
)
print(title)
print("=" * len(title))
model = build_model()
scores = evaluate(model, binary["clean"], binary["sentiment"])
print(f"\n1. Sentiment model (5-fold CV, {len(binary):,} labeled reviews)")
for name in ["model", "baseline"]:
print(
f" {name:9} accuracy {scores[f'{name}_accuracy']:.3f}"
f" macro F1 {scores[f'{name}_f1_macro']:.3f}"
)
negative = reviews["sentiment"] == "negative"
top_words, topic_ids = complaint_topics(reviews.loc[negative, "clean"])
reviews.loc[negative, "topic"] = [TOPIC_NAMES[i] for i in topic_ids]
counts = np.bincount(topic_ids, minlength=len(TOPIC_NAMES))
print(f"\n2. Complaint topics ({negative.sum()} negative reviews)")
for name, words, count in zip(TOPIC_NAMES, top_words, counts, strict=True):
print(f" {name:22} {count:3} {words}")
worst = product_table(reviews).head(5)
print("\n3. Products with the highest share of negative reviews")
for product, row in worst.iterrows():
print(
f" {product:23} {row['reviews']:3} reviews rating {row['rating']:.2f}"
f" negative {row['negative']:.0%} main: {row['main_complaint']}"
)
proba = cross_val_predict(
model, binary["clean"], binary["sentiment"], cv=5, method="predict_proba"
)
flags = binary.assign(p_positive=proba[:, 1])
flags = flags[(flags["rating"] >= 4) & (flags["p_positive"] < 0.1)]
print(f"\n4. Ratings of 4-5 stars with a negative text: {len(flags)} reviews")
for _, row in flags.nsmallest(3, "p_positive").iterrows():
print(f" {row['review_id']} {row['rating']}* p={row['p_positive']:.3f}")
print(f" {row['clean'][:70]}")
assert scores["model_accuracy"] > scores["baseline_accuracy"] + 0.1
assert reviews.loc[negative, "topic"].notna().all()
assert len(worst) == 5
main()
Output
Review insights report: 3,000 reviews, 30 products
==================================================
1. Sentiment model (5-fold CV, 2,662 labeled reviews)
model accuracy 0.909 macro F1 0.867
baseline accuracy 0.776 macro F1 0.437
2. Complaint topics (596 negative reviews)
poor quality, delivery 71 quality arrived poor delivery money
broke quickly 47 days broke cheaply buy use
bad service 79 terrible customer avoid service seller
battery 98 battery charge forever takes setup
high price 106 price way high point justified
refund delays 57 weeks refund waiting using ve
cheap material 85 material feels cheap quality looks
wrong size 53 size small wrong large runs
3. Products with the highest share of negative reviews
Robot Vacuum 67 reviews rating 3.09 negative 36% main: battery
Slim Fit Jeans 131 reviews rating 3.34 negative 33% main: wrong size
Smartwatch Series 5 106 reviews rating 3.47 negative 30% main: battery
Statistics Made Simple 85 reviews rating 3.64 negative 26% main: cheap material
A Brief History of Maps 68 reviews rating 3.71 negative 25% main: refund delays
4. Ratings of 4-5 stars with a negative text: 25 reviews
R00510 5* p=0.018
setup was so confusing. the battery takes forever to charge. cheaply m
R00999 5* p=0.018
the quality is disappointing. avoid.
R00964 5* p=0.023
this is my second one. the mat broke on the second use. the delivery d

How it works:

  1. clean_text and load_reviews keep the raw text and add clean, so every later step works on the same cleaned texts.
  2. evaluate passes the same cv=5 to both estimators. With a classifier and string labels, cross_validate uses stratified folds with a fixed order, so both see the same splits. The baseline’s macro F1 of about 0.44 shows that it never predicts “negative”.
  3. complaint_topics fits its own vectorizer on the negative reviews only, with stop words removed: topics should be about content words. The topic names come from reading the printed top words, so they belong in a constant at the top of the script.
  4. reviews.loc[negative, "topic"] = ... creates the topic column. Rows that are not negative get a missing value, and s.dropna().mode() ignores them when it finds the main complaint of a product.
  5. The product table sorts by negative share, with the number of reviews as a tie-breaker, so the order is stable.
  6. cross_val_predict gives out-of-fold probabilities. A model that trained on a review would be too sure of its label and would hide the contradiction.
  7. The three asserts check the claims the report makes. A future change that breaks the model or the topic assignment fails loudly instead of printing a wrong report.