What the label actually means
Sentiment analysis is not one task but a family of labelling decisions that share a vocabulary. Document-level polarity asks for a single positive, negative, or neutral stamp over a whole review. Sentence-level polarity splits the document first and labels each piece. Aspect-level sentiment asks a different and much more useful question: what does the author think about this particular feature? A laptop review that praises the keyboard and condemns the fan is simultaneously positive and negative at document level, and every document-level model forced to choose will pick one and lose the other.
The labelling scheme determines everything downstream.Binary polarity collapses neutral into one of the two poles and inflates apparent accuracy. Three-way with an explicit neutral class handles the many reviews that simply state facts. Fine-grained five-point scales demand far more annotation agreement than crowdsourcing usually delivers, and inter-annotator agreement on five-point sentiment routinely falls below the level where a model can be trusted to beat it.
This lesson works through the three approach families in increasing order of data requirement, then spends most of its length on the evaluation and domain-shift problems that actually decide whether a sentiment system is deployable. One more framing point before the code: sentiment is almost never the end goal. It is a proxy for churn risk, a routing signal for support queues, or a feature feeding a product-level score, and the acceptable error rate depends entirely on what the consumer of the label does with it. A recommendation engine can tolerate noisy polarity; an automated refund decision cannot, and the threshold has to be set by that cost asymmetry rather than by whatever maximises F1 on the benchmark.
Lexicon scoring and its blind spots
A lexicon model scores each word from a hand-built table and aggregates. It needs no training data, it is fully inspectable, and it works immediately on day one of a project. It also has no mechanism for composition: not good scores as the sum of not and good, and the result depends entirely on whether someone remembered to add a negation rule.
from nltk.sentiment import SentimentIntensityAnalyzer
import nltk
nltk.download("vader_lexicon", quiet=True)
sia = SentimentIntensityAnalyzer()
NEGATORS = {"not", "no", "never", "neither", "hardly", "barely"}
INTENSIFIERS = {"very", "extremely", "really", "so", "totally"}
def scored_sentiment(text, lexicon_scale=1.0):
words = text.lower().split()
total, negate = 0.0, False
for w in words:
base = lexicon_scale * lexicon_scores.get(w, 0.0)
if w in INTENSIFIERS:
continue
total += -base if negate else base
if w in NEGATORS:
negate = True
else:
negate = False
return total
lexicon_scores = {"good": 1.9, "great": 3.1, "bad": -2.5, "awful": -3.4}
samples = [
"the film was good",
"the film was not good",
"the film was very good",
"the film was good but the sound was awful",
]
for s in samples:
vader = sia.polarity_scores(s)["compound"]
print(f"{s:<45} vader={vader:+.3f} custom={scored_sentiment(s):+.2f}")
The fourth sample exposes the real limitation: both scores average across clauses, so a mixed review collapses to something mildly positive and the business question â which aspect failed â goes unanswered.
Learning from labels: the honest baseline
With a few hundred labelled examples you can beat any lexicon by training a linear model over TF-IDF n-grams. The important discipline is that the vectorizer lives inside the pipeline, so vocabulary is fitted on training folds only.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
from sklearn.metrics import classification_report
train = [
("absolutely loved it, would buy again", 1),
("brilliant acting and a tight script", 1),
("worth every penny of the price", 1),
("broke after two days of normal use", 0),
("customer support never replied", 0),
("a complete waste of money", 0),
("packaging was damaged on arrival", 0),
("the plot was predictable but fun", 1),
]
texts = [t for t, _ in train]
labels = [y for _, y in train]
pipe = Pipeline([
("tfidf", TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True, min_df=1)),
("clf", LogisticRegression(C=2.0, class_weight="balanced", max_iter=1000)),
])
scores = cross_val_score(pipe, texts, labels, cv=3, scoring="f1")
print("cv f1:", round(scores.mean(), 3), "+/-", round(scores.std(), 3))
pipe.fit(texts, labels)
print(classification_report(labels, pipe.predict(texts), digits=2))
weights = pipe.named_steps["clf"].coef_[0]
vocab = pipe.named_steps["tfidf"].get_feature_names_out()
top = sorted(zip(vocab, weights), key=lambda kv: -kv[1])[:5]
bottom = sorted(zip(vocab, weights), key=lambda kv: kv[1])[:5]
print("positive cues:", [w for w, _ in top])
print("negative cues:", [w for w, _ in bottom])
Inspecting the coefficients is not optional. If delivery appears among the strongest negative cues, your training set probably over-samples complaints about shipping, and the deployed model will punish every positive review that mentions delivery.
Aspect-level sentiment changes the question
Aspect-based sentiment analysis splits the problem into aspect extraction and per-aspect polarity. The payoff is an actionable output: a feature list with sentiment attached, which a product team can actually prioritise against.
# Aspect extraction followed by per-aspect polarity
ASPECT_LEXICON = {
"battery": ["battery", "charge", "power cell"],
"screen": ["screen", "display", "panel"],
"camera": ["camera", "photo", "lens"],
}
def aspect_sentiment(text, polarity_fn):
lower = text.lower()
out = {}
for aspect, cues in ASPECT_LEXICON.items():
if any(c in lower for c in cues):
out[aspect] = polarity_fn(text)
return out
review = "The camera is superb but the battery dies by lunchtime"
print(aspect_sentiment(review, lambda t: "pos" if "superb" in t else "neg"))
# {'battery': 'pos', 'camera': 'pos'} <- clause-agnostic, and wrong for battery
That deliberately wrong result is the point: naive aspect extraction plus document polarity mislabels mixed reviews. Production systems anchor polarity to the clause containing the aspect cue, usually by extracting the sentence around the aspect and classifying that span instead of the whole document.
Evaluation: accuracy hides the failure
On a corpus where 90 percent of reviews are positive, always predicting positive scores 90 percent accuracy while being useless. Precision, recall, and F1 per class expose this immediately, and for a moderation or churn use case the class you care about is usually the minority one.
| Metric | Sensitive to | Failure it exposes |
|---|---|---|
| Accuracy | Class balance | Majority-class collapse |
| Precision | False positives | Flagging benign text as negative |
| Recall | False negatives | Missing the complaints you need |
| F1 | Balance of the two | Minority-class blindness |
| Macro F1 | Per-class equally | Skewed label distributions |
| Cohen's kappa | Chance agreement | Scores inflated by imbalance |
| Calibration | Confidence accuracy | Over-confident wrong predictions |
For three-way sentiment, macro-averaged F1 is the number to report, because it weights neutral and negative as heavily as positive even when they are rare. Always publish the confusion matrix alongside it: the most common real-world defect is neutral being absorbed into whichever polarity dominates the training data.
Matching the approach to the label budget
The right entry point depends almost entirely on how much labelled data exists on day one. With zero labels, a lexicon gives you a working pipeline and a rough sense of class balance within an afternoon, and the honest way to use it is as a weak labeller to bootstrap a seed set rather than as the final system. With a few hundred labels per class, a TF-IDF linear classifier trained in a pipeline will usually surpass the lexicon by a wide margin, because the discriminative tokens for your domain are rarely the ones a general-purpose sentiment dictionary emphasises. With several thousand per class, fine-tuning a small pretrained transformer becomes worth the engineering, and the gains show up most clearly on negation, contrastive clauses, and domain-specific phrasing that n-grams cannot represent compositionally. Beyond that, the marginal returns shift from model capacity to label quality: at ten thousand examples, improving annotator agreement and resolving ambiguous guidelines typically buys more than moving from a small transformer to a large one.
A practical sequence is therefore to ship the lexicon, collect its disagreements with human reviewers, label those disagreements first because they are the informative cases, and retrain the linear model. Only when the residual errors are demonstrably compositional â cases where every word is present and the meaning still inverts â is the transformer stage justified.
Domain shift is the deployment problem
A model trained on movie reviews scores well on movie reviews and degrades sharply on support tickets, because the vocabulary that carries sentiment differs by domain. unpredictable is praise for a thriller and a bug report for a login flow. sick is positive in gaming contexts. The reliable fixes are to fine-tune on in-domain labels, to calibrate thresholds on a held-out in-domain set, and to monitor the predicted label distribution in production â a sudden shift in the positive rate is usually a data drift signal rather than a change in customer mood.
â ī¸Sarcasm is not solvable by more training data
Common Mistakes
Reporting accuracy on an imbalanced sentiment dataset
Fix: Report macro F1 and the confusion matrix; a majority baseline can post 90 percent accuracy while learning nothing.
Fitting the TF-IDF vectorizer before cross-validation
Fix: Nest it in a Pipeline so vocabulary and IDF are learned inside each training fold.
Applying a movie-review model to support tickets
Fix: Fine-tune on in-domain labels and recheck calibration, since sentiment-bearing vocabulary is domain specific.
Treating a mixed review as a single polarity
Fix: Extract aspects and classify the clause containing each aspect cue instead of the whole document.
Best Practices
- Start with a lexicon for a zero-label smoke test, then move to a linear TF-IDF baseline
- Publish macro F1 with the confusion matrix and the class distribution on every evaluation
- Inspect top-weighted features per class to detect label leakage and sampling bias
- Monitor predicted label distribution in production as an early drift alarm
Interview Questions
Q1: Why is accuracy a poor metric for sentiment analysis?
Sentiment datasets are usually heavily skewed, so a majority-class predictor reaches high accuracy while the minority class â often the one you care about â has zero recall.
Q2: How would you handle a review that is positive about one feature and negative about another?
Run aspect-based sentiment: extract the aspect terms, take the clause containing each, and classify polarity per clause rather than per document.
Q3: What typically breaks when a sentiment model moves to a new domain?
The vocabulary that carries polarity shifts, so weights learned on one domain misfire on another; the fix is in-domain fine-tuning plus recalibration of decision thresholds.
Key Takeaways
- The labelling scheme â binary, three-way, fine-grained, aspect-level â determines what the model can possibly learn
- Lexicons need no labels but cannot compose; linear models on TF-IDF beat them with a few hundred examples
- Aspect-level sentiment is what product teams actually need from mixed reviews
- Macro F1 and the confusion matrix are the honest metrics under class imbalance
- Domain shift, not model capacity, is what usually breaks a deployed sentiment system