🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Sentiment Analysis: Fine-Grained and Aspect-Based

Natural Language ProcessingSentiment Analysis: Fine-Grained and Aspect-BasedđŸŸĸ Free Lesson

Sentiment Analysis: Fine-Grained and Aspect-Based

What You'll Learn

  • 1Compare lexicon, classifier, and transformer approaches to sentiment
  • 2Attach a sentiment label to a specific aspect with attention over tokens
  • 3Choose macro F1 over accuracy for imbalanced label sets
  • 4Read a fine grained scale without confusing it with a calibrated probability

Sentiment analysis maps text to an opinion label, and the task quietly splits into three levels. Document level returns one polarity for a whole review, aspect level returns a separate opinion per feature, and multimodal systems add tone and face to the words. This lesson builds the model ladder from lexicons to transformers, then fixes the metric choices that decide whether your improvement was real.

Lexicons and Linear Classifiers

Lexicon methods sum valence scores from a fixed lexicon. VADER normalizes the raw sum with a squash function so a single extreme word cannot push the score past bounds:

where is the weighted sum of valence terms with modifiers and negation handling applied. Lexicons are transparent and need no training data, but they miss sarcasm, domain slang, and any word they never saw.

Supervised classifiers learn the weights instead. With bag of words features , logistic regression estimates a binary polarity:

This baseline still wins on small datasets, because a few thousand labeled reviews are rarely enough to fit a transformer from scratch, and error analysis shows the usual failures: negation scope, contrastive clauses, and domain shift from product reviews to support tickets.

Aspect-Based Sentiment

Aspect based sentiment analysis (ABSA) extracts the aspect term and then assigns sentiment to it, which turns one review into a structured table of opinions. The standard formulation conditions on the aspect:

An attention layer builds the aspect representation by weighting tokens near the aspect term, so irrelevant clauses contribute little:

Aspect term extraction runs first, because a polarity head cannot label an aspect it never localized. Implicit aspects such as price in a review that only says expensive require the model to infer the category, and that inference step is where most remaining ABSA errors come from.

For a laptop review that says the battery is excellent but the keyboard feels cheap, a document model sees two sentiments and one label, while the aspect model emits battery positive and keyboard negative. That structure is why product analytics, review moderation, and survey analysis all standardize on ABSA.

Benchmarks and Metrics

DatasetSizeLabelsLevel
SST-267,349 train phrasesbinarysentence
IMDb50,000 reviewsbinarydocument
GoEmotions58,009 comments27 emotions plus neutralfine grained
SemEval ABSAaspect tablespolarity per aspectaspect

Fine grained scales behave like ordinal categories, and a five way model that confuses 4 with 5 is far less wrong than one that confuses 1 with 5, yet accuracy treats them equally. Macro F1 averages per class, so the rare negative class in a mostly positive corpus still moves the score:

Multimodal sentiment adds prosody and facial action units to the text, which matters for short utterances where words are neutral but the tone is not. The fusion design decides most of the result: early fusion concatenates modalities before encoding, late fusion trains a separate model per modality and averages logits, and hybrid fusion keeps per modality heads that only combine at the final layer.

Domain shift is the quiet failure. A classifier trained on product reviews misreads support tickets because politeness conventions differ, and the fix is usually a few hundred in domain labels rather than a bigger architecture, which is why teams budget for relabeling at every new domain.

Worked Examples

Worked Code

python
"""Aspect level sentiment with a fine tuned checkpoint."""
from transformers import pipeline

classifier = pipeline("text-classification",
                      model="yangheng/deberta-v3-base-absa-v1.1",
                      return_all_scores=True)
review = "The battery life is excellent but the keyboard feels cheap."
for aspect in ["battery life", "keyboard"]:
    scores = classifier(review, text_pair=aspect)[0]
    best = max(scores, key=lambda s: s["score"])
    print(aspect, "->", best["label"], round(best["score"], 3))
python
"""Macro F1 from per class true positives, false positives, misses."""
def macro_f1(counts, labels):
    total = 0.0
    for label in labels:
        tp, fp, fn = counts[label]
        precision = tp / (tp + fp) if tp + fp else 0.0
        recall = tp / (tp + fn) if tp + fn else 0.0
        total += 0.0 if not precision + recall else 2 * precision * recall / (precision + recall)
    return round(total / len(labels), 3)


counts = {"pos": (80, 10, 10), "neg": (40, 5, 15), "neu": (30, 20, 50)}
print(macro_f1(counts, ["pos", "neg", "neu"]))

Real-World Applications

  • Review analytics - Retailers break star ratings into aspect tables so engineering hears about battery complaints while marketing watches delivery sentiment.
  • Support triage - Negative spikes on a billing topic page trigger a human queue before churn shows up in the numbers.
  • Brand monitoring - Fine grained emotion labels separate anger from disappointment, which need different responses.
  • Voice of customer - Multimodal scoring catches frustration in calls where the transcript alone reads politely.

💡Publish per class scores and the confusion matrix

Accuracy on a skewed sentiment set mostly measures the majority class. Macro F1 plus a confusion matrix tells you whether a regression came from the rare class you care about.

Common Mistakes

Using accuracy on skewed sentiment data

Fix: Report macro F1, since a mostly positive corpus inflates accuracy for a model that never predicts negative.

Treating softmax scores as calibrated

Fix: Apply temperature scaling or a Platt fit on dev before exposing a confidence to product logic.

Mixing document and aspect gold labels

Fix: Keep scopes in separate datasets, because a positive document can hold negative aspects.

Best Practices

  • Report macro F1 with per class support and a confusion matrix
  • Evaluate on a domain matched test set when you ship to a new vertical
  • Separate aspect extraction accuracy from aspect sentiment accuracy

Key Takeaways

  • Lexicons normalize a valence sum while supervised models learn weights from labeled text
  • Aspect based sentiment conditions on an aspect representation built with attention
  • Macro F1 averages per class F1 so rare classes still move the headline
  • Softmax outputs need calibration before they can drive product thresholds

Frequently Asked Questions

Why does aspect sentiment need attention?

Because the sentence contains evidence for several aspects at once. Attention concentrates the representation on tokens near the aspect term so the classifier reads the right clause.

Is five way sentiment better than binary?

Only if your downstream action differs. If all you do is escalate negatives, collapsing to binary removes a source of label noise and improves measured F1.

How do you handle sarcasm?

You rarely detect it lexically. Context models catch some cases, and calibrated abstention, routing low confidence items to review, is usually cheaper than chasing the last few percent.

Interview Questions

Q1: How do you evaluate an aspect based sentiment system?

Score aspect extraction with span F1 first, then aspect sentiment with macro F1 on matched aspect pairs, because end to end accuracy conflates a tagging failure with a polarity failure.

Q2: Why can accuracy and macro F1 disagree sharply?

With a dominant class, accuracy rewards predicting it everywhere while macro F1 assigns equal weight to each class, so a collapsed minority class tanks macro F1 and leaves accuracy flat.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement