Label correctness testing
Why This Matters
In supervised learning, the labels are the specification. A model trained on labels that say “approve” for an applicant who should be rejected learns to approve such applicants. A test set with wrong labels marks correct predictions as errors and wrong ones as correct. Labels are made by people, often in a hurry, sometimes with unclear guidelines, and their errors pass straight into the model and into every metric you calculate.
What you will learn
- The approaches to test labels: expert review, multiple annotation, risk-based prioritisation, distribution analysis, rules, and model-based analysis
- How to measure agreement between annotators with Cohen’s kappa
- How to let a model point at suspicious labels, in code, and why a person still has to decide
Syllabus: AI-5.1.6.
Approaches
- Expert review. Domain experts, or trained annotators, review a sample of the labels against the labelling guidelines. The guidelines themselves are reviewed too: ambiguous guidelines produce inconsistent labels.
- Multiple annotation. Several annotators label the same data independently. Where they disagree, someone investigates. Inter-annotator agreement (IAA) is measured with percentage agreement or Cohen’s kappa. Low agreement points to unclear guidelines, genuinely ambiguous data, or poor annotators.
- Risk-based prioritisation. Labelling everything twice is expensive. Spend the effort where it matters: ambiguous data points near the class boundary, and high-impact or safety-critical data.
- Data distribution analysis. Compare the label distribution with comparable datasets. If 40% of transactions are labelled fraud where the industry sees 1%, something is wrong with the labelling.
- Automated rule-based tests. Rules a correct label must satisfy: bounding boxes may not overlap or extend beyond the image; a “rejected” loan may not have a payout date; the label must follow the bank’s rule when the rule is known (lesson 38, the correlate constraint).
- Model loss analysis. During training, data points with a persistently high loss (the model keeps getting them wrong) may be mislabelled.
- Model confidence analysis. Data points where the model has low confidence in the given label may be mislabelled, ambiguous, or out of distribution.
The syllabus advises combining them: expert review sets the guidelines, IAA refines the labelling process, and model-based methods find defects as the model develops.
Cohen’s kappa
Percentage agreement overstates how well annotators agree, because some agreement happens by chance. Cohen’s kappa corrects for that:
kappa = (observed agreement − agreement expected by chance) / (1 − agreement expected by chance)
Example: two loan officers each label 20 loan files, approve or reject. Officer A approves 7, officer B approves 8. They both approve 6 files and both reject 11: they agree on 17 of 20.
- Observed agreement: 17 / 20 = 0.85
- Chance agreement: both approve by chance 0.35 × 0.40 = 0.14; both reject by chance 0.65 × 0.60 = 0.39; total 0.53
- Kappa = (0.85 − 0.53) / (1 − 0.53) = 0.32 / 0.47 = 0.68
A common reading: below 0.4 poor, 0.4 to 0.6 moderate, 0.6 to 0.8 substantial, above 0.8 almost perfect. 85% agreement sounds excellent; a kappa of 0.68 says it is good, not excellent.
Hands-on: let a model find suspicious labels
Model confidence analysis on the loan data. The trick is cross-validation (lesson 16): every row is scored by a model that was not trained on that row, so the model cannot simply remember the wrong label. Rows where that model barely believes the given label are suspects. You continue in the practice project; create module-6/test_label_correctness.py:
"""Lesson "Label correctness testing": find suspicious labels with a model, and measure agreement between annotators."""
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from sklearn.metrics import cohen_kappa_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
from sklearn.tree import DecisionTreeClassifier
sys.path.insert(0, str(Path(__file__).parent.parent / "module-3"))
from test_data_preparation import prepare # noqa: E402
FEATURES = ["age", "income", "creditScore"]
@pytest.fixture(scope="module")
def data(api):
raw = pd.DataFrame(api.get(f"{api.base}/datasets/loans-train", timeout=10).json()["data"])
return prepare(raw)
@pytest.fixture(scope="module")
def suspects(data):
"""Model confidence analysis: rows where a model trained WITHOUT that row barely believes the given label."""
label = (data["approved"] == "Yes").astype(int)
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
model = DecisionTreeClassifier(max_depth=2, random_state=0)
probability_yes = cross_val_predict(model, data[FEATURES], label, cv=folds, method="predict_proba")[:, 1]
confidence_in_label = np.where(label == 1, probability_yes, 1 - probability_yes)
found = data.assign(confidence=confidence_in_label.round(2))
found = found[found["confidence"] < 0.1]
print("\n" + found[["id", *FEATURES, "approved", "confidence"]].to_string(index=False))
return found
def test_the_known_wrong_label_is_among_the_suspects(suspects):
assert 18 in set(suspects["id"])
def test_a_reviewer_confirms_only_some_suspects(suspects):
# The review: an expert checks each suspect against the bank's approval rule.
rule = (suspects["creditScore"] > 650) & (suspects["income"] > 50000)
wrong = suspects[rule != (suspects["approved"] == "Yes")]
print(f"\n {len(suspects)} suspects, {len(wrong)} confirmed wrong: {list(wrong['id'])}")
# Row 18 is a wrong label. Row 12 is not: its credit score was missing and imputed in lesson 15,
# so the label only looks wrong. The review has to check the raw data, not just the prepared row.
assert list(wrong["id"]) == [12, 18]
def test_agreement_between_two_annotators():
# 20 loan files labelled independently by two loan officers (1 = approve).
officer_a = [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0]
officer_b = [1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0]
agreement = np.mean(np.array(officer_a) == np.array(officer_b))
kappa = cohen_kappa_score(officer_a, officer_b)
print(f"\n percentage agreement {agreement:.0%}, Cohen's kappa {kappa:.2f}")
assert kappa >= 0.6, "agreement too low: clarify the labelling guidelines"
Run it
pytest module-6/test_label_correctness.py -v -s
id age income creditScore approved confidence
12 56.0 115871.0 629.0 Yes 0.00
18 66.0 80000.0 720.0 No 0.00
32 65.0 50898.0 681.0 Yes 0.00
36 28.0 47083.0 668.0 No 0.08
39 44.0 91086.0 663.0 Yes 0.00
PASSED
5 suspects, 2 confirmed wrong: [12, 18]
PASSED
percentage agreement 85%, Cohen's kappa 0.68
PASSED
Read the result
The model flags five rows. The review finds:
- Row 18 is a wrong label. Credit score 720, income $80,000: the rule says approve, the label says no. This is the defect planted in the data. Found.
- Row 12 looks wrong but is not a label error. Its credit score was missing and was imputed with the median (629) in lesson 15. The label “Yes” was correct for the real, unknown credit score. The defect is in the imputation, not the label. Checking the raw data, not only the prepared row, is part of the review.
- Rows 32, 36 and 39 are correct. They lie near the class boundary: incomes of $50,898 and $47,083, credit scores of 663 to 681. A depth-2 tree with slightly misplaced thresholds gets them wrong. These are the ambiguous points the syllabus says to prioritise for review.
And one wrong label was not found: row 22 (approved, but income −5,000). Preparation turned the impossible income into the median, which made the label look plausible. Each method has blind spots; that is why they are combined. Lesson 38’s constraint on the raw data found row 22 directly.
So model confidence analysis gave five suspects, one real label error, one data error, and three boundary cases worth a second look. That is a typical result: cheap to run, a useful shortlist, and useless without a person who decides.
Exercise
- Two annotators label 100 X-rays as “abnormal” or “normal”. They agree on 90. Annotator A says “abnormal” 10 times, annotator B 12 times, and both say “abnormal” for 6 of the same X-rays. Calculate the percentage agreement and Cohen’s kappa. What do you conclude?
- In the hands-on, change the confidence threshold from 0.1 to 0.4. How many suspects do you get, and what does that do to the review effort?
Show suggested answer
Agreement: 90%. Both “abnormal”: 6; both “normal”: 90 − 6 = 84. Chance agreement: abnormal 0.10 × 0.12 = 0.012, normal 0.90 × 0.88 = 0.792, total 0.804. Kappa = (0.90 − 0.804) / (1 − 0.804) = 0.096 / 0.196 = 0.49: only moderate. 90% agreement sounds high, but because almost everything is “normal”, much of it is chance. On the cases that matter, the abnormal ones, they agree on only 6 of 16 that either called abnormal. The guidelines for “abnormal” need work before this labelling can be trusted.
Seven suspects instead of five: rows 35 and 45 are added (confidence 0.33), both correct labels with credit scores just above 650. The review finds the same two errors, so the extra effort buys nothing here. The threshold trades review effort against the risk of missing a wrong label; choose it based on how costly a wrong label is (risk-based prioritisation).
Exam-style questions
1. Several annotators label the same images, and their agreement is measured with Cohen’s kappa. The kappa is low. What does this most likely indicate?
- A. The model is overfitting
- B. Unclear labelling guidelines, ambiguous data or poor annotation
- C. The images are too large
- D. The annotators are too experienced
Show answer
2. Which label correctness approach uses data points with a persistently high error during training as candidates for mislabelling?
- A. Expert review
- B. Model loss analysis
- C. Data distribution analysis
- D. Automated rule-based testing
Show answer
3. With limited review budget, which labels should be reviewed first, according to risk-based prioritisation?
- A. A random sample only
- B. Ambiguous data points near the class boundary and high-impact or safety-critical data
- C. The labels the model is most confident about
- D. The most recently added labels
Show answer
Your project so far
ai-testing-practice/
├── ...
└── module-6/
├── test_dataset_constraints.py
├── test_bias.py
├── test_representativeness.py
└── test_label_correctness.py new in this lesson
The finished version is in the example repository: module-6/test_label_correctness.py.