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:
- How reliable is an automatic sentiment model on our reviews?
- What do unhappy customers complain about, and how often?
- Which products have the most negative reviews, and what is the main complaint for each?
- 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.
Dataset
Section titled “Dataset”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.
Requirements
Section titled “Requirements”Your script must:
- Clean the texts with
html.unescape, lowercasing and whitespace collapsing, in one function. - Build the sentiment model as one
Pipeline:TfidfVectorizer(ngram_range=(1, 2), min_df=2)andLogisticRegression(C=10, max_iter=1000). - Report its 5-fold cross-validated accuracy and macro F1 next to a
DummyClassifierbaseline, with the same folds. - 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. - 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.
- 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. - Organize the code in small functions with type hints and docstrings, and run it from a
main()function. - End with
assertchecks: 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):
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.437Step plan
Section titled “Step plan”-
Load and clean. Write
clean_textandload_reviews(path), which adds acleancolumn. Print one raw and one cleaned text to check. -
Build and evaluate the model. Write
build_model()andevaluate(model, texts, labels). Usecross_validatewithscoring=["accuracy", "f1_macro"]andcv=5for both the model andDummyClassifier(strategy="most_frequent"). Macro F1 shows what the baseline hides: it never predicts the negative class. -
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. -
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
modeof the topic column within each group. -
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. -
Print the report. Use f-strings with fixed widths so the columns line up. Shorten long review texts to 70 characters.
-
Add the checks and run the script end to end with
python review_report.py.
A skeleton to start from:
import htmlimport re
import numpy as npimport pandas as pdfrom sklearn.decomposition import NMFfrom sklearn.dummy import DummyClassifierfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_predict, cross_validatefrom 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()Rubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Add the neutral reviews: train a three-class model and report per-class recall with and without
class_weight="balanced". - 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. - Replace the keyword-free topics with aspect-based sentiment (exercise M41-X02) for the worst product, and compare the two views.
- Add a “similar complaints” section: for the worst product, embed its negative reviews with LSA (
TruncatedSVDon TF-IDF) and print, for its most negative review, the 3 most similar negative reviews of other products. - Save the product table to
output/product_report.csvand the flagged reviews tooutput/flagged_reviews.csvfor the team.
Reference solution
Section titled “Reference solution”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
import htmlimport re
import numpy as npimport pandas as pdfrom sklearn.decomposition import NMFfrom sklearn.dummy import DummyClassifierfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import cross_val_predict, cross_validatefrom 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()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 dHow it works:
clean_textandload_reviewskeep the rawtextand addclean, so every later step works on the same cleaned texts.evaluatepasses the samecv=5to both estimators. With a classifier and string labels,cross_validateuses 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”.complaint_topicsfits 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.reviews.loc[negative, "topic"] = ...creates thetopiccolumn. Rows that are not negative get a missing value, ands.dropna().mode()ignores them when it finds the main complaint of a product.- The product table sorts by negative share, with the number of reviews as a tie-breaker, so the order is stable.
cross_val_predictgives out-of-fold probabilities. A model that trained on a review would be too sure of its label and would hide the contradiction.- 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.