Marketing teams collect more customer text than anyone can read: reviews, survey answers, support emails, social posts. Sentiment analysis sorts it automatically into positive and negative, so you can see what customers complain about and track whether it’s getting better. This lesson builds a working review classifier in Python and shows how to read what it learned.
Playing loads the video from YouTube. Watch on YouTube
The data: labeled reviews
Every classifier learns from examples. Here are twelve short product reviews, each labeled 1 for positive and 0 for negative. A real project starts from hundreds or thousands; your review platform’s star ratings are a convenient source of labels, with four and five stars counted as positive and one and two as negative.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
reviews = [
("Love this case, fits perfectly and feels solid", 1),
("Fast delivery and great customer service", 1),
("The charger works well and charges quickly", 1),
("Excellent quality for the price, would buy again", 1),
("Really happy with the purchase, highly recommend", 1),
("Great value and the color is exactly as shown", 1),
("Arrived broken and support never replied", 0),
("Stopped working after two days, waste of money", 0),
("Poor quality, the case cracked within a week", 0),
("Delivery was late and the box was damaged", 0),
("Cheap material and it does not fit my phone", 0),
("Very disappointed, asked for a refund", 0),
]
texts, labels = zip(*reviews)From words to numbers: TF-IDF
A model can’t read text, so we turn each review into numbers. TF-IDF gives every word a weight: high if the word appears in this review but rarely elsewhere, low for words that are everywhere, like “the”. With ngram_range=(1, 2) it also weighs pairs of words, so “never replied” counts as a phrase. Logistic regression then learns how much each word pushes a review towards positive or negative.
Worked example: train and score new reviews
model = make_pipeline(TfidfVectorizer(ngram_range=(1, 2)), LogisticRegression(C=10))
model.fit(texts, labels)
new = ["The case feels solid and great value",
"Charger stopped working and support never replied",
"Delivery was fast"]
for text, p in zip(new, model.predict_proba(new)[:, 1]):
print(f"{p:.2f} positive | {text}")0.74 positive | The case feels solid and great value
0.23 positive | Charger stopped working and support never replied
0.38 positive | Delivery was fastThe first two are right. The third is a useful failure: “Delivery was fast” is clearly positive, but the model leans negative. In our twelve reviews, “delivery” appears in one positive and one negative review, “was” only in negative ones, and “fast” in a positive review it hasn’t linked strongly enough. With so little data, the model learned an accident of the examples. More labeled reviews fix this; no amount of tuning does.
What did the model learn?
Logistic regression is easy to inspect: every word has a weight. Listing the strongest weights in each direction shows what drives the scores, and catches problems like the one above:
vec = model.named_steps["tfidfvectorizer"]
coef = model.named_steps["logisticregression"].coef_[0]
words = vec.get_feature_names_out()
order = coef.argsort()
print("Most negative words:", ", ".join(words[order[:4]]))
print("Most positive words:", ", ".join(words[order[-4:]][::-1]))Most negative words: was, asked for, disappointed, asked
Most positive words: great, service, customer service, great customer“Disappointed” is a sensible negative word; “was” is not, and its presence at the top confirms the problem we saw. This check takes one line and is worth doing on every text model before anyone acts on its scores.
A fair accuracy figure needs a test set of reviews the model didn’t learn from, just as in the housing lesson. With twelve examples there’s nothing to spare, which is one more reason the first job in a real project is collecting and labelling enough reviews.
Using sentiment in marketing
- Track the share of negative reviews per product or per month, and investigate when it moves.
- Read the most negative reviews first: they point to the fixes that matter most.
- Compare sentiment before and after a change, such as a new supplier or a new delivery partner.
For harder text, such as sarcasm, mixed reviews or many languages, a pretrained language model does better than TF-IDF, and an LLM can explain why a review is negative, not just score it. Start with a simple model like this one anyway: it’s fast, cheap, easy to inspect, and gives you the baseline any bigger model has to beat.
Try it yourself
- Add six more positive reviews that mention delivery, retrain, and score “Delivery was fast” again.
- Set ngram_range to (1, 1) so the model only sees single words. Which predictions change?
- Write three reviews that mix praise and complaint. How does the model score them, and do you agree?
Key points
- TF-IDF turns text into numbers that weight distinctive words highly.
- Logistic regression learns a weight per word or phrase, which you can list to see what drives the scores.
- Small training sets teach accidents; check the strongest words before anyone acts on the scores.
Want to go further?
I teach professionals one to one, and I build these systems for businesses. See Python AI mentoring or see what I build.