AI Wiki中文/EN

Sentiment analysis: whose opinion, about which aspect?

情感分析

Separate targets and conflicting opinions, inspect explicit composition rules, and retain sarcasm and scope failures.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Good food and bad service are not one neutral opinion

The invented review food good but service bad contains two opinions about different targets. Adding a positive word score and a negative word score can give0 while losing both useful conclusions. Sentiment analysis needs a prediction unit: the whole document, a sentence, an expressed aspect term, or a predefined aspect category.

Pang, Lee and Vaithyanathan’s2002 study considers overall movie-review sentiment and compares word-list baselines with learned text classifiers. SemEval-2014 Task4 separates aspect-term extraction, polarity of supplied terms, category detection and polarity of supplied categories. These tasks should not share an unlabeled accuracy number. Review-level task Four aspect tasks

A polarity label is also not an emotion diagnosis or an objective measure of product quality. It describes an interpretation under an annotation policy. The program below uses supplied aspect words and explicit local rules so that every contribution and failure is visible.

Food can be good while service is bad. Separate positive and negative evidence keeps conflict distinct from neutrality; the rule-based example deliberately retains its negation and sarcasm failures.
Food can be good while service is bad. Separate positive and negative evidence keeps conflict distinct from neutrality; the rule-based example deliberately retains its negation and sarcasm failures.

Keep the target and opposing evidence visible

Define what the labels mean

For a given aspect, use four labels: positive, negative, neutral and conflict. SemEval’s conflict label applies when positive and negative opinions are both expressed about that aspect; its term-polarity task supplies the aspect terms. Detecting implicit categories is a separate task. SB1–SB4 definitions

Our rule system accumulates positive and negative contributions separately. If an opinion word has base valuev_i, an adjacent intensity modifier multiplies it bym_i, and an odd number of recognized preceding negations flips its sign:

si=vimi(−1)qi mod 2.s_i=v_i m_i(-1)^{q_i\bmod2}.

These are invented teaching weights and rules, not calibrated probabilities or a reproduction of a named sentiment library. The default negation window contains at most three preceding tokens in the same clause. Punctuation andbut end that clause; an immediately precedingvery multiplies by1.5 andslightly by0.5.

Assign each scored word to the closest supplied aspect mention in the same clause, within six token positions. Ties prefer an earlier mention. If no eligible target exists, retain it as an unassigned opinion rather than invent an implicit aspect. Repeated mentions of the same aspect accumulate together.

Pa=∑i: owner(i)=amax⁡(si,0),Na=∑i: owner(i)=amax⁡(−si,0),neta=Pa−Na.P_a=\sum_{i:\,owner(i)=a}\max(s_i,0),\qquad N_a=\sum_{i:\,owner(i)=a}\max(-s_i,0),\qquad net_a=P_a-N_a.

The decision table distinguishes no directional evidence from both directions:

