Detect Suspicious Annotators in Data Pipelines
SQL & DataModel answerLast updated
Process crowd-sourced label data to compute consensus metrics and flag underperforming annotators at scale.
You are building an evaluation pipeline to monitor label quality across a crowdsourced data labeling workflow. A dataset contains multi-worker annotations alongside reference ground-truth labels for a subset of images.
Write a function identify_low_quality_annotator(df) that processes a pandas DataFrame df and returns the annotator_id of the worker whose annotations demonstrate the poorest quality.
Input Schema
df contains the following columns:
annotator_id(str): Unique worker identifier.image_id(str): Unique item identifier.label(int): Class label (0 or 1).is_ground_truth(bool):Trueif this row represents a validated gold-standard reference label;Falseif it is a submission from a general annotator.
Logic & Scoring Rules
- Gold Reference Definition: A ground-truth reference for an
image_idis derived from rows whereis_ground_truth == True. If an image has multiple conflicting gold rows (e.g., one row withlabel = 0and another withlabel = 1), that image is considered ambiguous and must be completely excluded from evaluation. - Annotator Accuracy Calculation:
- An annotator's quality metric is calculated as their accuracy rate on distinct gold-standard images they labeled.
- If a non-gold row shares an
image_idandlabelvalue with the image's gold reference, it is scored as correct (1), otherwise incorrect (0). - If an annotator labeled the same gold image multiple times, drop duplicates to ensure each distinct image is counted at most once per annotator (keeping the first entry).
- Statistical Threshold: To prevent sample size noise, only include annotators who have evaluated at least 20 distinct valid ground-truth images. Workers with fewer than 20 evaluated gold images must be ignored. Annotators with zero gold interactions are automatically excluded.
- Tie-Breaking Order:
- Primary metric: Lowest accuracy rate (
correct_gold_labels / total_gold_images_evaluated). - First tie-breaker: Smallest total count of non-gold annotations submitted by the worker across the entire dataset.
- Second tie-breaker: Lexicographically smallest
annotator_id(ascending order).
- Primary metric: Lowest accuracy rate (
- Null Handling: If no single annotator satisfies the 20-gold-image threshold (or if
dfcontains no usable evaluation rows), returnNone.
Example
import pandas as pd
data = {
'annotator_id': ['worker_1', 'worker_1', 'worker_2', 'worker_2', 'worker_3'],
'image_id': ['img_1', 'img_2', 'img_1', 'img_2', 'img_1'],
'label': [1, 0, 0, 1, 1],
'is_ground_truth': [False, False, False, False, True]
}
df = pd.DataFrame(data)
# Calling identify_low_quality_annotator(df) returns None
# because no worker has evaluated >= 20 ground-truth images.
Hints
Hint 1
Isolate the gold reference labels first by checking `is_ground_truth == True` and dropping images that contain conflicting reference values.
Hint 2
Join non-gold annotations with valid gold references using `image_id` to compute individual match scores.
Hint 3
Make sure total work counts consider all non-gold rows per worker, while accuracy evaluation is filtered only to qualified gold matches.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
To isolate underperforming annotators efficiently at scale ($10^5 - 10^6$ rows), we leverage vectorized operations in pandas rather than iterating over rows or applying Python lambdas per group.
1. Reference Data Normalization
First, partition df into gold standard references (is_ground_truth == True) and worker submissions (is_ground_truth == False).
Gold data may occasionally suffer from internal conflicts if multiple conflicting reference rows exist for a single image_id. We group gold rows by image_id and retain only images where min(label) == max(label). This yields a deterministic lookup table mapping image_id -> true_label.
2. Annotator Aggregation & Join
- Total Work Volume: Group non-gold rows by
annotator_idto count the total non-gold items submitted (total_work). This serves as our first tie-breaking key. - Deduplication: Deduplicate worker entries on
(annotator_id, image_id)so duplicate submissions for the same image do not distort sample counts. - Matching Gold Images: Perform an inner join between worker submissions and the validated gold reference table on
image_id. Annotators without gold labels are naturally dropped here.
3. Metric Calculation & Filtering
For each qualifying worker-image pair, compute correctness as (worker_label == gold_label).
Group the joined results by annotator_id to derive:
n_gold: Count of distinct gold images evaluated.n_correct: Count of correctly labeled gold images.accuracy:n_correct / n_gold.
Filter out any annotator where n_gold < 20.
4. Sorting & Selection
Sort the remaining dataset using the multi-column criteria:
accuracy(ascending)total_work(ascending)annotator_id(ascending)
Return the top row's annotator_id, or None if the filtered table is empty.
Python Implementation
import pandas as pd
from typing import Optional
def identify_low_quality_annotator(df: pd.DataFrame, min_gold_threshold: int = 20) -> Optional[str]:
if df.empty:
return None
# Cast to boolean to ensure safety against int/string inputs
is_gt = df["is_ground_truth"].astype(bool)
# 1. Filter and validate gold labels
gold_df = df[is_gt]
if gold_df.empty:
return None
# Group gold labels by image_id to detect and drop contradictory references
gold_grouped = gold_df.groupby("image_id")["label"].agg(["min", "max"])
valid_gold = gold_grouped[gold_grouped["min"] == gold_grouped["max"]]["min"].rename("gold_label")
if valid_gold.empty:
return None
# 2. Extract worker annotations and aggregate total submission volumes
worker_df = df[~is_gt]
if worker_df.empty:
return None
total_submissions = worker_df.groupby("annotator_id").size().rename("total_work")
# 3. Join worker submissions with valid gold reference labels
# Deduplicate worker records per image first
deduped_worker_df = worker_df.drop_duplicates(subset=["annotator_id", "image_id"])
scored_df = deduped_worker_df.merge(
valid_gold, left_on="image_id", right_index=True, how="inner"
)
if scored_df.empty:
return None
scored_df["is_correct"] = (scored_df["label"] == scored_df["gold_label"]).astype(int)
# 4. Compute per-worker stats
metrics = scored_df.groupby("annotator_id").agg(
n_gold=("is_correct", "count"),
n_correct=("is_correct", "sum")
)
# Calculate exact accuracy ratio
metrics["accuracy"] = metrics["n_correct"] / metrics["n_gold"]
# Merge total overall submissions for tie-breaking
metrics = metrics.join(total_submissions, how="left")
# Filter for statistical significance threshold
qualified_metrics = metrics[metrics["n_gold"] >= min_gold_threshold]
if qualified_metrics.empty:
return None
# 5. Deterministic multi-key sorting
ranked_annotators = qualified_metrics.reset_index().sort_values(
by=["accuracy", "total_work", "annotator_id"],
ascending=[True, True, True]
)
return ranked_annotators.iloc[0]["annotator_id"]
Complexity Analysis
- Time Complexity: $\mathcal{O}(N \log N)$ where $N$ is the number of rows in
df. Grouping, filtering, and merging run in linear $\mathcal{O}(N)$ time. The final sorting step operates on $A$ qualified annotators ($\mathcal{O}(A \log A)$), where $A \ll N$. Overall runtime easily completes within milliseconds for $10^6$ rows using native Pandas primitives. - Space Complexity: $\mathcal{O}(N)$ to construct intermediate filtered DataFrames (
worker_df,scored_df, and aggregated metric indices).
Key Edge Cases Handled
- Contradictory References: Ground-truth rows with conflicting label values for the same
image_idare removed to prevent incorrect grading. - No Qualifiers: Returns
Nonegracefully if zero workers pass the 20-gold-image threshold. - Repeated Labels: If a worker labels the same ground-truth image multiple times,
drop_duplicatesprevents double-counting metrics. - Zero Gold Annotations: Workers who only annotate unverified images are safely excluded by the inner join without raising key errors.