Threshold-Sweep Precision-Recall Curve
Easy · Machine Learning · Data Scientist · Technical Screen
Problem Statement
Given parallel evaluation arrays from a binary classification model, compute the exact points along its precision-recall curve across all observed score cutoffs.
Implement the function:
def precision_recall_curve(y_true: List[int], y_score: List[float]) -> Dict[str, List[float]]:
Each index i corresponds to one evaluated record:
- y_true[i] holds the ground-truth class indicator (1 for a positive instance, 0 for a negative instance).
- y_score[i] holds a real-valued confidence score assigned by the model, where larger numbers indicate stronger belief in class 1.
Construct the curve by evaluating every unique value t present in y_score, ordered from largest to smallest:
1. Classify record i as predicted positive whenever y_score[i] >= t, and predicted negative whenever y_score[i] < t. Because all records sharing score t cross the cutoff simultaneously, equal scores produce a single curve entry rather than separate per-record steps.
2. Let TP denote the count of records with y_score[i] >= t and y_true[i] == 1, FP denote the count of records with y_score[i] >= t and y_true[i] == 0, and P denote the total count of 1s across the entire y_true list.
3. Record:
- precision = TP / (TP + FP) (guaranteed well-defined because at least one record has y_score[i] == t), and
- recall = TP / P if P > 0, or 1.0 if P == 0 (when no actual positives exist to be missed).
Return a dictionary {"thresholds": thresholds, "precision": precision, "recall": recall} containing three equal-length lists of floats without prepending or appending synthetic sentinel points. When the input lists are empty, return three empty lists.
Examples
Example 1
Input: y_true = [1, 1, 0, 1, 0], y_score = [0.95, 0.6, 0.75, 0.3, 0.15]
Output: {
"thresholds": [0.95, 0.75, 0.6, 0.3, 0.15],
"precision": [1.0, 0.5, 0.6666666666666666, 0.75, 0.6],
"recall": [0.3333333333333333, 0.3333333333333333, 0.6666666666666666, 1.0, 1.0]
}
Walk-through: There are P = 3 ground-truth positives in total. Ranking pairs from highest score to lowest gives (0.95, 1), (0.75, 0), (0.6, 1), (0.3, 1), (0.15, 0). Stepping the cutoff through those five distinct scores yields TP/Flagged ratios 1/1, 1/2, 2/3, 3/4, 3/5 for precision and 1/3, 1/3, 2/3, 3/3, 3/3 for recall.
Example 2
Input: y_true = [0, 1, 0, 1, 1, 0], y_score = [0.2, 0.85, 0.5, 0.5, 0.5, 0.1]
Output: {
"thresholds": [0.85, 0.5, 0.2, 0.1],
"precision": [1.0, 0.75, 0.6, 0.5],
"recall": [0.3333333333333333, 1.0, 1.0, 1.0]
}
Walk-through: Three records tie at score 0.5 (two positives and one negative). At cutoff 0.85, only (0.85, 1) is selected (precision = 1/1, recall = 1/3). Lowering the cutoff to 0.5 admits all three tied records at once, bringing cumulative counts to TP = 3 and FP = 1 (precision = 3/4 = 0.75, recall = 3/3 = 1.0). Cutoffs 0.2 and 0.1 each add one negative record.
Example 3
Input: y_true = [1, 0, 1], y_score = [2.5, 2.5, -1.0]
Output: {
"thresholds": [2.5, -1.0],
"precision": [0.5, 0.6666666666666666],
"recall": [0.5, 1.0]
}
Walk-through: Raw uncalibrated logits (including negative numbers and values above 1) follow the exact same ordering rules. At t = 2.5, one positive and one negative tie at the top (TP = 1, FP = 1, so precision = 0.5 and recall = 0.5). At t = -1.0, the remaining positive joins (TP = 2, FP = 1, so precision = 2/3 and recall = 1.0).
Constraints
0 <= len(y_true) == len(y_score) <= 5 * 10^4y_true[i]is either0or1.y_score[i]is a finiteintorfloat(not restricted to[0.0, 1.0]).- Floating-point answers within
10^-6relative or absolute tolerance are accepted. - Aim for
O(n log n)time complexity andO(n)space complexity, wheren = len(y_true).
Step-by-step walkthrough
Understand the inputs, rules, and output shape
We receive two equal-length lists describing how a binary model scored
nrecords:y_true: ground-truth class indicators in{0, 1}(1= positive instance,0= negative instance).y_score: real-valued model confidence scores (larger numbers mean stronger confidence in class1).
We return a dictionary
{"thresholds": ..., "precision": ..., "recall": ...}whose three lists have matching lengths under these rules:thresholdsholds the unique values ofy_scoresorted from largest to smallest.- At cutoff
t, every record withscore >= tis classified as1, and every record withscore < tis classified as0. - No extra synthetic anchor point is added:
kunique scores yieldkentries (and empty input lists yield three empty lists).
Note: when
y_truecontains zero positive labels (total_positives == 0),TP / Pis0 / 0. Matching scikit-learn's convention, our implementation reports1.0("zero positives were missed") instead of dividing by zero.Define precision and recall from the four outcome counts
Fix a single cutoff
t. Comparing each record's decision (score >= t) against its actual label (0or1) places it into one of four buckets:Actual Label = 1 Actual Label = 0 +-------------------------+-------------------------+ Predicted 1 | True Positive (TP) | False Positive (FP) | Total flagged = TP + FP (score >= t) | caught a real target | false alarm | +-------------------------+-------------------------+ Predicted 0 | False Negative (FN) | True Negative (TN) | (score < t) | missed a real target | quietly ignored | +-------------------------+-------------------------+ Total positives P = TP + FNFrom those counts, we define both evaluation ratios:
- Precision =
TP / (TP + FP): among all records selected at cutofft, what fraction belong to class1? (Alert purity.) - Recall =
TP / (TP + FN) = TP / P: among allPclass-1records in the entire dataset, what fraction were selected at cutofft? (Target coverage.)
As we step
tdownward from the top score to the bottom score, the selected prefix only expands:- Recall never drops, because
TPcan only stay flat or grow whilePremains constant. - Precision can rise and fall, climbing whenever newly admitted records are true positives and dipping whenever they are false positives.
- Notice that
TNnever appears in either ratio — so huge numbers of easy negatives never artificially boost a precision-recall curve.
- Precision =
Why recounting from scratch per cutoff is too slow
A direct brute-force loop extracts the unique scores in descending order and, for every cutoff
t, scans allnrecords from index0ton - 1to tallyTPandFPwherescore >= t.When all
nscores are distinct, scanningnrecords acrossncutoffs performsO(n^2)operations (2.5 * 10^9checks atn = 50,000). That work is wasted because stepping from one cutoff down to the next lower score keeps every previously selected record selected — only the records sitting right atcurrent_thresholdjoin the selected set.Key idea: sort descending and sweep tied score blocks
Once we sort
(score, label)pairs from largest score to smallest, the records selected at any cutofftalways form a contiguous prefix of the sorted list:Sorted (score, label): (0.85, 1) | (0.5, 1), (0.5, 1), (0.5, 0) | (0.2, 0) | (0.1, 0) ----------+------------------------------+----------+--------- Selected at t = 0.85: [=======] TP=1, FP=0 Selected at t = 0.50: [======================================] TP=3, FP=1 Selected at t = 0.20: [=================================================] TP=3, FP=2 Selected at t = 0.10: [============================================================] TP=3, FP=3Two invariants make this single-pass sweep exact:
- Absorb equal scores as one atomic group: In the diagram above,
(0.5, 1),(0.5, 1), and(0.5, 0)all satisfyscore >= 0.5simultaneously. No cutoff can include one0.5record while excluding another0.5record! An innerwhileloop therefore consumes every record equal tocurrent_thresholdbefore recording one(threshold, precision, recall)point. - Precision never divides by zero: Because
current_thresholdis read directly fromscored_items[i], at least one record enters the active prefix, guaranteeingtrue_pos + false_pos >= 1.
# Phase 2: slide the threshold down one distinct score block at a time. true_pos = 0 false_pos = 0 i = 0 n = len(scored_items) while i < n: current_threshold = scored_items[i][0] # Consume ALL items tied at current_threshold before recording a point, # because rule `score >= threshold` flags every tied item simultaneously. while i < n and scored_items[i][0] == current_threshold: _, label = scored_items[i] if label == 1: true_pos += 1 else: false_pos += 1 i += 1 # At least one item just crossed current_threshold, so true_pos + false_pos >= 1. thresholds.append(current_threshold) precision.append(true_pos / (true_pos + false_pos)) if total_positives > 0: recall.append(true_pos / total_positives) else: # Degenerate dataset with zero real positives (0/0): report 1.0 ("nothing missed"). recall.append(1.0)- Absorb equal scores as one atomic group: In the diagram above,
Trace Example 2 with tied scores
Let us trace Example 2:
y_true = [0, 1, 0, 1, 1, 0]andy_score = [0.2, 0.85, 0.5, 0.5, 0.5, 0.1]. First,total_positives = 3. Sortingzip(y_score, y_true)in descending order produces[(0.85, 1), (0.5, 1), (0.5, 1), (0.5, 0), (0.2, 0), (0.1, 0)]:Threshold | Records in block | Running TP | Running FP | Precision = TP/(TP+FP) | Recall = TP/3 ----------+--------------------------------+------------+------------+------------------------+-------------- 0.85 | (0.85, 1) | 1 | 0 | 1 / 1 = 1.0 | 1 / 3 = 0.333 0.50 | (0.5, 1), (0.5, 1), (0.5, 0) | 3 | 1 | 3 / 4 = 0.75 | 3 / 3 = 1.0 0.20 | (0.2, 0) | 3 | 2 | 3 / 5 = 0.6 | 3 / 3 = 1.0 0.10 | (0.1, 0) | 3 | 3 | 3 / 6 = 0.5 | 3 / 3 = 1.0Look closely at
0.50: consuming all three tied items together updatesTPfrom1to3andFPfrom0to1in one step. Emitting points after individual items would fabricate intermediate points at recall2/3whose precision would even change depending on whether(0.5, 0)happened to sort before or after(0.5, 1)!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def precision_recall_curve(y_true: List[int], y_score: List[float]) -> Dict[str, List[float]]: # Phase 1: count all actual positives (denominator of recall). total_positives = 0 for label in y_true: if label == 1: total_positives += 1 # scored_items: list of (score, label) pairs ordered from highest score to lowest # so equal scores sit adjacent and can cross the threshold together. scored_items = sorted(zip(y_score, y_true), reverse=True) thresholds: List[float] = [] precision: List[float] = [] recall: List[float] = [] # Phase 2: slide the threshold down one distinct score block at a time. true_pos = 0 false_pos = 0 i = 0 n = len(scored_items) while i < n: current_threshold = scored_items[i][0] # Consume ALL items tied at current_threshold before recording a point, # because rule `score >= threshold` flags every tied item simultaneously. while i < n and scored_items[i][0] == current_threshold: _, label = scored_items[i] if label == 1: true_pos += 1 else: false_pos += 1 i += 1 # At least one item just crossed current_threshold, so true_pos + false_pos >= 1. thresholds.append(current_threshold) precision.append(true_pos / (true_pos + false_pos)) if total_positives > 0: recall.append(true_pos / total_positives) else: # Degenerate dataset with zero real positives (0/0): report 1.0 ("nothing missed"). recall.append(1.0) return { "thresholds": thresholds, "precision": precision, "recall": recall, }✅ Submit now — all tests should pass.
Intuition & how it works
Imagine sorting incoming support tickets from highest predicted urgency score at the top of a page to lowest at the bottom, then sliding a horizontal ruler steadily down the list so every ticket at or above the ruler gets paged. Precision (the share of paged tickets that are genuinely urgent, TP / (TP + FP)) measures alert accuracy, while recall (the share of all genuinely urgent tickets on the page that sit above the ruler, TP / P) measures how much real urgency you captured. Rather than scanning the entire list anew for every ruler position, we run a threshold sweep — sorting the (score, label) pairs once in descending score order and maintaining running counts of true positives (class-1 records above the ruler) and false positives (class-0 records above the ruler) as the ruler steps down one unique score group at a time.
Why does the naive approach fall short? Extracting every unique score and rescanning all n records for each cutoff wastes O(n^2) work re-checking records that already passed higher cutoffs. A second common trap emits a curve point after every single sorted element without grouping equal scores, which invents phantom precision-recall points whenever multiple records share the exact same score (and makes the answer depend on tie-break order).
Let's trace Example 1 (y_true = [1, 1, 0, 1, 0], y_score = [0.95, 0.6, 0.75, 0.3, 0.15], total positives P = 3):
- At threshold = 0.95: (0.95, 1) enters -> TP = 1, FP = 0 -> precision = 1/1 = 1.0, recall = 1/3 ≈ 0.333.
- At threshold = 0.75: (0.75, 0) enters -> TP = 1, FP = 1 -> precision = 1/2 = 0.5, recall = 1/3 ≈ 0.333.
- At threshold = 0.60: (0.60, 1) enters -> TP = 2, FP = 1 -> precision = 2/3 ≈ 0.667, recall = 2/3 ≈ 0.667.
- At threshold = 0.30: (0.30, 1) enters -> TP = 3, FP = 1 -> precision = 3/4 = 0.75, recall = 3/3 = 1.0.
- At threshold = 0.15: (0.15, 0) enters -> TP = 3, FP = 2 -> precision = 3/5 = 0.6, recall = 3/3 = 1.0.
Complexity
Let n be the number of evaluated records (len(y_true) == len(y_score)).
- Time:
O(n log n). Countingtotal_positivesscansy_trueonce inO(n)time, sorting then(score, label)tuples takesO(n log n)comparisons, and the nestedwhilesweep advances indexistrictly forward from0tonso each tuple is visited once (O(n)). - Space:
O(n).scored_itemsholdsnpairs, andthresholds,precision, andrecalleach hold at mostnfloats (one entry per unique score).
Edge cases
- Equal scores in
y_score: all records sharingcurrent_thresholdare absorbed by the innerwhileloop before appending a point, so tied positives and negatives never create order-dependent intermediate steps. - Cutoff strictly above
max(y_score): because every returned cutoff comes fromy_score, at least one record satisfiesscore >= current_threshold(true_pos + false_pos >= 1), avoiding0 / 0in precision. For plotting, callers commonly prepend the conventional anchor(recall = 0.0, precision = 1.0). - Zero positives in
y_true(total_positives == 0):TP / Pbecomes0 / 0; ourelsebranch emits1.0for recall (matching scikit-learn) while precision stays0.0at every cutoff. - Severe class imbalance: class imbalance means one class (typically class
0) vastly outnumbers the other. At the minimum score cutoff every record is selected (TP = P,TP + FP = n), pinning the final precision entry to the dataset base rateP / n. - Empty inputs (
[],[]):scored_itemsis empty, the sweep loop skips immediately, and three empty lists are returned. - Signed or uncalibrated scores: arbitrary integers or raw logits such as
[2.5, 2.5, -1.0]work identically to probabilities in[0, 1]because only relative score order matters.
Common mistakes
- Recording a point per element instead of per unique score: breaks Example 2 (
0.5appears three times) and Example 3 (2.5appears twice), producing phantom recall steps when scores tie. - Writing strict
score > thresholdinstead ofscore >= threshold: leaves zero selected items (ZeroDivisionError) at the top cutoff and shifts every point off by one block. - Dividing recall by
TP + FPinstead oftotal_positives: mixes up precision's denominator with recall's fixed dataset-wide denominatorP. - Integrating PR area with straight-line trapezoids: because precision varies hyperbolically (
TP / (TP + FP)) between cutoffs, linear trapezoids overestimate performance between sparse points; step-wise Average Precision avoids that optimistic bias.
Alternative approaches
- Vectorized NumPy prefix sums: sort descending via
order = np.argsort(-y_score, kind="mergesort"), takenp.cumsumofy_true[order]for runningTPcounts, locate the final index of each equal-score run usingnp.nonzero(np.diff(y_score[order]))[0], and index at those run boundaries — sameO(n log n)asymptotic bound with fast C array operations. sklearn.metrics.precision_recall_curve: computes the exact same distinct-cutoff ratios, except its returnedthresholdsare ordered ascending and it appends one extra sentinel entry(precision = 1.0, recall = 0.0).
Follow-up questions
- How is Average Precision (step-wise AUPRC) computed from these curve points, and what represents a random-classifier baseline? Average Precision (AP) summarizes the curve as the recall-increment-weighted sum of precisions across cutoffs:
AP = sum_k (recall[k] - recall[k - 1]) * precision[k]takingrecall[-1] = 0.0(on Example 1,(1/3)*1.0 + 0*0.5 + (1/3)*(2/3) + (1/3)*0.75 + 0*0.6 = 29/36 ≈ 0.806). Under random score assignment, expected precision at any cutoff depth equals the positive prevalenceP / n, so the horizontal reference baseline isP / nrather than0.5(an AP of0.08is strong whenP / n = 0.002, yet poor whenP / n = 0.50). On very small samples with tinyP, finite-sample random AP sits slightly aboveP / n, so permutation baselines (shufflingy_scoremany times) give a sharper check whenPis small.
def average_precision(curve: Dict[str, List[float]]) -> float:
ap = 0.0
prev_recall = 0.0
for prec, rec in zip(curve["precision"], curve["recall"]):
ap += (rec - prev_recall) * prec
prev_recall = rec
return ap
- How should you render this curve on a chart without misleading linear interpolation? Plot
recallhorizontally andprecisionvertically, prepend the(0.0, 1.0)starting anchor, and draw a right-aligned step curve (where="pre") instead of diagonal line segments so the plotted area equals the exact step-wise rectangles summed by Average Precision, overlaid with a dashed horizontal line atP / n.
import matplotlib.pyplot as plt
curve = precision_recall_curve(y_true, y_score)
recall = [0.0] + curve["recall"]
precision = [1.0] + curve["precision"]
baseline = sum(y_true) / len(y_true)
plt.step(recall, precision, where="pre", label="Model PR curve")
plt.axhline(baseline, linestyle="--", label=f"Prevalence baseline ({baseline:.2f})")
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.ylim(0.0, 1.05)
plt.legend()
plt.show()
- Why is a precision-recall curve preferred over an ROC curve on heavily imbalanced datasets? An ROC (Receiver Operating Characteristic) curve plots recall against the false positive rate (
FPR = FP / (FP + TN), the share of all negatives mistakenly flagged). When positives are rare — say200defective parts among1,000,000inspected parts — raising1,800false alarms yields a tinyFPR = 1,800 / 999,800 ≈ 0.0018that makes the ROC curve look nearly ideal, even though precision is200 / (200 + 1,800) = 10%(90%of inspections are false alarms). Because precision comparesTPdirectly againstFPwithout dividing by hugeTN, the PR curve immediately reveals false-alarm dilution whenever positive events are rare.
Follow-up questions
- How is Average Precision (step-wise AUPRC) computed from these curve points, and what represents a random-classifier baseline?
- How should you render this curve on a chart without misleading linear interpolation?
- Why is a precision-recall curve preferred over an ROC curve on heavily imbalanced datasets?
Similar questions
- Designing a Leakage-Free Churn Baseline Model from Monthly Snapshots
- Curation Pipeline for OCR Post-Correction Fine-Tuning
- Sequence vs. Vision Architectures and Vectorized K-Means
- Preference Alignment Trade-Offs for Enterprise LLMs
- End-to-End Propensity Modeling for Rare Conversions
- Pipelines, Neural Architectures, and Child-Level Deep Learning
More Microsoft interview questions
- In-Memory Cache With LRU Eviction Medium
- Peak Substring Frequency Under Character Bounds Medium
- Distinct Triplets Summing to Zero Medium Pro
- Longest Duplicate-Free Substring Length Medium Pro
- Consolidate Overlapping Intervals Medium Pro
- Minimum Highway Fuel Expense Medium Pro
- Smallest Daily Cargo Vessel Capacity Medium Pro
- Evaluating Binary Classifiers Under Unequal Error Costs Medium Pro
- Sequential Markdowns and Undiscounted Indices Hard Pro
- Worldwide Mobile 1-on-1 VoIP Calling Architecture Medium Pro