label(a)={neutral,Pa=Na=0,positive,Pa>0, Na=0,negative,Pa=0, Na>0,conflict,Pa>0, Na>0.label(a)=\begin{cases} neutral,&P_a=N_a=0,\\ positive,&P_a>0,\ N_a=0,\\ negative,&P_a=0,\ N_a>0,\\ conflict,&P_a>0,\ N_a>0. \end{cases}

Thusfood good but food bad has positive2, negative2 and net0, yet is conflict. food arrived has no recognized sentiment evidence and is neutral under this baseline. The latter label does not prove that a reader would find no opinion in a richer context.

Local rules expose composition errors

not good flips the word’s contribution;not very good gives2×1.5×(−1)=−3. Butnot only good is not ordinarily a negative evaluation. The same small window flips it anyway. Double-negation parity is likewise a declared arithmetic rule, not a general theory of how people interpret negation.

A learned document classifier can replace fixed word weights or encode larger context, but it still needs a target definition, suitable labels and held-out evaluation. Pang et al.’s bag-feature setup is one historical learned alternative. Its third exploratory word-list baseline used information from the test data; such a development exercise must not be described as a sealed-test result. Baselines and feature methods

Run the rules and keep the counterexamples

The complete block uses only Python3.12’s standard library. Aspect terms are a supplied lowercase, single-word inventory. Tokenization preserves source intervals and otherwise unrecognized non-space characters, but does not implement Chinese word segmentation or a multilingual model.

"""Original transparent aspect-polarity rules, with deliberate failure examples."""
import json,re
LEXICON={'good':2.,'great':3.,'excellent':3.,'bad':-2.,'terrible':-3.,'slow':-1.5,'boring':-2.}
NEGATIONS={'not','never','no'};BOOSTERS={'very':1.5,'slightly':.5};LABELS=('positive','negative','neutral','conflict')


def polarity(positive,negative):
    if positive and negative:return 'conflict'
    if positive:return 'positive'
    if negative:return 'negative'
    return 'neutral'


def analyze(text,aspects=('food','service','battery','screen'),negation_window=3):
    if not isinstance(text,str) or len(text)>10000:raise ValueError('text must have at most10000 characters')
    if type(negation_window) is not int or not 0<=negation_window<=5:raise ValueError('negation window must be0..5')
    if not aspects or any(not isinstance(a,str) or not re.fullmatch('[a-z]+',a) for a in aspects) or len(set(aspects))!=len(aspects):
        raise ValueError('unique lowercase single-word aspect terms required')
    tokens=[];clause=0
    for match in re.finditer(r"[A-Za-z]+(?:'[A-Za-z]+)?|[^\s]",text):
        word=match[0].casefold();tokens.append({'word':word,'span':list(match.span()),'clause':clause})
        if word in {'.',',','!','?',';','but'}:clause+=1
    mentions=[(i,t['word'],t['clause']) for i,t in enumerate(tokens) if t['word'] in aspects]
    totals={a:[0.,0.] for _,a,_ in mentions};evidence=[]
    for i,token in enumerate(tokens):
        word=token['word']
        if word not in LEXICON:continue
        previous=[t['word'] for t in tokens[max(0,i-negation_window):i] if t['clause']==token['clause']]
        negated=sum(w in NEGATIONS for w in previous)%2==1
        modifier=BOOSTERS.get(tokens[i-1]['word'],1.) if i and tokens[i-1]['clause']==token['clause'] else 1.
        value=LEXICON[word]*modifier*(-1 if negated else 1)
        candidates=[(abs(i-j),0 if j<i else 1,j,a) for j,a,c in mentions if c==token['clause'] and abs(i-j)<=6]
        owner=min(candidates)[3] if candidates else None
        if owner is not None:totals[owner][0 if value>0 else 1]+=abs(value)
        evidence.append({'word':word,'span':token['span'],'base':LEXICON[word],'modifier':modifier,'negated':negated,'value':value,'aspect':owner})
    result={a:{'positive':p,'negative':n,'net':p-n,'label':polarity(p,n)} for a,(p,n) in sorted(totals.items())}
    return {'tokens':tokens,'aspects':result,'evidence':evidence,'unassigned_opinions':sum(e['aspect'] is None for e in evidence)}


def metrics(gold,predicted):
    if len(gold)!=len(predicted) or any(v not in LABELS for v in list(gold)+list(predicted)):raise ValueError('aligned supported labels required')
    classes={}
    for label in LABELS:
        g=gold.count(label);p=predicted.count(label);tp=sum(a==b==label for a,b in zip(gold,predicted))
        classes[label]={'tp':tp,'fp':p-tp,'fn':g-tp,'f1':2*tp/(g+p) if g+p else 0.}
    return {'accuracy':sum(a==b for a,b in zip(gold,predicted))/len(gold) if gold else 0.,
            'macro_f1':sum(c['f1'] for c in classes.values())/len(LABELS),'classes':classes}


def demo():
    # Gold intent is explicitly chosen for these invented examples; no corpus claim.
    cases=[('food is good','food','positive'),('service is not good','service','negative'),
           ('battery lasts hours','battery','neutral'),('food good but food bad','food','conflict'),
           ('service is not only good','service','positive'),('service great another delay','service','negative')]
    results=[];raw=[];gold=[];pred=[]
    for text,target,label in cases:
        full=analyze(text);baseline=analyze(text,negation_window=0);gold.append(label);pred.append(full['aspects'][target]['label']);raw.append(baseline['aspects'][target]['label'])
        results.append({'text':text,'target':target,'gold_intent':label,'prediction':pred[-1],'without_negation':raw[-1],'analysis':full})
    return {'cases':results,'with_negation':metrics(gold,pred),'without_negation':metrics(gold,raw),
            'mixed_aspects':analyze('food good but service bad'),'intensifier':analyze('service is not very good'),
            'scope':'Given aspect-term inventory, local English lexicon/window rules. No target extraction benchmark, learned classifier, sarcasm detector or VADER reproduction.'}

if __name__=='__main__':print(json.dumps(demo(),indent=2))

The six invented cases have explicitly chosen intended labels. Four are classified as intended. The remaining cases preserve two errors: not only good is incorrectly negative, and the fragment service great another delay, whose intended reading is sarcastically negative, is incorrectly positive. Without the surrounding intent, real annotators could also disagree about such short text.

The output includes every sentiment word, source interval, base score, modifier, negation decision and assigned aspect. It also includes an ablation with the negation window set to0. Both variants have accuracy4/6, but they make different mistakes: removing negation breaksnot good while repairingnot only good. One headline number would hide that exchange.

With the window enabled, macroF1 over the four declared labels is0.75; without it, macroF1 is2/3. These scores belong to this development fixture. They do not establish that this window improves reviews in general.

A sentiment score needs a stated interpretation

The closest-target rule can attach a sentiment word to the wrong aspect. Clause boundaries can also prevent an opinion from inheriting a target mentioned earlier. delicious but expensive contains no supplied aspect word, so this program returns no aspect predictions. It does not implement the implicit category detection that SemEval treats separately. Aspect categories

Sarcasm, quotation, comparison, domain-specific word meanings and a speaker’s actual target can defeat local lexical rules. A text may quote somebody else’s praise while rejecting it. Polarity scores should therefore be attached to their evidence and scope, not treated as a personality measurement or verified fact about the target.

For a classifier, report the annotation unit and per-class errors. Accuracy is the fraction of correct labels. Our additional macroF1 treats each declared class equally and uses0 when its F1 denominator is zero:

Fmacro=1∣C∣∑c∈C2TPc2TPc+FPc+FNc.F_{macro}=\frac1{|\mathcal C|}\sum_{c\in\mathcal C}\frac{2TP_c}{2TP_c+FP_c+FN_c}.

SemEval’s supplied-term and supplied-category polarity subtasks use accuracy; our four-class macro score is an additional teaching diagnostic, not their official headline score. Do not compare aspect extraction F1 with polarity accuracy as if they measured one task. Task evaluation excerpt

The text cap is10,000 characters. For n tokens and m aspect mentions, this straightforward implementation can scan m candidates for each opinion word, giving O(n(m+1)) worst-case work including token scanning. Fixed local windows add bounded work per opinion; stored tokens and evidence use O(n+m) space. The implementation favors inspectability over an optimized nearest-target data structure.

Ask what changed, not just whether the score rose

  1. Why does net0 not determine whether an aspect is neutral or conflicting?

Answer: Positive2 and negative2 yield net0 but contain opposing opinions. Positive0 and negative0 also yield net0 but contain no recognized directional evidence. Keeping both totals preserves the distinction.

  1. Compute the rule contribution forservice is not very good. Then explain why the same negation window mishandlesnot only good.

Answer: The contribution is2×1.5×(−1)=−3. The window only counts recognized negations; it does not understand thenot onlyconstruction. Its arithmetic can be correct while its language interpretation is wrong.

  1. Both window settings get four of six cases correct. Can the settings be considered equivalent?

Answer: No. They exchange errors onnot goodandnot only good; their class-level error counts and macroF1 also differ. Compare the confusion structure and the kinds of language affected, not accuracy alone.

  1. A review saysdelicious but expensivewithout naming food or price. Is an empty aspect result proof that the review has no sentiment?

Answer: No. It exposes the supplied-term inventory’s limitation. Inferring food and price categories is an additional task requiring its own labels and evaluation. Adding rules for these two known words turns them into development cases, not fresh test evidence.

Document labels and aspect labels answer different questions

The2002 movie-review study makes overall sentiment a text-classification problem; the2014 aspect task makes target detection and target polarity separate parts of the contract. They provide useful reference points without making either dataset a universal definition of sentiment. Our local-rule example isolates composition and target assignment; it does not reproduce either paper’s systems. Document sentiment Aspect definitions

Continue with text classification for train/validation/test pipelines, tokenization for input units, and precision and recall for error accounting. Computational pragmatics addresses why literal words may differ from a speaker’s intended message.

Make a prediction, then check

The same aspect receives positive strength2 and negative strength2. Which label does the declared policy choose?

Choose one answer

Learning objectives

  • Define opinion target, granularity and annotation policy before scoring.
  • Separate neutral sentiment from conflicting positive and negative evidence.
  • Inspect local negation, intensification and aspect assignment rules.
  • Preserve sarcasm/composition failures and compare class-sensitive metrics.

Prerequisites & connections

Explore related knowledge →

References

  1. Thumbs up? Sentiment Classification using Machine Learning Techniques
    Bo Pang, Lillian Lee and Shivakumar Vaithyanathan · 2002
  2. SemEval-2014 Task4: Aspect Based Sentiment Analysis
    Maria Pontiki, Dimitris Galanis, John Pavlopoulos, Harris Papageorgiou, Ion Androutsopoulos and Suresh Manandhar · 2014

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Single AI author checked four paired equations and four explained exercises against scoped Pang2002 and SemEval2014. Given aspects, local English lexicon, clause/window negation, modifier factors and separate positive/negative evidence are explicit. Conflict versus neutral at net zero, not-only failure, assigned sarcastic intent and six-case ablation are retained. Both accuracies4/6 with different errors; macro F1 .75 versus2/3; intensified negative score-3 checked. Unpublished prerequisite links point to the catalogue. No VADER, trained sarcasm detector or ABSA benchmark reproduction.

  • Single AI author checked four paired equations and four explained exercises against scoped Pang2002 and SemEval2014. Given aspects, local English lexicon, clause/window negation, modifier factors and separate positive/negative evidence are explicit. Conflict versus neutral at net zero, not-only failure, assigned sarcastic intent and six-case ablation are retained. Both accuracies4/6 with different errors; macro F1 .75 versus2/3; intensified negative score-3 checked. Unpublished prerequisite links point to the catalogue. No VADER, trained sarcasm detector or ABSA benchmark reproduction.
  • Four original computed SVGs bind exact bilingual MDX. Eleven figure checks and36 isolated language/width cases with four fallback fonts passed; six actual desktop/mobile screenshots inspected by this AI author. This is separate from final full-page browser acceptance, with no human peer-review claim.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.