Sentiment analysis detects whether text expresses a positive, negative or neutral opinion. Businesses use it on reviews, tweets and support tickets. This tutorial builds a classic ML model, shows honestly why it needs lots of data, then uses a pre-trained transformer.
What You Will Learn
- Build a TF-IDF + logistic regression sentiment model
- Why tiny datasets fail
- Inspect which words drive predictions
- Use a pre-trained model with Hugging Face
- Handle negation, sarcasm and Hinglish
Prerequisites
Bag of Words & TF-IDF, Logistic Regression.
A Small Labelled Dataset
import pandas as pd
pos = ["Loved the food, will come again", "Excellent service and tasty biryani",
"Great ambience and friendly staff", "The paneer tikka was amazing",
"Quick delivery and hot food", "Best dosa in town, highly recommend",
"Very good taste and fair price", "Staff was polite and helpful",
"Fresh ingredients, loved it", "Awesome experience with family",
"Delicious desserts and good coffee", "Value for money, great portions",
"Clean place and tasty food", "Wonderful flavours, will order again",
"Superb thali, excellent quality"]
neg = ["Food was cold and tasteless", "Terrible service, waited an hour",
"Too expensive for small portions", "The biryani was very oily",
"Rude staff and dirty tables", "Worst pizza I have ever had",
"Delivery was late and food spilled", "Overcooked noodles, not worth it",
"Bad experience, will not return", "Bland curry and stale bread",
"Very slow service and noisy place", "Found hair in the food, disgusting",
"Poor quality and overpriced", "Waited long, order was wrong",
"Stale snacks and bad coffee"]
df = pd.DataFrame({"text": pos + neg, "label": [1] * 15 + [0] * 15})
Train and Evaluate
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import cross_val_score
model = make_pipeline(TfidfVectorizer(ngram_range=(1, 2)), LogisticRegression())
print(round(cross_val_score(model, df.text, df.label, cv=5).mean(), 3))
model.fit(df.text, df.label)
tests = ["The food was tasty and staff friendly", "Service was slow and food cold", "Not good at all"]
for t, p in zip(tests, model.predict_proba(tests)[:, 1]):
print(f"{p:.2f} {t}")
0.467 0.52 The food was tasty and staff friendly 0.43 Service was slow and food cold 0.50 Not good at all
Explanation: Cross-validated accuracy is only 47% – no better than guessing – and the probabilities on new sentences are all close to 0.5. With 30 reviews, almost every word in a new review was seen once or never. This is the key lesson of text classification: classic models need thousands of labelled examples. On a public dataset such as the 50,000 IMDB movie reviews, the same kind of pipeline typically reaches around 88–90% accuracy.
What Did It Learn?
import numpy as np
names = model[0].get_feature_names_out()
order = np.argsort(model[1].coef_[0])
print("negative:", list(names[order[:5]]))
print("positive:", list(names[order[-5:]]))
negative: ['bad', 'stale', 'not', 'waited', 'was'] positive: ['great', 'loved', 'and tasty', 'tasty', 'excellent']
Explanation: Even with little data the strongest words make sense. Looking at coefficients is a quick way to sanity-check any text model.
Pre-trained Transformer
# pip install transformers torch
from transformers import pipeline
clf = pipeline("sentiment-analysis") # downloads a fine-tuned DistilBERT model
print(clf(["The food was tasty and staff friendly", "Not good at all",
"Not bad, actually quite tasty"]))
Explanation: A model pre-trained on huge text and fine-tuned on labelled reviews understands phrases like “not good” and “not bad” without any training on your side. For Hindi or Hinglish, choose a multilingual model from the Hugging Face hub (for example XLM-RoBERTa-based sentiment models) – see BERT. LLMs such as GPT, Claude or Gemini can also classify sentiment with a short prompt.
Choosing an Approach
| Approach | Data needed | Pros | Cons |
|---|---|---|---|
| Lexicon (VADER, TextBlob) | None | Instant, explainable | Misses context and domain words |
| TF-IDF + logistic regression | Thousands of labels | Fast, cheap, transparent | Weak on negation and sarcasm |
| Fine-tuned transformer | Hundreds to thousands | High accuracy | Needs GPU, slower |
| LLM prompt | Zero or few examples | Flexible, multilingual | Cost per call, needs evaluation |
Series
NLP series: NLP Intro · Tokenizer · Stop Words · Stemming · Lemmatization · Bag of Words & TF-IDF · Word Embeddings · Sentiment Analysis · NER · Topic Modeling · BERT · Spam Project
Interview Questions
Q: How would you build a sentiment classifier?
Collect labelled data, vectorise with TF-IDF or embeddings, train a classifier and evaluate with cross-validation – or fine-tune a transformer.
Q: Why do bigrams help sentiment?
They capture short phrases such as “not good” that single words miss.
Practice Exercises
- Add 50 more reviews to the dataset and watch cross-validated accuracy change.
- Compare the Hugging Face pipeline with your model on 20 reviews you write yourself.
Summary
TF-IDF + logistic regression is a fast baseline when you have thousands of labelled texts; with little data use a pre-trained transformer or an LLM. Always evaluate on held-out data.
Next: Named Entity Recognition
Machine Learning Tutorials, Courses and Certifications