Sentiment Analysis & Text Classification
Classify documents/sentiment with classical and neural pipelines end to end.
In plain words
Sentiment analysis teaches a computer to read a review and decide whether the writer is happy or unhappy, by showing it lots of reviews that people have already labelled.
Think of it like…
A mailroom sorter. You can give them a rulebook (lexicon), train them on thousands of past examples (supervised model) or ask a well-read generalist (large language model) to decide from instructions; the sorter's real problem is that most mail is routine and the few urgent letters are the ones that matter.
Where you’ve seen it
A retailer has 10,000 product reviews, 2,000 of them negative (20%). A model that always predicts positive scores 80% accuracy and finds no complaints. The TF-IDF plus logistic regression baseline produces this confusion matrix on the negative class: 1,500 true positives, 500 false positives, 500 false negatives and 7,500 true negatives, so accuracy is (1,500 + 7,500) / 10,000 = 90%, precision 1,500 / 2,000 = 0.75, recall 0.75 and F1 0.75; the positive class has precision and recall of 0.9375, so macro-F1 is (0.75 + 0.9375) / 2 = 0.844. Lowering the decision threshold on the negative probability from 0.5 to 0.35 raises recall to 0.85 at a precision of 0.64 (illustrative), a good trade for a team that must catch angry customers, while a team auto-refunding on negative reviews would raise the threshold instead. Label quality is checked with two annotators: observed agreement 0.85 and chance agreement 0.55 give Cohen's kappa (0.85 − 0.55) / (1 − 0.55) = 0.667, adequate but showing that the neutral class is ambiguous. Reviews such as "not good" and "great, another delay" show why bigrams and sarcasm handling matter; the team keeps the negation, adds bigrams, splits train and test by product so that one product's phrasing doesn't leak, and evaluates a fine-tuned transformer against the baseline before deciding whether the gain is worth the cost.
Words you’ll hear
- Precision and recall
- Share of predicted positives that are right, and share of true positives found.
- F1 / macro-F1
- Harmonic mean of precision and recall, and its unweighted average over classes.
- Decision threshold
- The probability cut-off that turns scores into labels; tune it to the cost of errors.
- Cohen's kappa
- Agreement between annotators corrected for chance.
Visual diagram
Theory & deep dive
Metrics for imbalanced text problems
With 2,000 negatives among 10,000 reviews the baseline of always predicting positive achieves 80% accuracy and 0 recall on the class you care about. Use the confusion matrix. For the negative class in the example, TP = 1,500, FP = 500, FN = 500, TN = 7,500: precision = TP / (TP + FP) = 0.75, recall = TP / (TP + FN) = 0.75 and F1 = 2PR / (P + R) = 0.75, while accuracy is 90%. For multi-class problems report per-class scores and an average: macro-F1 treats classes equally (per-class F1 of 0.9, 0.6 and 0.3 averages to 0.6, exposing the weak class), whereas micro-F1 pools all decisions and is dominated by large classes.
Probabilities allow threshold tuning: predict negative when P(negative) exceeds a cut-off chosen on validation data. Plot the precision–recall curve and pick the point where the cost of a missed complaint balances the cost of a false alarm; for instance, moving from threshold 0.5 to 0.35 may lift recall from 0.75 to 0.85 and drop precision from 0.75 to 0.64. Check calibration if the probabilities are shown to people or used downstream, and report confidence intervals (bootstrap the test set), because a one-point F1 difference on a few hundred examples is noise.
Negative class: TP 1,500, FP 500, FN 500, TN 7,500. Accuracy = 9,000 / 10,000 = 0.90. Precision = 1,500 / 2,000 = 0.75. Recall = 1,500 / 2,000 = 0.75. F1 = 0.75. Positive class F1 = 0.9375. Macro-F1 = 0.844.
Model choices, data quality and failure modes
A sensible ladder: start with a lexicon such as VADER for a zero-training sanity check, then TF-IDF with unigrams and bigrams plus logistic regression (fast, interpretable, hard to beat per unit of effort), then embedding features if wording varies, then a fine-tuned transformer when you have thousands of labelled examples and the accuracy gain justifies the cost, or a zero-shot LLM when you have no labels (verify it on a labelled sample). Compare every option on the same group-aware splits and metric, and include latency and cost per thousand documents in the comparison.
Most failures come from the data. Label noise and ambiguity: measure inter-annotator agreement (kappa of 0.667 from observed agreement 0.85 and chance 0.55) and write clear guidelines for neutral and mixed reviews. Negation, sarcasm and domain shift: "not good" needs bigrams or context models, sarcasm is hard for any model and a classifier trained on movie reviews will misjudge product reviews. Leakage: split by user, product or time rather than randomly when the same author or template appears many times. Spurious cues: inspect the top coefficients; a model that keys on "refund" or a boilerplate footer is learning the process, not the sentiment. After launch, monitor label drift and sample predictions for re-labelling.
Observed agreement p_o = 0.85, agreement expected by chance p_e = 0.55. Kappa = (0.85 − 0.55) / (1 − 0.55) = 0.30 / 0.45 = 0.667, usually read as substantial but imperfect agreement, a ceiling on how well any model can score against these labels.
How it works, step by step
Step 1 of 41. Define labels and split by group
Write labelling guidelines, measure annotator agreement and split by product, user or time to avoid leakage.
- Check
- class balance
When to use it & trade-offs
What it is
Text classification assigns a label (or several) to a document: spam or not, topic, intent, urgency, or the sentiment (positive, negative, neutral) of a review. An end-to-end pipeline defines the labels, collects and cleans examples, splits the data honestly, turns text into features (TF-IDF, embeddings or a transformer's representations), trains a classifier, tunes the decision threshold, evaluates with metrics suited to class balance (precision, recall, F1) and monitors the model after launch. Options range from lexicon rules (such as VADER) through TF-IDF plus a linear model to fine-tuned transformers and zero-shot large language models, trading accuracy against cost, speed and interpretability.
Why it matters: Most business text arrives unlabelled and unbalanced: complaints are a minority of reviews, urgent tickets are rare and sarcasm and negation break naive methods. A model reporting 80% accuracy may be doing nothing at all if 80% of the examples belong to one class. The skill lies in choosing the label scheme, measuring the right metric, thresholding for the cost of mistakes, checking label quality and picking the cheapest model that meets the requirement.
When to reach for it
- Routing support tickets and flagging urgent messages
- Tracking customer sentiment by product and week
- Topic or intent tagging for search and analytics
When to avoid or be careful
- Reporting accuracy alone on imbalanced classes
- Random splits when the same author or product repeats
- Deploying an unvalidated zero-shot labeller
Sentiment and classification approaches
Strengths: No training; transparent.
Watch out: Weak on domain slang and sarcasm.
Strengths: Fast; interpretable coefficients.
Watch out: No deep context or synonyms.
Strengths: Understands context and negation.
Watch out: Costlier to train and serve.
Strengths: Needs only instructions.
Watch out: Per-call cost and variability; needs validation.
Interview signals & numbers to know
When this topic comes up
- “Why is accuracy misleading here?”
- Precision, recall and the threshold trade-off
- Macro versus micro F1
- Handling negation and sarcasm
- How to choose between TF-IDF and a transformer
Benchmarks & rules of thumb
- 80% vs 90%
- majority baseline versus the example model's accuracy
- 0.75 · 0.75 · 0.75
- negative-class precision, recall and F1 in the example
- 0.844
- macro-F1 of the example (0.75 and 0.9375 averaged)
Common mistakes & follow-ups
Common interview mistakes
- Leaving the threshold at 0.5 regardless of costs.
- Treating noisy labels as ground truth.
- Trusting a sentiment model trained in one domain on another.
Likely interviewer follow-ups
- How would you deal with a 1:100 class imbalance?
- How would you choose between a linear model and a transformer?
- How do you check the labels are good enough?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Sentiment Analysis & Text Classification with data science interview Q&A and hands-on practice.