TExcelTAD

Label Quality

The introduction showed test accuracy falling as more training labels were flipped. Real datasets are never perfectly labelled: studies of popular benchmarks have found a few percent of wrong test labels even in carefully built ones such as ImageNet. Labels go wrong because the task is ambiguous, annotators are tired or rushed, guidelines are unclear, classes are confusable, automatic labelling rules misfire, or a label was correct once and the world changed. This lesson measures label quality in two ways: by agreement between annotators, and by asking a model which labels look suspicious.

Agreement between annotators

When two people label the same items, the share of items on which they agree, the observed agreement pop_o, is the first measure. But some agreement happens by chance: if both annotators say "positive" 90% of the time, they will agree on most items even when guessing. Cohen's kappa corrects for that:

κ=po−pe1−pe,pe=∑kp1,k p2,k\kappa = \frac{p_o - p_e}{1 - p_e}, \qquad p_e = \sum_{k} p_{1,k}\, p_{2,k}

where p1,kp_{1,k} and p2,kp_{2,k} are the shares of items that annotator 1 and annotator 2 put in class kk, so pep_e is the agreement expected by chance. κ=1\kappa = 1 is perfect agreement, κ=0\kappa = 0 is no better than chance. A rough, widely used reading (Landis and Koch): above 0.8 is very good, 0.6 to 0.8 substantial, 0.4 to 0.6 moderate, below 0.4 a sign that the task or the guidelines need work.

From scratch, and with scikit-learn:

python · try it yourself
import numpy as np
from sklearn.metrics import cohen_kappa_score, confusion_matrix

a1 = np.array(["spam", "ham", "ham", "spam", "ham", "ham", "ham", "spam", "ham", "ham",
               "ham", "ham", "spam", "ham", "ham", "ham", "ham", "ham", "spam", "ham"])
a2 = np.array(["spam", "ham", "ham", "ham", "ham", "ham", "ham", "spam", "ham", "spam",
               "ham", "ham", "spam", "ham", "ham", "ham", "ham", "ham", "ham", "ham"])

classes = ["ham", "spam"]
p_o = (a1 == a2).mean()
p_e = sum((a1 == k).mean() * (a2 == k).mean() for k in classes)
kappa = (p_o - p_e) / (1 - p_e)
print(f"observed agreement {p_o:.2f}, chance agreement {p_e:.3f}, kappa {kappa:.3f}")
print("scikit-learn kappa:", round(cohen_kappa_score(a1, a2), 3))
print(confusion_matrix(a1, a2, labels=classes))
observed agreement 0.85, chance agreement 0.650, kappa 0.571
scikit-learn kappa: 0.571
[[14  1]
 [ 2  3]]

The annotators agree on 85% of the 20 emails, which sounds good. But both call most emails "ham", so 65% agreement is expected by chance alone, and kappa is 0.571: moderate. Of the 6 emails that at least one of them called spam, they agree on only 3. The confusion matrix between the two annotators (rows annotator 1, columns annotator 2) shows where they disagree, which points to the guideline that needs a clearer rule. For more than two annotators, Fleiss' kappa and Krippendorff's alpha generalise the idea.

Finding suspicious labels with a model

You cannot afford to relabel everything twice. A trained model can point to the labels most worth checking: if a model that did not see a sample during training is confident that it belongs to a different class than its label says, the label is suspicious. "Did not see" is important, since a model trained on the sample may have memorised the wrong label. Cross-validated predictions provide exactly that: each sample is predicted by a model trained on the other folds. This is the core idea of confident learning (the cleanlab library implements a refined version).

The experiment below flips 5% of the labels of the digits dataset, then checks whether the model's suspicion finds them:

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y_true = load_digits(return_X_y=True)
rng = np.random.default_rng(0)
y = y_true.copy()
flipped = rng.choice(len(y), size=int(0.05 * len(y)), replace=False)
y[flipped] = (y[flipped] + rng.integers(1, 10, len(flipped))) % 10      # a different digit

model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))
proba = cross_val_predict(model, X, y, cv=5, method="predict_proba")
given = proba[np.arange(len(y)), y]                 # probability of the label we were given
suspects = np.argsort(given)[:len(flipped)]          # the least believable labels

