Sub topic 13
Going Beyond One Label: Aspect-Based Sentiment
This chapter assumes you can run Python, have scored text with VADER, and know how a TF-IDF classifier is evaluated with precision, recall, and F1. It also assumes you have seen a pretrained transformer used through the Hugging Face pipeline API.
Why one label is not enough
Consider this review: "The battery life is great, but the screen is awful." A document-level classifier must give it one label. Positive misses the complaint. Negative misses the praise. Neutral describes neither opinion. The review holds two opinions about two different things.
Aspect-based sentiment analysis (ABSA) attaches sentiment to specific aspects of an entity. An aspect is a part, feature, or property that people evaluate, such as battery, screen, price, delivery, or staff. The output changes from one label per text to a set of pairs, such as (battery, positive) and (screen, negative).
ABSA is useful when the reader wants to act on the result. A product team cares less that 40% of reviews are negative than that most negative reviews mention the charger. Support teams can route complaints by aspect. Analysts can track one aspect over time.
The subtasks of ABSA
ABSA is a bundle of related tasks. Papers and tools often cover only some of them, so check which ones a tool covers.
| Subtask | Question it answers | Example output |
|---|---|---|
| Aspect term extraction | Which words name something being evaluated? | "battery life", "screen" |
| Aspect category detection | Which predefined category does the text touch? | BATTERY, DISPLAY |
| Aspect sentiment classification | What is the polarity toward a given aspect? | screen → negative |
| Opinion term extraction | Which words express the opinion? | "great", "awful" |
Aspect terms are words that appear in the text. Aspect categories come from a fixed list that you define. A review can mention "the charger" (a term) and belong to the BATTERY category even though the word "battery" never appears.
The most practical setup for many projects is to define the category list yourself and then classify sentiment per category. It avoids open-ended term extraction, which needs labeled spans. It also gives stable categories you can count across thousands of reviews.
How the pieces fit together
The usual pipeline has three stages. You find where aspects are mentioned, isolate the text that talks about each one, and classify sentiment for that piece or for the aspect together with the full text.
The normalization step from earlier chapters still applies. Keep punctuation and negation words, because they carry sentiment. Do not strip stopwords like "not" or "but" before splitting, because "but" is often the cue that sentiment is about to change.
A rule-based baseline
A baseline helps you see the problem before you reach for a large model. This version has three parts:
- A hand-written aspect dictionary maps each category to trigger words.
- A clause splitter cuts the text at contrast words and sentence punctuation.
- VADER scores each clause that mentions an aspect.
import re
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
ASPECTS = {
"battery": ["battery", "charge", "charging", "charger"],
"screen": ["screen", "display", "brightness"],
"price": ["price", "cost", "expensive", "cheap"],
"delivery": ["delivery", "shipping", "package"],
}
analyzer = SentimentIntensityAnalyzer()
CLAUSE_SPLIT = re.compile(r"\b(?:but|however|although|though|yet)\b|[.;!?]", re.I)
def label_from_compound(compound):
if compound >= 0.05:
return "positive"
if compound <= -0.05:
return "negative"
return "neutral"
def aspect_sentiment(text):
results = []
for clause in CLAUSE_SPLIT.split(text):
clause = clause.strip()
if not clause:
continue
lowered = clause.lower()
for aspect, words in ASPECTS.items():
if any(re.search(rf"\b{re.escape(w)}\b", lowered) for w in words):
compound = analyzer.polarity_scores(clause)["compound"]
results.append((aspect, label_from_compound(compound), clause))
return results
review = "The battery life is great, but the screen is awful. Shipping was slow."
for aspect, label, clause in aspect_sentiment(review):
print(f"{aspect:9s} {label:9s} | {clause}")The splitter separates the praise from the complaint, so each aspect gets its own score. If you scored the whole review once, the two opinions would partly cancel in the compound score.
This baseline fails in predictable ways:
- It misses aspects named by words you did not list, such as "juice" for battery.
- It breaks when one clause covers two aspects, as in "great screen and battery".
- It fails when the opinion sits in a different sentence from the aspect. In "The screen arrived scratched. Awful." the word "Awful" is in a clause with no aspect.
- It inherits every weakness of VADER, including sarcasm and domain vocabulary.
It still does one useful job. It gives you a floor to compare against, and its errors show what your data looks like.
Using a pretrained ABSA model
A stronger approach treats aspect sentiment as sentence-pair classification. The model reads the full review and the aspect term together and predicts the polarity toward that aspect. Because the whole sentence is visible, the model can use context that clause splitting throws away.
from transformers import pipeline
classifier = pipeline(
"text-classification",
model="yangheng/deberta-v3-base-absa-v1.1",
)
review = "The battery life is great, but the screen is awful."
for aspect in ["battery life", "screen", "price"]:
result = classifier({"text": review, "text_pair": aspect})
print(f"{aspect:12s} -> {result['label']} ({result['score']:.3f})")Run this on a machine that can download the model. The exact label strings depend on the model's configuration, so print them before writing code that matches on them.
Notice what happens for "price", which the review never mentions. The model still returns a label, because a classifier must pick from its output classes. In practice this means the model can give a confident-looking answer about an aspect that is not in the text. Your pipeline must decide separately whether an aspect is mentioned, for example with the dictionary above, and only then ask for its polarity.
Choosing an approach
| Approach | Needs labeled data | Handles implicit aspects | Typical failure |
|---|---|---|---|
| Dictionary plus lexicon | No | No | Missed aspect words, split errors |
| Dictionary plus trained classifier per clause | Clause-level labels | No | Mixed opinions in one clause |
| Pretrained ABSA pair model | No for a first test | Partly | Wrong output for absent aspects, domain shift |
| Fine-tuned pair model | Aspect-level labels | Yes, if the labels include them | Annotation cost, label noise |
Start with the cheapest option that answers your actual question. If a team only needs to know whether complaints about delivery are rising, a dictionary of delivery words and a clause-level score may be enough. If you need high accuracy on subtle opinions, plan for aspect-level annotation, because published ABSA datasets cover narrow domains such as laptops and restaurants. That is the same domain-shift concern from earlier chapters.
Annotation and evaluation
Aspect-level labels cost more than document-level ones. An annotator must mark each aspect and its polarity, so agreement between annotators is lower. Write guidelines for the hard cases:
- Is "it works" an opinion about a specific aspect, or about the product overall?
- Does "expensive but worth it" count as negative, positive, or mixed for price?
- Is a sentence like "the screen is 6 inches" an opinion or just a fact?
Evaluate in layers, and report each layer separately:
- Aspect detection: precision and recall of finding which aspects are mentioned.
- Polarity given a correct aspect: accuracy or macro-F1 over the sentiment labels.
- End to end: a prediction counts only if both the aspect and its polarity are right.
The end-to-end score is always lower, and mixing the layers hides where the system is failing. A system with 95% polarity accuracy on gold aspects can still perform badly if it misses half the aspects.
Consider the "conflict" or "mixed" cases as well. When a single aspect receives both praise and criticism in the same review, a three-class scheme forces a wrong choice. Some ABSA datasets add a conflict label. Decide early whether your label scheme needs one, as you did for the neutral class.
Aggregating results
Per-aspect predictions become useful once you aggregate them. A simple table counts reviews by aspect and polarity, and you can compute a net score per aspect as the share of positive mentions minus the share of negative mentions. Two cautions apply:
- Report the number of mentions beside every score. A net score of -0.8 from five mentions is weak evidence.
- Keep the review or post ID with each prediction so you can read examples behind any number. That supports the error analysis work from the previous chapters.
Exercise
A review says "Fast delivery, but the box was crushed and the charger stopped working." Using the clause-splitting baseline from this chapter with the ASPECTS dictionary shown, which aspects does it detect, and what is one way it could still go wrong?
Show answer
Splitting at "but" and "." gives the clauses "Fast delivery", "the box was crushed and the charger stopped working". The first matches nothing in the dictionary (the word "delivery" matches the delivery aspect, so delivery is detected as positive), and the second matches battery through the word "charger". Note that "box" is not in any list, so the crushed package is not attributed to delivery. The charger clause would be scored as negative, which is correct, but the "crushed box" complaint is attributed to battery only through the shared clause. This shows the main failure mode: one clause covering two aspects, and aspect words missing from the dictionary.
Exercise
Why can a sentence-pair ABSA model return a confident label for an aspect that is not mentioned in the text, and how do you prevent it from corrupting your counts?
Show answer
A classifier must output one of its trained classes for any input, so it produces a label even when the aspect is absent. Prevent this with a separate aspect-detection step, such as a dictionary or a trained category detector, and only run polarity classification on aspects that are detected. You can also add an explicit "not mentioned" class during fine-tuning.
Exercise
A system reports 94% polarity accuracy given gold aspects but misses 40% of aspect mentions. How should you report its performance?
Show answer
Report aspect detection precision and recall, polarity accuracy or macro-F1 given correct aspects, and an end-to-end score where both must be right. The end-to-end score will be much lower than 94% because every missed aspect counts as an error, so reporting only the polarity figure would overstate performance.