Sub topic 2
Where labels come from: star ratings, annotation, and weak labels
A sentiment classifier can only learn what its labels teach it. This chapter covers the three main ways to get labels (star ratings, human annotation, and weak labeling), the biases each one brings, and how to check label quality before you train anything.
It assumes you know basic Python, the idea of supervised learning (training data, test data, predictions), and have scikit-learn installed. You should also have settled your label scheme from the previous chapter: the classes, such as positive, negative, and neutral, and whether you label whole documents or sentences.
Why label quality sets the ceiling
Evaluation metrics compare predictions against labels. If the labels are noisy, inconsistent, or biased, the metrics measure agreement with that noise. A model can look weak because the labels are wrong. It can also look strong because it learned the same shortcut that produced the labels.
There are three common sources:
| Source | Cost | Typical noise | Best use |
|---|---|---|---|
| Star ratings | Almost free | Rating and text disagree, neutral is blurry | Large reviews corpus, first baseline |
| Human annotation | High | Annotator disagreement, guideline drift | Test sets, social posts, final training data |
| Weak labels | Low | Systematic bias from the rules used | Bootstrapping, pretraining, finding candidates for annotation |
Star ratings as labels
Review sites give you a label next to every text: the star rating. This is the cheapest way to get thousands or millions of labeled examples, and it is why many sentiment benchmarks are built on product and movie reviews.
Mapping stars to classes
You choose the mapping, and the choice changes the task. A common scheme for a 1 to 5 scale:
- 1 and 2 stars become negative.
- 3 stars becomes neutral.
- 4 and 5 stars become positive.
Another common scheme drops the 3-star reviews and keeps a binary positive/negative task. This is easier, since the hardest cases are gone, but a model trained this way has never seen neutral text. It will force every neutral post into one of two classes when you deploy it.
def stars_to_label(stars, keep_neutral=True):
"""Map a 1-5 star rating to 'neg', 'neu', or 'pos'.
Returns None for 3-star reviews when keep_neutral is False,
so the caller can drop them.
"""
if stars <= 2:
return "neg"
if stars >= 4:
return "pos"
return "neu" if keep_neutral else None
reviews = [
("Battery died in a week", 1),
("It is fine, does the job", 3),
("Best purchase this year", 5),
]
for text, stars in reviews:
print(stars, stars_to_label(stars), "|", text)What goes wrong with star labels
Star labels measure what the reviewer chose to click, not the sentiment of the sentence you will classify. Four problems come up repeatedly:
- Text and rating disagree. "Great product, but it arrived broken and support ignored me" may come with 2 stars. The text has positive and negative parts. The label covers the whole review.
- Reviews are about more than the text. A 1-star review can complain about shipping, price, or a seller. If your goal is sentiment toward the product, that label is partly wrong.
- The distribution is skewed. Most review sites show many 5-star and 1-star reviews and fewer in the middle. The 3-star class is also the least consistent, because people use it for "mixed", "average", and "I didn't care".
- Reviewer habits differ. One person's 4 stars is another's 5. Some reviews are fake or incentivized, and they push the labels toward extremes.
Check how the ratings are distributed before choosing a mapping. If 3-star reviews are 8 percent of the data, a neutral class built from them will be small, and the imbalance chapter will matter for you.
Human annotation
When you need labels that match your exact definition, people have to read the text and assign them. Annotation is slow and costs money, so plan it carefully.
Write guidelines first
Annotators disagree most when the instructions leave room. A usable guideline contains:
- A definition of each class, written in terms of what the author expresses, not what the annotator feels.
- Rules for hard cases: sarcasm, questions, news-style statements, mixed opinions, and text that is only factual.
- Three to five worked examples per class, including borderline ones.
- A rule for unusable text, such as "off-topic" or "not in the target language".
Pilot the guidelines on 50 to 100 items with two or three annotators. Compare their labels, discuss every disagreement, and revise the text. Doing this once usually removes most of the preventable disagreement.
Measure agreement
Raw percent agreement overstates quality, because annotators would agree sometimes by chance, especially when one class dominates. Cohen's kappa corrects for chance agreement between two annotators:
kappa = (p_o - p_e) / (1 - p_e)Here p_o is the observed agreement, and p_e is the agreement you would expect if each annotator labeled at random with their own label frequencies. A kappa of 1 is perfect agreement and 0 is chance level. Values from about 0.6 to 0.8 are often described as substantial agreement, though the exact cutoffs are a convention and not a law. For three or more annotators, Fleiss' kappa or Krippendorff's alpha extend the idea.
from sklearn.metrics import cohen_kappa_score
annotator_a = ["pos", "pos", "pos", "neg", "neg", "neu", "pos", "neg", "neu", "pos"]
annotator_b = ["pos", "pos", "neu", "neg", "neg", "neu", "pos", "pos", "neu", "pos"]
agreement = sum(a == b for a, b in zip(annotator_a, annotator_b)) / len(annotator_a)
kappa = cohen_kappa_score(annotator_a, annotator_b)
print("raw agreement:", agreement) # 0.8
print("cohen's kappa:", round(kappa, 3)) # 0.683Raw agreement is 0.8, but kappa is only 0.683, because half the items are positive and some agreement happens by chance. Kappa also shows you which class pairs cause the trouble. Build a confusion matrix between the two annotators (the same tool you will use for model evaluation) and look for pairs such as neutral versus positive.
Resolve disagreements
For the final dataset you need one label per item. The usual options are:
- Majority vote across three or more annotators.
- Adjudication, where a senior annotator decides each disagreement.
- Keeping the disagreement as a soft label, such as 2 of 3 annotators said positive, which some training methods can use directly.
Keep the items where annotators split. They are the hard cases, and they tell you where the model's errors will cluster. Report inter-annotator agreement alongside your model's score, because it works as a rough ceiling. A model that scores above human agreement on the test set is usually fitting annotation artifacts.
Crowd platforms and bias
Crowd workers are fast and cheap, but quality varies. Include a few gold items with known answers to catch inattentive workers. Also watch for annotator bias. Slang, dialects, and in-group language in social posts may be read as more negative by annotators who do not use them, and that bias goes into your labels.
Weak labels
Weak labeling means producing labels automatically with rules or other models instead of by hand. Each rule is a labeling function. It returns a class when it is confident enough, and None (abstain) when it is not. Typical rules for sentiment:
- Emoji or emoticons, such as a smile or a thumbs-down.
- Hashtags such as
#loveor#fail, removed from the text afterwards so the model does not just learn the hashtag. - Keywords, such as "refund" or "waste of money".
- Output from a lexicon tool like VADER, using only its confident scores.
from collections import Counter
POS_EMOJI = {"😀", "😍", "👍"}
NEG_EMOJI = {"😡", "👎", "😞"}
def lf_emoji(text):
if any(e in text for e in POS_EMOJI):
return "pos"
if any(e in text for e in NEG_EMOJI):
return "neg"
return None
def lf_positive_words(text):
return "pos" if any(w in text.lower() for w in ("love", "excellent")) else None
def lf_negative_words(text):
return "neg" if any(w in text.lower() for w in ("refund", "trash")) else None
LABELING_FUNCTIONS = [lf_emoji, lf_positive_words, lf_negative_words]
def weak_label(text):
votes = [v for v in (lf(text) for lf in LABELING_FUNCTIONS) if v is not None]
if not votes:
return None # nobody had an opinion
counts = Counter(votes).most_common()
if len(counts) > 1 and counts[0][1] == counts[1][1]:
return None # tie: leave for a human
return counts[0][0]
posts = [
"Love this phone 😍",
"Want a refund, this is trash 👎",
"Shipping took a week",
"Love the screen but I want a refund",
]
for post in posts:
print(weak_label(post), "|", post)The four posts get pos, neg, None, and None. The abstentions matter. The third post has no signal, and the fourth has conflicting signals. Forcing labels on them would add noise, and sending them to human annotators is a sensible use of the budget.
Risks of weak labels
Weak labels carry the bias of the rules. If positive posts are labeled by emoji, the model may learn "has emoji" and not "is positive", and it will then fail on positive posts without emoji. The labeled subset also differs from the whole population: posts that contain emoji are not typical posts.
Always audit a sample. Label 100 to 200 weakly labeled items by hand, compute the accuracy of the weak labels, and look at which kinds of text they get wrong. Keep your test set hand-labeled and never use weak labels there.
Checklist before you train
- State the mapping from source signal to class, and keep it in code, not in your head.
- Print the class distribution.
- Read 50 random labeled items. If you disagree with more than a few labels, the labels need work.
- For human labels, report agreement. For weak labels, report audited accuracy.
- Split train and test before any rule tuning, and remove duplicate or near-duplicate texts across the split. Reviews are often copied, and duplicates inflate scores.
- Remove label leakage: stars, rating words like "5 stars", and labeling hashtags must not remain in the text the model sees.
Exercise
Two annotators label 100 posts. They agree on 90, so raw agreement is 0.90. Of the 100 posts, both label about 90 as positive. Why might Cohen's kappa still be low, and what does that tell you?
Show answer
With 90 percent of the items positive, the annotators would agree on roughly 0.9 × 0.9 + 0.1 × 0.1 = 0.82 of items by chance alone, so p_e is about 0.82. Kappa is (0.90 − 0.82) / (1 − 0.82), which is about 0.44. High raw agreement is mostly produced by class imbalance and says little about whether they agree on the rare negative posts. Look at the confusion matrix between annotators and revise the guidelines for the minority class.
Exercise
You build a training set by labeling posts positive when they contain a smiling emoji and negative when they contain an angry emoji. The model scores 95 percent on a held-out part of the same data but poorly on posts without emoji. Name the problem and one fix.
Show answer
The labels come from the emoji, so the model learned emoji as a shortcut, and the held-out part has the same shortcut. The labeled posts are also not representative of posts without emoji. Fixes include removing the emoji from the text before training, hand-labeling a test set of typical posts without relying on the rule, and adding other labeling functions or human labels so the model must use the words.