hits = np.isin(suspects, flipped).sum()
print(f"flipped labels: {len(flipped)} of {len(y)}")
print(f"among the {len(suspects)} most suspicious labels, {hits} were flipped ({hits / len(suspects):.0%})")
for i in suspects[:5]:
    print(f"  sample {i:4}: label {y[i]}, model says {proba[i].argmax()} (p={proba[i].max():.2f}), true {y_true[i]}")
flipped labels: 89 of 1797
among the 89 most suspicious labels, 69 were flipped (78%)
  sample  527: label 7, model says 1 (p=0.93), true 1
  sample 1023: label 5, model says 4 (p=1.00), true 4
  sample  934: label 4, model says 9 (p=0.98), true 9
  sample 1419: label 3, model says 4 (p=1.00), true 4
  sample 1268: label 8, model says 4 (p=0.97), true 4

Of the 89 flipped labels, 69 are among the 89 least believable ones: a reviewer who checks just 5% of the dataset, chosen this way, finds 78% of the errors, where a random 5% sample would find about 5% of them. The five most suspicious samples were all flipped, and each time the model's guess is the true digit. In practice you send the suspects to a human reviewer instead of changing labels automatically: some of them are genuinely ambiguous samples or rare but correct cases, and the reviewer's decisions improve both the dataset and the guidelines.

Other label checks

Many label problems need no model at all:

python · try it yourself
import pandas as pd

ann = pd.DataFrame({
    "image": ["i1", "i2", "i3", "i4", "i5", "i6"],
    "label": ["cat", "dog", "Cat", "dgo", "dog", "cat"],
    "annotator": ["a", "a", "b", "b", "c", "c"],
    "seconds": [4.2, 3.8, 0.4, 0.3, 5.1, 4.6],
})
allowed = {"cat", "dog"}
print("labels outside the allowed set:", sorted(set(ann["label"]) - allowed))
print("median seconds per item by annotator:")
print(ann.groupby("annotator")["seconds"].median())
labels outside the allowed set: ['Cat', 'dgo']
median seconds per item by annotator:
annotator
a    4.00
b    0.35
c    4.85
Name: seconds, dtype: float64
  • Allowed values: typos (dgo) and case variants (Cat) create fake classes.
  • Speed: annotator b spends under half a second per item, far less than the others; their labels deserve a check, as do labels made at the end of long sessions.
  • Consistency rules: a multi-label tag set that includes both "indoor" and "outdoor", or a bounding box labelled "car" that is 3 pixels wide.
  • Drift over time: the share of each label per week; a sudden change may be a guideline change or a tool bug, not a change in the world.

Pitfalls

  • Treating labels as ground truth: estimate their error rate before you trust a score to the third decimal.
  • Using in-sample predictions to find label errors: a model that trained on a wrong label tends to agree with it. Use cross-validated predictions.
  • Auto-correcting labels: flagged labels go to review; some are hard but correct.
  • A noisy test set: label errors in the test set distort every comparison between models. Clean the test set most carefully of all.

Practice

  1. Two annotators agree on 90% of items. Each labels 95% of items as "normal". Is the agreement good?
Answer

Chance agreement is pe=0.95⋅0.95+0.05⋅0.05=0.905p_e = 0.95 \cdot 0.95 + 0.05 \cdot 0.05 = 0.905, so κ=(0.90−0.905)/(1−0.905)≈−0.05\kappa = (0.90 - 0.905)/(1 - 0.905) \approx -0.05: no better than chance. They agree mainly because both say "normal" almost always, and they hardly ever agree on which items are abnormal.

  1. Why does the model-based check use cross_val_predict instead of fitting once on all data and calling predict_proba?
Answer

A model trained on a sample can memorise that sample's (wrong) label and then confidently agree with it. Cross-validated predictions come from models that never saw the sample, so they judge the label independently.

Test yourself

What does Cohen's kappa correct the observed agreement for?

  1. The number of annotators
  2. Agreement that would happen by chance given each annotator's label shares
  3. The time spent per item
  4. Missing labels

A kappa of 0.25 between two trained annotators suggests…

  1. Excellent labels
  2. The task or the guidelines are unclear and need work
  3. The model is overfitting
  4. The classes are balanced

Which samples does the confident-learning idea flag as suspicious?

  1. Samples with the highest loss in the training set
  2. Samples where a model that did not train on them gives a low probability to their given label
  3. Samples with missing values
  4. The most recent samples