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^4
  • y_true[i] is either 0 or 1.
  • y_score[i] is a finite int or float (not restricted to [0.0, 1.0]).
  • Floating-point answers within 10^-6 relative or absolute tolerance are accepted.
  • Aim for O(n log n) time complexity and O(n) space complexity, where n = len(y_true).

Step-by-step walkthrough

  1. Understand the inputs, rules, and output shape

    We receive two equal-length lists describing how a binary model scored n records:

    • 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 class 1).

    We return a dictionary {"thresholds": ..., "precision": ..., "recall": ...} whose three lists have matching lengths under these rules:

    • thresholds holds the unique values of y_score sorted from largest to smallest.
    • At cutoff t, every record with score >= t is classified as 1, and every record with score < t is classified as 0.
    • No extra synthetic anchor point is added: k unique scores yield k entries (and empty input lists yield three empty lists).

    Note: when y_true contains zero positive labels (total_positives == 0), TP / P is 0 / 0. Matching scikit-learn's convention, our implementation reports 1.0 ("zero positives were missed") instead of dividing by zero.

  2. 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 (0 or 1) 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 + FN
    

    From those counts, we define both evaluation ratios:

    • Precision = TP / (TP + FP): among all records selected at cutoff t, what fraction belong to class 1? (Alert purity.)
    • Recall = TP / (TP + FN) = TP / P: among all P class-1 records in the entire dataset, what fraction were selected at cutoff t? (Target coverage.)

    As we step t downward from the top score to the bottom score, the selected prefix only expands:

    • Recall never drops, because TP can only stay flat or grow while P remains constant.
    • Precision can rise and fall, climbing whenever newly admitted records are true positives and dipping whenever they are false positives.
    • Notice that TN never appears in either ratio — so huge numbers of easy negatives never artificially boost a precision-recall curve.
  3. 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 all n records from index 0 to n - 1 to tally TP and FP where score >= t.

    When all n scores are distinct, scanning n records across n cutoffs performs O(n^2) operations (2.5 * 10^9 checks at n = 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 at current_threshold join the selected set.

  4. 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 cutoff t always 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=3
    

    Two invariants make this single-pass sweep exact:

    1. Absorb equal scores as one atomic group: In the diagram above, (0.5, 1), (0.5, 1), and (0.5, 0) all satisfy score >= 0.5 simultaneously. No cutoff can include one 0.5 record while excluding another 0.5 record! An inner while loop therefore consumes every record equal to current_threshold before recording one (threshold, precision, recall) point.
    2. Precision never divides by zero: Because current_threshold is read directly from scored_items[i], at least one record enters the active prefix, guaranteeing true_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)
    
  5. Trace Example 2 with tied scores

    Let us trace Example 2: y_true = [0, 1, 0, 1, 1, 0] and y_score = [0.2, 0.85, 0.5, 0.5, 0.5, 0.1]. First, total_positives = 3. Sorting zip(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.0
    

    Look closely at 0.50: consuming all three tied items together updates TP from 1 to 3 and FP from 0 to 1 in one step. Emitting points after individual items would fabricate intermediate points at recall 2/3 whose precision would even change depending on whether (0.5, 0) happened to sort before or after (0.5, 1)!

  6. 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). Counting total_positives scans y_true once in O(n) time, sorting the n (score, label) tuples takes O(n log n) comparisons, and the nested while sweep advances index i strictly forward from 0 to n so each tuple is visited once (O(n)).
  • Space: O(n). scored_items holds n pairs, and thresholds, precision, and recall each hold at most n floats (one entry per unique score).

Edge cases

  • Equal scores in y_score: all records sharing current_threshold are absorbed by the inner while loop 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 from y_score, at least one record satisfies score >= current_threshold (true_pos + false_pos >= 1), avoiding 0 / 0 in precision. For plotting, callers commonly prepend the conventional anchor (recall = 0.0, precision = 1.0).
  • Zero positives in y_true (total_positives == 0): TP / P becomes 0 / 0; our else branch emits 1.0 for recall (matching scikit-learn) while precision stays 0.0 at 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 rate P / n.
  • Empty inputs ([], []): scored_items is 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.5 appears three times) and Example 3 (2.5 appears twice), producing phantom recall steps when scores tie.
  • Writing strict score > threshold instead of score >= threshold: leaves zero selected items (ZeroDivisionError) at the top cutoff and shifts every point off by one block.
  • Dividing recall by TP + FP instead of total_positives: mixes up precision's denominator with recall's fixed dataset-wide denominator P.
  • 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"), take np.cumsum of y_true[order] for running TP counts, locate the final index of each equal-score run using np.nonzero(np.diff(y_score[order]))[0], and index at those run boundaries — same O(n log n) asymptotic bound with fast C array operations.
  • sklearn.metrics.precision_recall_curve: computes the exact same distinct-cutoff ratios, except its returned thresholds are 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] taking recall[-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 prevalence P / n, so the horizontal reference baseline is P / n rather than 0.5 (an AP of 0.08 is strong when P / n = 0.002, yet poor when P / n = 0.50). On very small samples with tiny P, finite-sample random AP sits slightly above P / n, so permutation baselines (shuffling y_score many times) give a sharper check when P is 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 recall horizontally and precision vertically, 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 at P / 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 — say 200 defective parts among 1,000,000 inspected parts — raising 1,800 false alarms yields a tiny FPR = 1,800 / 999,800 ≈ 0.0018 that makes the ROC curve look nearly ideal, even though precision is 200 / (200 + 1,800) = 10% (90% of inspections are false alarms). Because precision compares TP directly against FP without dividing by huge TN, the PR curve immediately reveals false-alarm dilution whenever positive events are rare.

Follow-up questions

Similar questions

More Microsoft interview questions

All 252 Microsoft questions →