Sub topic 4
A quick baseline with a sentiment lexicon (VADER)
This chapter assumes you can run Python scripts, install packages with pip, and read a dictionary of scores. It also assumes you know the labels from the first chapter: positive, negative, and neutral. You do not need any machine learning for this chapter. A lexicon scorer is the cheapest baseline you can build, and every later model should be compared against it.
What a lexicon method does
A sentiment lexicon is a list of words, each with a number that says how positive or negative the word is. A lexicon method looks up each word in the text and combines the numbers into one score. It has no training step and needs no labeled data.
VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule set built for short, informal text such as tweets and reviews. It has three properties that matter in practice:
- A rated lexicon. It has about 7,500 entries. Each has a valence between -4 (extremely negative) and +4 (extremely positive), averaged over several human raters.
- It covers social text. The lexicon includes emoticons such as
:)and:(, and slang such aslolandmeh. - It applies rules after lookup. The rules adjust the raw word scores using punctuation, capitalization, degree words, negation, and the word "but".
Install it with pip install vaderSentiment.
How the score is computed
The rules are the part that makes VADER better than a plain word count:
- Capitalization. An all-caps word in a text that also has lowercase words gets extra intensity.
GREATscores higher thangreat. - Exclamation marks. Each
!adds a small boost, up to a limit. Question marks add a smaller boost. - Degree modifiers.
very,extremely, andreallyraise the next word's valence.slightlyandbarelylower it. - Negation. A negating word such as
notorneverin the three words before a sentiment word reduces and flips its valence. - "But". Sentiment before
butis weighted down and sentiment after it is weighted up.
After the rules, VADER sums the valences and normalizes the sum with x / sqrt(x² + 15). This squeezes any sum into the range -1 to +1. The result is the compound score.
polarity_scores returns four numbers:
| Key | Meaning |
|---|---|
| `neg` | Share of the text's sentiment weight that is negative |
| `neu` | Share that is neutral |
| `pos` | Share that is positive |
| `compound` | Normalized overall score from -1 to +1 |
The neg, neu, and pos values add up to about 1. They are proportions, not probabilities. Use compound when you need a single decision.
Scoring text and choosing a label
The usual thresholds are:
- Compound score of +0.05 or higher: positive.
- Compound score of -0.05 or lower: negative.
- Anything between: neutral.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
scores = analyzer.polarity_scores("The battery life is great, but the screen is awful.")
print(scores) # dict with 'neg', 'neu', 'pos', and 'compound'
compound = scores["compound"]
if compound >= 0.05:
label = "positive"
elif compound <= -0.05:
label = "negative"
else:
label = "neutral"
print(label)This sentence mixes praise and criticism. VADER cannot say the sentence is about two different things. It returns one number, and the but rule pushes that number toward the second clause. That is the first limit of the method. We return to it in the aspect-based chapter.
Seeing the rules at work
Run the same message with small changes and watch the compound score move. The exact numbers depend on the installed version, so compare the direction of change rather than the values.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
variants = [
"The food was good.",
"The food was very good.",
"The food was GOOD!!!",
"The food was not good.",
"The food was good, but the service was slow.",
"The food was good :)",
]
for text in variants:
compound = analyzer.polarity_scores(text)["compound"]
print(f"{compound:+.3f} {text}")Expect very good and GOOD!!! to score higher than plain good. Expect not good to be negative. Expect the but sentence to score lower than the plain sentence, because slow gets extra weight.
Preparing text for VADER
The normalization chapter showed a function that replaces links and mentions and strips the hash from hashtags. VADER works best when you preserve the signals its rules read:
- Do not lowercase. The capitalization rule needs the original case.
- Do not strip punctuation. The exclamation mark rule and the emoticon entries need it.
- Keep emoticons and emojis. VADER's lexicon includes emoticons. Emojis are translated to their text names, so the emoji
😍is read as a word describing it. - Remove or replace URLs and mentions. They carry no sentiment and can only add noise.
Here is the pipeline with normalization first and scoring second.
import re
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
def normalize_post(text):
text = re.sub(r"https?://\S+", "<url>", text)
text = re.sub(r"@\w+", "@user", text)
text = re.sub(r"#(\w+)", r"\1", text)
return re.sub(r"\s+", " ", text).strip()
def vader_label(text, threshold=0.05):
compound = analyzer.polarity_scores(normalize_post(text))["compound"]
if compound >= threshold:
return "positive"
if compound <= -threshold:
return "negative"
return "neutral"
posts = [
"Loving the new phone!! @shopfan #bestbuy https://example.com/x",
"Third outage this week. Unbelievable.",
"Delivery arrives on Tuesday.",
]
for post in posts:
print(vader_label(post), "|", post)The first post should come out positive. The second is a real complaint, but VADER may not call it negative, because Unbelievable is ambiguous. The third has no sentiment words, so it should be neutral.
Adapting the lexicon to your domain
The lexicon is a plain Python dictionary at analyzer.lexicon. You can add or change entries to match your domain. This is the main tuning knob VADER offers.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
text = "Support said refund denied, still waiting."
print("before:", analyzer.polarity_scores(text)["compound"])
analyzer.lexicon.update({"refund": -1.0, "denied": -2.5, "waiting": -0.8})
print("after: ", analyzer.polarity_scores(text)["compound"])A few cautions apply when you edit the lexicon:
- Entries are single tokens. VADER does not read multi-word phrases such as
battery drainas a unit. - Valences should sit on the same -4 to +4 scale as the existing entries.
- A word can change meaning between domains.
sickis bad in a health forum and may be praise in a skateboarding community. Check how a word is used in your data before you change it. - Every edit changes scores across the whole dataset. Re-run your evaluation after each change.
Where VADER works and where it fails
VADER is a good first model when:
- You have no labeled data yet, and you need something to look at today.
- Texts are short and written in plain, direct language.
- You need a transparent score. You can print which tokens contributed.
- You want a reference to measure later models against.
It is a poor fit when:
- The text is sarcastic. "Great, another delay" has a positive word and a negative meaning. VADER scores the word.
- Sentiment depends on context. "The plot was unpredictable" is praise for a thriller and a complaint about a bank's interest rate.
- The text is long. Sentiment words from different parts of a review get averaged together, and the compound score drifts toward the extremes or the middle without telling you much.
- Negation is distant. The three-word window misses cases such as "I would never say this product was good."
- The language is not English. The lexicon is English. Applying it to another language gives mostly zero scores and a flood of
neutral. - The text states facts that are bad news. "My flight was cancelled" has no sentiment word, so VADER calls it neutral.
Checking VADER against labeled data
Never judge a baseline by reading a few outputs. Score a labeled set and compare. This small example computes accuracy, and the evaluation chapter replaces accuracy with precision, recall, and F1.
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
labeled = [
("Absolutely love it", "positive"),
("Fantastic quality and fast shipping", "positive"),
("Terrible, broke after one day", "negative"),
("Waste of money, very disappointed", "negative"),
("Great, another delay", "negative"),
("It arrived on Monday", "neutral"),
]
def predict(text):
compound = analyzer.polarity_scores(text)["compound"]
if compound >= 0.05:
return "positive"
if compound <= -0.05:
return "negative"
return "neutral"
correct = 0
for text, gold in labeled:
pred = predict(text)
correct += pred == gold
flag = "ok " if pred == gold else "ERR"
print(flag, gold, "->", pred, "|", text)
print("accuracy:", correct / len(labeled))Look at the errors line by line. The sarcastic Great, another delay is the usual one. A pattern in the errors tells you whether to edit the lexicon, change the thresholds, or move to a trained model.
Common mistakes
- Lowercasing and stripping punctuation before scoring. This removes the signals VADER's rules depend on.
- Using the
posscore as "probability of positive". It is a proportion of the text's weight. - Tuning the thresholds on your test set. Choose them on a separate validation set, or keep ±0.05 as a fixed default.
- Running VADER on long documents as one string. Split into sentences, score each, and aggregate with a rule you can explain.
- Reporting results without a baseline for the neutral class. In many datasets, neutral is the hardest class for lexicons.
Exercise
A review reads "The camera is NOT bad at all!!!" Name two VADER rules that act on this text and say what each does to the score. Then say why a VADER-based pipeline that lowercases text before scoring would change the result.
Show answer
The negation rule sees NOT before bad and flips and reduces the negative valence of bad, which moves the score toward positive. The capitalization and exclamation mark rules add intensity, so the shouted NOT and the three ! make the score stronger in the direction already set. Lowercasing removes the capitalization signal, so the emphasis from NOT is lost and the score becomes weaker. The negation rule still works on lowercase not, but the intensity from capitalization does not.
Exercise
You run VADER on 1,000 support tickets and 70% come back neutral. Describe a check that tells you whether the model is working or whether the lexicon is missing the vocabulary of your domain, and one fix you could try.
Show answer
Count how many neutral predictions have a compound score of exactly 0.0, and read a sample of them. If most are tickets that clearly express frustration or praise using words such as "refund", "outage", or "denied", the lexicon is missing domain vocabulary. A fix is to add those words to analyzer.lexicon with valences on the -4 to +4 scale, then re-run the evaluation on a labeled set to confirm accuracy improved without hurting other classes. If many are factual statements, the neutral label may be correct.