Sentiment Analysis
Prerequisites
- !Text classification metrics and thresholds
- !How transformers are fine-tuned for token or sentence tasks
- !What class imbalance does to a loss function
What You'll Learn
- 1Define a sentiment label set that matches the decision the business will take on it
- 2Build a lexicon scorer with negation and intensifier handling as a cheap baseline
- 3Move from document polarity to aspect-level sentiment with evidence spans
- 4Decide when an LLM judge is worth its cost and how to keep it stable
Sentiment is a label you have to define first
"Is this review positive?" sounds like a question with an obvious answer until the annotations come back split three ways. One annotator marks a review with a complaint about shipping and praise for the product as positive overall; another marks it negative because the customer said they might not repurchase; a third calls it neutral. The model is not failing â the label was never defined.
Write the definition as decisions the annotators can apply mechanically. Is the target the product, the experience, or the writer's intent to buy? Is there a neutral class, and what separates it from mixed? Is the scale ordinal (one to five stars) or categorical? Is sarcasm labelled by literal meaning or intended meaning? Each choice changes both what you can measure and what action the output can drive.
Match the label to the downstream action. A dashboard that wants "are customers angry this week" needs a high-recall anger signal and tolerates noise. A routing system that escalates tickets needs high precision on the negative class, because a false alarm costs an agent's attention while a miss costs a customer. The same model serves neither well without different thresholds.
A lexicon baseline that still earns its keep
Before training anything, a valence lexicon with a handful of rules gives you a running number in an afternoon â invaluable as a floor for comparison and as a fallback when the model service is down.
import re
VALENCE = {
"love": 2.4, "great": 1.9, "fast": 1.1, "helpful": 1.6, "solid": 1.2,
"hate": -2.4, "broken": -2.1, "slow": -1.2, "rude": -1.9, "refund": -1.5,
"okay": 0.4, "fine": 0.5, "average": 0.3,
}
NEGATORS = {"not", "never", "no", "cannot", "hardly", "isn't", "wasn't"}
INTENSIFIERS = {"very": 1.3, "really": 1.35, "extremely": 1.6, "slightly": 0.6}
def score_sentiment(text: str) -> dict:
tokens = re.findall(r"[a-z']+", text.lower())
total, hits = 0.0, []
for i, tok in enumerate(tokens):
val = VALENCE.get(tok)
if val is None:
continue
window = tokens[max(0, i - 3):i]
if any(w in NEGATORS for w in window):
val *= -0.85 # negation flips, but not perfectly
for w in window:
if w in INTENSIFIERS:
val *= INTENSIFIERS[w]
break
total += val
hits.append((tok, round(val, 2)))
label = "positive" if total > 1.0 else "negative" if total < -1.0 else "neutral"
confidence = min(1.0, abs(total) / 4.0)
return {"label": label, "score": round(total, 2),
"confidence": round(confidence, 2), "evidence": hits}
print(score_sentiment("The battery life is great but support was really rude"))
# -> negative-ish evidence captured on both sides; score decides the winner
Two properties make this useful. The evidence list is explainable â you can show which words moved the score â and the neutral band around zero means the scorer admits uncertainty instead of forcing a side. Both are things the trained model will have to be told to do.
Aspect sentiment: the output people actually want
Document-level polarity collapses sentences like "The camera is stunning, the software is sluggish" into one number that describes neither. Aspect-level sentiment returns a tuple per aspect: the aspect, the polarity, and the span that justifies it.
| Approach | Accuracy on aspects | Explainable | Setup cost |
|---|---|---|---|
| Keyword rules per aspect | Low to medium | Yes | High maintenance |
| Lexicon polarity over aspect window | Medium | Yes | Low |
| Token classification (aspect + polarity heads) | High | Partially | Labeling effort |
| LLM extraction to structured output | High | Yes, with spans | Prompt iteration |
The practical pipeline combines recall and precision: a model proposes candidate aspects from a domain list, a polarity scorer labels each, and the response is grouped by aspect for the dashboard. When an aspect is mentioned without sentiment â "arrived Tuesday" â the correct label is neutral, not missing, because absence of complaint is signal too.
from collections import defaultdict
def aspect_report(aspects: list[dict]) -> dict:
"""aspects: [{"aspect": str, "label": str, "confidence": float}, ...]"""
grouped = defaultdict(list)
for a in aspects:
grouped[a["aspect"].lower()].append(a)
report = {}
for aspect, items in grouped.items():
pos = [i for i in items if i["label"] == "positive"]
neg = [i for i in items if i["label"] == "negative"]
weight = lambda bucket: sum(i["confidence"] for i in bucket)
if weight(pos) > weight(neg) * 1.25:
overall = "positive"
elif weight(neg) > weight(pos) * 1.25:
overall = "negative"
else:
overall = "mixed"
report[aspect] = {
"overall": overall,
"mentions": len(items),
"confidence": round(max(weight(pos), weight(neg)) / max(1, len(items)), 2),
}
return dict(sorted(report.items(),
key=lambda kv: kv[1]["mentions"], reverse=True))
mentions = [
{"aspect": "camera", "label": "positive", "confidence": 0.93},
{"aspect": "software", "label": "negative", "confidence": 0.88},
{"aspect": "camera", "label": "positive", "confidence": 0.81},
]
print(aspect_report(mentions))
Weighting by confidence rather than counting votes is deliberate: three weak positives should not outvote one strong negative when you are deciding whether to escalate.
Training a classifier and calibrating it
Fine-tuned transformers do well here, with three recurring adjustments. Class imbalance appears because genuinely angry reviews are a minority, so use class weights or focal loss and judge by per-class F1. Domain shift appears whenever you pretrain-tune on product reviews and deploy on support tickets â the vocabulary of complaint differs â so fine-tune on at least a sample of production text. And calibration appears because downstream code wants thresholds: apply temperature scaling on a validation set, then pick the negative threshold from the cost ratio rather than from 0.5.
Watch for the leak that inflates every offline score: reviews from the same product page share phrasing, so a random split puts near-duplicates on both sides. Split by product, author, or time instead, and report the honest number before the demo.
Sarcasm, emoji and the limits of text
Sarcasm is the standing failure mode: "Oh great, another update that broke my workflow" is lexically positive and semantically furious. Models trained on enough similar phrasing catch the common patterns â interjections, capitalisation, hyperbolic praise attached to a complaint â but genuine sarcasm often needs context text does not contain: the customer's history, the thread's prior turns, the fact that this is the third ticket this week about the same bug.
Rather than chase a universal sarcasm detector, encode the context you have. Include the previous turn, the product tier, and the number of prior contacts as model features. Where the text alone is genuinely ambiguous, let the label be ambiguous: a confidence band that routes uncertain cases to a human is more valuable than a confident wrong answer, because the human resolves the ones the model cannot while the model handles the rest at scale.
Putting an LLM in the loop as judge
For long, mixed messages a prompting LLM can outperform a small classifier and return structured justification, but only if you pin its behaviour down. Ask for a fixed JSON schema, a confidence value, and the exact supporting quote; sample the answer twice and compare, because instability across samples reveals a prompt that is guessing; and evaluate the judge against a human-labelled set before trusting it in production. The cost maths is unforgiving: an LLM judge at a few hundred tokens per message costs orders of magnitude more than a classifier, so reserve it for the abstain bucket â the messages the cheap model flagged as uncertain â rather than for all traffic.
Metrics, error review and operating the system
Accuracy tells you little when the positive class is 8% of traffic and your threshold decides escalation. Track precision and recall separately for the negative class, because those are the two numbers with different costs attached: recall misses angry customers, precision wastes agent time. Add a confusion view over the neutral class, which is where most production arguments actually happen â a neutral labelled negative becomes a spurious alert, and a neutral labelled positive hides a complaint that is still building.
Review errors on a schedule rather than after an incident. Sample fifty predictions from the previous week, read the evidence spans, and bucket each miss: wrong label definition, missing context, sarcasm, domain shift, or genuine model error. Most teams find the first two dominate, and both are fixed in data and prompt rather than in architecture. Finally, watch the input distribution itself â average message length, emoji frequency, the share of text containing a refund keyword. When those move, sentiment metrics follow within days, and a leading indicator buys time to relabel before the dashboard turns red.
Common Mistakes
Shipping a sentiment label that annotators interpret three different ways
Fix: Write mechanical definitions with near-miss examples and measure agreement before training
Evaluating with a random split over near-duplicate reviews
Fix: Split by product, author or time so shared phrasing cannot leak across the boundary
Running an LLM judge on every message
Fix: Route only the classifier's abstain bucket to the judge and record the cost per resolution
Treating mixed sentiment as neutral
Fix: Keep a mixed or per-aspect output so praise and complaint are not averaged into silence
Best Practices
- Define the label from the downstream decision, then derive metrics and thresholds from it
- Ship a lexicon scorer as a fallback and as an explainable floor for the trained model
- Return evidence spans with every prediction; they make review, debugging and trust dramatically faster
- Calibrate probabilities and set thresholds from the cost of a wrong action
- Monitor class distribution weekly â a shift in the positive/negative ratio is an early warning of a product incident
Key Takeaways
- Sentiment quality starts with a written definition tied to a specific downstream action
- A lexicon scorer with negation and intensifier rules is a cheap, explainable baseline and a production fallback
- Aspect-level output with evidence spans is usually what stakeholders actually need from the system
- Split honestly by product, author or time, and calibrate thresholds from the cost of errors
- LLM judges earn their cost only in the abstain bucket, and only with schema, quoting and self-consistency checks