Sentiment Analysis: Lexicons to Fine-Tuned BERT
Sentiment analysis converts text into a signal about the author's attitude: positive, negative, neutral, and β in richer systems β a continuous score or per-aspect opinions. It sits behind brand-monitoring dashboards, review triage, ticket routing, and trading signals derived from news. The task looks easy on demo data and gets genuinely hard on real text, where sarcasm, negation, mixed opinions, and domain jargon break naive systems.
This lesson walks the full accuracy-versus-cost ladder. You will start with lexicon scoring and understand exactly where it fails, move to an attention-based LSTM that learns context, fine-tune BERT for state-of-the-art accuracy, and extend to aspect-based sentiment analysis (ABSA), which reports what people like or dislike rather than a single blob score. Along the way you will handle negation, class imbalance, and the domain shift that silently degrades deployed models.
What You'll Learn
- 1Score text with VADER and word-list lexicons, and explain their failure modes
- 2Train an attention-based BiLSTM sentiment classifier in PyTorch
- 3Fine-tune BERT for sentiment with proper learning rates and evaluation
- 4Implement aspect-based sentiment analysis and diagnose negation errors
Prerequisites
- !Python and pandas
- !Basic PyTorch (tensors, training loops)
- !Familiarity with train/test splits and classification metrics
What sentiment analysis actually predicts
Before choosing a model, fix the prediction target. Three conventions dominate. Document-level sentiment assigns one label per review or tweet. Sentence-level splits long text first, which prevents a single negative paragraph from flipping an otherwise positive review. Aspect-level extracts opinions about specific attributes β a phone review can be positive on camera and negative on battery, and collapsing that into "mixed" loses the actionable detail.
| Approach | Typical accuracy (binary) | Latency | Needs labels? | Handles negation? |
|---|---|---|---|---|
| Word-list lexicon | 60β70% | Sub-millisecond | No | Poorly |
| VADER | 65β75% on social text | Sub-millisecond | No | Partially |
| TF-IDF + logistic regression | 80β88% | Milliseconds | Yes | Implicitly |
| BiLSTM + attention | 85β90% | Tens of ms | Yes (thousands) | Yes |
| Fine-tuned BERT | 90β95% | Tensβhundreds of ms | Yes (thousands) | Yes |
The right starting point depends on label availability. With zero labels, lexicons give you a same-day baseline. With a few thousand labeled examples, linear models on TF-IDF are hard to beat for speed. With ten thousand-plus examples and GPU budget, fine-tuned transformers win.
Lexicon scoring and where it breaks
Lexicon methods sum polarity scores from a dictionary. VADER extends this with rules for capitalization (emphasis), punctuation (exclamation intensity), degree modifiers ("very good"), and a small slang lexicon β which is why it performs respectably on tweets without any training.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
examples = [
"Absolutely loved the camera quality and battery life!",
"The camera is great, but the battery dies by noon.", # mixed
"Not bad for a budget phone.", # negation + faint praise
"This is the best phone I have ever owned.", # superlative
"I spent three hours waiting for support.", # implied negative, no cue words
]
for text in examples:
s = analyzer.polarity_scores(text)
label = "pos" if s["compound"] >= 0.05 else "neg" if s["compound"] <= -0.05 else "neu"
print(f"{label:3s} {s['compound']:+.3f} {text}")
The mixed-opinion sentence exposes the core limitation: additive scoring has no notion of contrast. "Great... but... dies" sums to near zero, which is arguably correct for overall sentiment but useless for product teams who need the battery complaint extracted. The support-waiting sentence contains no negative lexicon entry at all β the negativity is inferential, and only a model with world knowledge catches it.
An attention-based LSTM classifier
Recurrent models read the sequence and learn which tokens matter. A bidirectional LSTM captures context from both directions; a learned attention layer then weights time steps so the classifier focuses on opinion-bearing words rather than the final hidden state alone.
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from collections import Counter
class SentimentDataset(Dataset):
def __init__(self, texts, labels, vocab=None, max_len=128):
self.texts, self.labels, self.max_len = texts, labels, max_len
if vocab is None:
counts = Counter(w.lower() for t in texts for w in t.split())
self.vocab = {"<PAD>": 0, "<UNK>": 1}
for w, c in counts.items():
if c >= 2:
self.vocab[w] = len(self.vocab)
else:
self.vocab = vocab
def encode(self, text):
ids = [self.vocab.get(w.lower(), 1) for w in text.split()][: self.max_len]
ids += [0] * (self.max_len - len(ids))
return torch.tensor(ids, dtype=torch.long)
def __len__(self):
return len(self.texts)
def __getitem__(self, i):
return self.encode(self.texts[i]), torch.tensor(self.labels[i], dtype=torch.long)
class AttentionLSTM(nn.Module):
def __init__(self, vocab_size, embed_dim=128, hidden=128, n_classes=3, dropout=0.3):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
self.lstm = nn.LSTM(embed_dim, hidden, num_layers=2, batch_first=True,
bidirectional=True, dropout=dropout)
self.attn = nn.Linear(hidden * 2, 1)
self.head = nn.Sequential(
nn.Linear(hidden * 2, 64), nn.ReLU(), nn.Dropout(dropout),
nn.Linear(64, n_classes),
)
def forward(self, x):
emb = self.embedding(x)
out, _ = self.lstm(emb)
weights = torch.softmax(self.attn(out).squeeze(-1), dim=1)
context = torch.bmm(weights.unsqueeze(1), out).squeeze(1)
return self.head(context), weights
# Toy loop β substitute your real labeled corpus
dataset = SentimentDataset(examples * 50, [2, 1, 1, 2, 0] * 50)
loader = DataLoader(dataset, batch_size=32, shuffle=True)
model = AttentionLSTM(len(dataset.vocab))
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
loss_fn = nn.CrossEntropyLoss()
for epoch in range(5):
model.train()
total = 0.0
for xb, yb in loader:
logits, _ = model(xb)
loss = loss_fn(logits, yb)
opt.zero_grad(); loss.backward(); opt.step()
total += loss.item()
print(f"epoch {epoch+1} loss={total/len(loader):.4f}")
Inspecting the attention weights after training is a cheap interpretability win: highlight the top-weighted tokens in the UI and reviewers can see why the model flagged a comment.
Fine-tuning BERT for sentiment
Transformers capture long-range context and word sense through pretraining on massive corpora. For sentiment, the recipe is straightforward: tokenize with the BERT tokenizer, take the pooled [CLS] representation, attach a classification head, and train with a small learning rate (2e-5 is the standard starting point) so the pretrained weights adapt without being destroyed.
from transformers import BertTokenizer, BertForSequenceClassification, AdamW
from torch.utils.data import DataLoader
class BertSentiment:
def __init__(self, model_name="bert-base-uncased", n_classes=3):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.tokenizer = BertTokenizer.from_pretrained(model_name)
self.model = BertForSequenceClassification.from_pretrained(
model_name, num_labels=n_classes
).to(self.device)
def _batch(self, texts, labels=None, max_len=128):
enc = self.tokenizer(texts, padding=True, truncation=True,
max_length=max_len, return_tensors="pt").to(self.device)
if labels is not None:
enc["labels"] = torch.tensor(labels, device=self.device)
return enc
def fit(self, texts, labels, epochs=3, batch_size=16, lr=2e-5):
opt = AdamW(self.model.parameters(), lr=lr)
self.model.train()
for epoch in range(epochs):
total = 0.0
for i in range(0, len(texts), batch_size):
batch_texts = texts[i:i + batch_size]
batch_labels = labels[i:i + batch_size]
enc = self._batch(batch_texts, batch_labels)
out = self.model(**enc)
out.loss.backward()
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)
opt.step(); opt.zero_grad()
total += out.loss.item()
print(f"epoch {epoch+1} loss={total / (len(texts)//batch_size):.4f}")
@torch.no_grad()
def predict(self, texts):
self.model.eval()
enc = self._batch(texts)
logits = self.model(**enc).logits
return logits.argmax(dim=-1).cpu().numpy(), torch.softmax(logits, dim=-1).numpy()
clf = BertSentiment(n_classes=3)
# clf.fit(train_texts, train_labels) # supply your labeled dataset
print("BERT sentiment pipeline ready")
Two evaluation details matter more than people expect. First, report per-class F1, not just accuracy β negative reviews are often the minority class and the one the business cares about. Second, hold out a domain-specific test set. A model at 93% on Amazon reviews can drop to 78% on clinical notes; measure on your target distribution before shipping.
Aspect-based sentiment analysis
ABSA splits the problem: extract aspects (camera, battery, service), then classify the sentiment expressed about each aspect in its local context. A practical pipeline uses a small aspect lexicon or a fine-tuned token classifier for extraction, then runs sentiment on the sentence (or clause) containing each aspect mention.
import numpy as np
ASPECT_LEXICON = {
"camera": ["camera", "photo", "photos", "lens", "portrait"],
"battery": ["battery", "charge", "charging", "battery life"],
"service": ["support", "service", "agent", "customer care"],
"price": ["price", "cost", "value", "expensive", "cheap", "worth"],
}
def extract_aspect_sentences(text):
sentences = [s.strip() for s in text.replace("!", ".").split(".") if s.strip()]
hits = {}
for aspect, keywords in ASPECT_LEXICON.items():
matched = [s for s in sentences if any(k in s.lower() for k in keywords)]
if matched:
hits[aspect] = matched
return hits
def aspect_sentiment(text, analyzer):
results = {}
for aspect, sents in extract_aspect_sentences(text).items():
scores = [analyzer.polarity_scores(s)["compound"] for s in sents]
mean = float(np.mean(scores))
label = "positive" if mean > 0.05 else "negative" if mean < -0.05 else "neutral"
results[aspect] = {"label": label, "score": round(mean, 3)}
return results
review = ("The camera is stunning and photos come out sharp. "
"Unfortunately the battery barely lasts half a day. "
"Support replaced the unit quickly, but the price is hard to justify.")
print(aspect_sentiment(review, analyzer))
# -> camera: positive, battery: negative, service: positive, price: negative
Per-aspect output is what product teams actually act on. Averaging to a single star rating would bury the battery problem and the pricing complaint that a single global label cannot separate.
Negation, domain shift, and other failure modes
Negation flips polarity but often sits several tokens away from the opinion word ("I do not think the camera is any good"). Lexicons handle only window-based negation and usually fail on long-distance or double negation; neural models learn these patterns from data, but only if the training set contains enough of them. Audit your error slices for negation explicitly β build a 200-example challenge set of negated sentences and report accuracy on it separately.
Domain shift is the silent production killer. Product review vocabulary ("durable", "flimsy") does not transfer to hospitality ("noisy room", "rude staff") or finance ("volatile", "overweight"). Continuously sample live predictions, hand-label a slice weekly, and track accuracy drift; retrain when the rolling score falls below your acceptance threshold. Class imbalance needs the same attention: if 85% of tickets are neutral, a model predicting "neutral" always scores 85% accuracy while being useless β optimize macro F1 and consider class-weighted loss or focal loss.
Sarcasm and irony remain the hardest systematic failure: "Oh great, another software update that broke everything" is lexically positive and semantically negative. Neural models pick up on some sarcasm markers when training data contains enough of them, but production sarcasm rates vary wildly by platform β enterprise support tickets contain almost none, social media timelines are saturated. If sarcasm matters to your use case, measure it explicitly on a labeled slice rather than assuming the aggregate F1 reflects it. Finally, watch for label-definition drift: if the product team redefines what counts as a "negative" ticket (say, escalating billing complaints to negative), yesterday's model is solving yesterday's problem even though the input distribution looks unchanged β re-annotation and retraining must follow the definition, not just the data. Multilingual deployments add another axis of drift: a model trained on English reviews does not merely translate poorly to Japanese; it fails on different linguistic cues entirely, so per-language evaluation and separate fine-tuning are usually required rather than optional.
Common Mistakes
Shipping a lexicon score as if it were a trained model without measuring domain accuracy
Fix: Label a 200β500 sample test set from your own domain and measure before choosing the approach; lexicons often land near chance on formal or specialized text.
Tuning BERT with the default 3e-5 learning rate and dropout 0.1 on a tiny dataset
Fix: Drop to 2e-5 with 2β3 epochs and early stopping; on datasets under 2k examples, freeze the lower transformer layers.
Reporting only overall accuracy on an imbalanced sentiment dataset
Fix: Report per-class precision/recall/F1 and the confusion matrix; the negative class is usually both rare and most important.
Evaluating aspect sentiment with the global review label as ground truth
Fix: Annotate aspect-level labels; global labels systematically penalize correct mixed-aspect predictions.
Best Practices
- Build a lexicon or TF-IDF baseline first; it defines the bar your neural model must clear
- Keep a fixed, domain-labeled test set and a small adversarial set (negation, sarcasm, mixed sentiment) β never train on either
- Log attention weights or token attributions with predictions so reviewers can audit errors
- Retrain on a rolling window of fresh labels to counter language drift
- For mixed-aspect text, prefer aspect-level outputs even when the headline metric is document-level
Interview Questions
Q1: Why does additive lexicon scoring fail on mixed reviews?
It has no mechanism for contrast or scope: positive and negative clauses are summed independently, so 'great camera, terrible battery' collapses toward neutral and the actionable complaint disappears.
Q2: What learning rate and why so small when fine-tuning BERT?
Around 2e-5 with AdamW. Large rates destroy the pretrained representations (catastrophic forgetting); small rates let the model adapt the last layers while keeping general language knowledge.
Q3: How do you detect concept drift in a deployed sentiment model?
Hold out a continuously refreshed labeled slice, track macro F1 over time, and monitor the prediction distribution β a sudden shift in positive/negative base rates often precedes an accuracy drop.
Key Takeaways
- Choose the simplest approach your label budget supports: lexicons zero-shot, TF-IDF with thousands of labels, BERT with tens of thousands plus GPU
- Attention LSTMs give cheap interpretability; transformer fine-tuning gives accuracy β both need domain-matched evaluation
- Aspect-based sentiment is the format product teams can act on; global scores hide mixed opinions
- Negation, imbalance, and domain shift are the three failure modes to audit for every deployment
- Monitor accuracy drift on fresh labels; sentiment language evolves and static models decay