Select Score Cutoff for Target Precision

Medium · Machine Learning · Data Scientist · Online Assessment

Problem Statement

Implement select_precision_threshold(y_val, scores, target_precision) to choose a classification cutoff on validation predictions so that positive alerts satisfy a required precision floor while capturing as many true positives as possible.

You receive two equal-length validation sequences and a precision requirement:

  • y_val: binary ground-truth labels (1 for a true positive instance, 0 for a negative instance).
  • scores: real-valued model confidence scores or predicted probabilities aligned index-by-index with y_val.
  • target_precision: the minimum acceptable precision (for example 0.95).

For any candidate cutoff tau drawn from the distinct values present in scores, every validation item i with scores[i] >= tau is predicted positive:

  • Let TP be the count of flagged items (scores[i] >= tau) with y_val[i] == 1.
  • Let FP be the count of flagged items (scores[i] >= tau) with y_val[i] == 0.
  • Let P be the total count of items across y_val with y_val[i] == 1.
  • Define precision = TP / (TP + FP) and recall = TP / P.

Select tau according to the following rules:

  1. Precision floor: Keep only candidate cutoffs from scores where precision >= target_precision.
  2. Maximize recall: Among qualifying cutoffs, choose the one with the largest recall.
  3. Tie-breaking: If multiple qualifying cutoffs achieve the exact same maximum recall, choose the smallest tau.
  4. Infeasible or empty cases: If y_val is empty, contains zero positive labels (P == 0), or has no candidate cutoff reaching target_precision, return {"threshold": None, "precision": None, "recall": None}.

Return a dictionary {"threshold": tau, "precision": precision, "recall": recall} without modifying the input lists.

Examples

Example 1

Input:
  y_val = [1, 1, 0, 1, 0]
  scores = [0.95, 0.85, 0.70, 0.60, 0.20]
  target_precision = 0.75
Output:
  {"threshold": 0.6, "precision": 0.75, "recall": 1.0}

There are P = 3 positive items in total: - At tau = 0.95: TP = 1, FP = 0, giving precision = 1.0, recall = 1/3. - At tau = 0.85: TP = 2, FP = 0, giving precision = 1.0, recall = 2/3. - At tau = 0.70: TP = 2, FP = 1, giving precision = 2/3 < 0.75 (misses the floor). - At tau = 0.60: TP = 3, FP = 1, giving precision = 3/4 = 0.75 >= 0.75 and recall = 3/3 = 1.0. - At tau = 0.20: TP = 3, FP = 2, giving precision = 3/5 = 0.60 < 0.75.

Notice that precision dips below 0.75 at tau = 0.70 and climbs back up to 0.75 at tau = 0.60, achieving full recall (1.0).

Example 2

Input:
  y_val = [0, 1, 1, 0]
  scores = [0.40, 0.92, 0.75, 0.50]
  target_precision = 0.60
Output:
  {"threshold": 0.5, "precision": 0.6666666666666666, "recall": 1.0}

Sorting by score from highest to lowest gives [(0.92, 1), (0.75, 1), (0.50, 0), (0.40, 0)] with P = 2: - tau = 0.92: precision = 1.0, recall = 0.5 (qualifies). - tau = 0.75: precision = 1.0, recall = 1.0 (qualifies). - tau = 0.50: precision = 2/3 = 0.6667, recall = 1.0 (qualifies). - tau = 0.40: precision = 2/4 = 0.50 (below 0.60).

Both tau = 0.75 and tau = 0.50 reach the maximum recall = 1.0 while meeting precision >= 0.60; the tie-breaker picks the lower cutoff 0.5.

Constraints

  • 0 <= len(y_val) == len(scores) <= 10^5
  • y_val[i] is either 0 or 1.
  • 0.0 <= scores[i] <= 1.0
  • 0.0 < target_precision <= 1.0

Step-by-step walkthrough

  1. Understand the cutoff selection rules

    We are given validation binary labels y_val (0 or 1), model confidence values scores, and a required precision floor target_precision. Let's pin down every rule of the selection contract:

    • Flagging rule: an item i is predicted positive whenever scores[i] >= tau (matching the inclusive convention of scikit-learn's precision_recall_curve).
    • Candidate cutoffs: the distinct numbers appearing in scores. Why restrict tau to observed scores? Any number strictly between two adjacent scores (say 0.80 between 0.85 and 0.70) flags the exact same subset of items as the higher score (0.85), while choosing 0.85 comes directly from scores.
    • Metrics at tau:
      • precision = TP / (TP + FP) — among all flagged items (scores[i] >= tau), the fraction with y_val[i] == 1.
      • recall = TP / total_positives — among all positive items in y_val, the fraction that got flagged.
    • Objective & tie-breaker: keep only cutoffs where precision >= target_precision. Among those, maximize recall; if multiple cutoffs share the highest recall, pick the smallest tau.
    • No valid cutoff / zero positives: when y_val is empty, has zero positive labels (0 / 0 recall), or has no cutoff reaching target_precision, return {"threshold": None, "precision": None, "recall": None}.
  2. Why rescanning per cutoff (or binary search) fails

    A literal brute-force loop tests every distinct score tau by scanning all N validation items from scratch to count TP and FP. When all N scores are distinct, that takes O(N^2) operations — billions of checks once N reaches tens of thousands.

    Two tempting shortcuts also fail: binary search on tau, and sweeping downward while stopping the moment precision dips below target_precision. Both are incorrect because precision is not monotonic as tau decreases! Look at Example 1 (y_val = [1, 1, 0, 1, 0], scores = [0.95, 0.85, 0.70, 0.60, 0.20], target_precision = 0.75):

    Descending scores:  0.95    0.85    0.70    0.60    0.20
    Labels:               1       1       0       1       0
    Running TP / Flag:   1/1     2/2     2/3     3/4     3/5
    Precision:          1.00    1.00    0.67    0.75    0.60
                         OK      OK     MISS     OK!    MISS
    

    At tau = 0.70, a negative item drops precision to 0.67 (below 0.75), yet right below it at tau = 0.60, another positive item pulls precision back up to 0.75 at recall = 1.0! We must inspect every distinct score group from top to bottom without stopping early.

  3. Key idea 1: sort descending and sweep one score group at a time

    Instead of recounting from scratch per cutoff, pair each (score, label) and sort the pairs from highest score to lowest. As tau steps downward from one distinct score to the next, every previously flagged item stays flagged (score >= tau remains true), so we simply add the newly reached items to running true_positives and false_positives counters.

    Watch out for tied scores: all items sharing the exact same score cross the cutoff simultaneously! If (0.5, 1) and (0.5, 0) tie at 0.5, setting tau = 0.5 flags both items together:

    Sorted pairs:  [(0.8, 1),  (0.5, 1), (0.5, 0)]
                     |--tau=0.8--|
                     |---------tau=0.5----------|   <-- absorb BOTH 0.5 items before
                                                        computing precision = 2 / 3 = 0.67
    

    A two-level while loop handles ties cleanly: the outer loop records candidate_tau = scored_examples[idx][0], and the inner loop consumes all items with score == candidate_tau before evaluating precision and recall.

  4. Key idea 2: why the tie-breaker reduces to overwriting `best_result`

    Track what happens to recall = true_positives / total_positives as candidate_tau moves strictly downward:

    1. Lowering candidate_tau only adds items to the flagged prefix; nothing is ever removed.
    2. Consequently, true_positives (and therefore recall) never decreases during the downward sweep.

    Now compare an earlier qualifying cutoff tau_high against any later qualifying cutoff tau_low (tau_low < tau_high): - Either recall(tau_low) > recall(tau_high), so tau_low wins by higher recall; - Or recall(tau_low) == recall(tau_high) (only negative items joined, while precision stayed >= target_precision), so tau_low wins the tie-breaker by smaller cutoff!

    Every later qualifying cutoff automatically beats every earlier one. During our downward pass, whenever precision >= target_precision, we unconditionally overwrite best_result.

  5. Code the helper and sorted setup

    First we write count_positives(y_val) so we can return the all-None dictionary immediately when total_positives == 0, avoiding division by zero in recall.

    from typing import Dict, List, Optional
    
    
    def count_positives(y_val: List[int]) -> int:
        """Return the total number of ground-truth positive labels (label == 1)."""
        total_positives = 0
        for label in y_val:
            if label == 1:
                total_positives += 1
        return total_positives
    

    Inside select_precision_threshold, we copy (score, label) pairs into a fresh list scored_examples (keeping the caller's y_val and scores intact) and sort it with scored_examples.sort(reverse=True). Within equal scores, Python sorts (score, 1) ahead of (score, 0), which makes no difference because the inner while loop absorbs the entire tied block before computing metrics.

  6. Walk through Example 1 and Example 2

    Let's trace Example 2 (y_val = [0, 1, 1, 0], scores = [0.40, 0.92, 0.75, 0.50], target_precision = 0.60), where total_positives = 2:

    Sorted pairs: [(0.92, 1), (0.75, 1), (0.50, 0), (0.40, 0)]
    
    Step | candidate_tau | TP | FP | precision = TP/(TP+FP) | recall = TP/2 | >= 0.60?
    -----+---------------+----+----+------------------------+---------------+---------
      1  |     0.92      |  1 |  0 |      1 / 1 = 1.00      |   1 / 2 = 0.5 |   YES -> save 0.92
      2  |     0.75      |  2 |  0 |      2 / 2 = 1.00      |   2 / 2 = 1.0 |   YES -> save 0.75
      3  |     0.50      |  2 |  1 |      2 / 3 = 0.67      |   2 / 2 = 1.0 |   YES -> save 0.50
      4  |     0.40      |  2 |  2 |      2 / 4 = 0.50      |   2 / 2 = 1.0 |   no
    

    Look closely at steps 2 and 3: both reach recall = 1.0, and even though tau = 0.75 has higher precision (1.00 vs 0.67), the tie-breaking rule prefers the lower cutoff among equal-recall candidates, so step 3 overwrites best_result with {"threshold": 0.5, "precision": 0.6666666666666666, "recall": 1.0}. Similarly, on Example 1 (target_precision = 0.75), steps at 0.95, 0.85, and 0.60 all qualify, ending with {"threshold": 0.6, "precision": 0.75, "recall": 1.0}.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_positives(y_val: List[int]) -> int:
        """Return the total number of ground-truth positive labels (label == 1)."""
        total_positives = 0
        for label in y_val:
            if label == 1:
                total_positives += 1
        return total_positives
    
    
    def select_precision_threshold(
        y_val: List[int], scores: List[float], target_precision: float
    ) -> Dict[str, Optional[float]]:
        """Select the smallest threshold tau achieving precision >= target_precision at max recall."""
        # best_result: {"threshold": tau, "precision": p, "recall": r} for the best valid tau seen
        best_result: Dict[str, Optional[float]] = {
            "threshold": None,
            "precision": None,
            "recall": None,
        }
    
        # Phase 1: Count positive labels; if zero (or empty input), recall is undefined (0 / 0).
        total_positives = count_positives(y_val)
        if total_positives == 0:
            return best_result
    
        # scored_examples: list of (score, label) pairs sorted highest score first, e.g. [(0.95, 1), (0.85, 1)]
        scored_examples = []
        for score, label in zip(scores, y_val):
            scored_examples.append((score, label))
    
        # Phase 2: Sort descending by score so sliding tau downward only ADDS items to the flagged set.
        scored_examples.sort(reverse=True)
    
        # Phase 3: Sweep candidate thresholds downward one distinct score group at a time.
        true_positives = 0
        false_positives = 0
        idx = 0
        num_examples = len(scored_examples)
    
        while idx < num_examples:
            candidate_tau = scored_examples[idx][0]
    
            # Absorb ALL items tied at `candidate_tau` before computing precision, because the rule
            # `score >= candidate_tau` flags every tied item simultaneously.
            while idx < num_examples and scored_examples[idx][0] == candidate_tau:
                label = scored_examples[idx][1]
                if label == 1:
                    true_positives += 1
                else:
                    false_positives += 1
                idx += 1
    
            flagged_count = true_positives + false_positives
            precision = true_positives / flagged_count
            recall = true_positives / total_positives
    
            # Use `>=` because exact equality (e.g. 19 / 20 == 0.95) meets the precision floor.
            if precision >= target_precision:
                # As candidate_tau strictly decreases, true_positives (and thus recall) never drops.
                # So every later qualifying tau either achieves strictly higher recall, or ties the
                # highest recall at a strictly lower threshold — winning both rules automatically.
                best_result = {
                    "threshold": candidate_tau,
                    "precision": precision,
                    "recall": recall,
                }
    
        return best_result
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine stacking scored risk alerts from the highest confidence score at the top down to the lowest score at the bottom, then sliding a divider (tau) down the pile. Every alert at or above the divider gets triggered. Precision (the share of triggered alerts that are genuinely positive, TP / (TP + FP)) tells you how clean your alert queue is, while recall (the share of all real positives in the dataset that sit above the divider, TP / total_positives) tells you how many true incidents you catch. Sweeping the divider through every distinct score traces out the precision–recall curve.

Why do simpler shortcuts fail? Recomputing TP and FP over all N validation rows for every distinct score takes O(N^2) operations, which bogs down on tens of thousands of examples. Conversely, binary-searching tau or halting the downward sweep the first time precision drops below target_precision gives wrong answers, because precision is not monotonic: encountering one negative item can push precision below the floor, and a cluster of positives right beneath it can lift precision back above the floor at even higher recall! Sorting once in descending score order and maintaining running true_positives and false_positives counts lets us evaluate every distinct cutoff in one linear sweep.

Let's walk through Example 1 (y_val = [1, 1, 0, 1, 0], scores = [0.95, 0.85, 0.70, 0.60, 0.20], target_precision = 0.75, with 3 total positives):

Divider tau = 0.95 -> flags top 1 -> TP=1, FP=0 -> precision=1.00, recall=0.33 (qualifies)
Divider tau = 0.85 -> flags top 2 -> TP=2, FP=0 -> precision=1.00, recall=0.67 (qualifies)
Divider tau = 0.70 -> flags top 3 -> TP=2, FP=1 -> precision=0.67, recall=0.67 (below 0.75)
Divider tau = 0.60 -> flags top 4 -> TP=3, FP=1 -> precision=0.75, recall=1.00 (recovers!)
Divider tau = 0.20 -> flags all 5 -> TP=3, FP=2 -> precision=0.60, recall=1.00 (below 0.75)

Because recall never shrinks as tau decreases, every later qualifying cutoff either achieves strictly higher recall or ties the highest recall at a strictly lower tau — so simply overwriting the saved answer at 0.95 -> 0.85 -> 0.60 lands directly on {"threshold": 0.6, "precision": 0.75, "recall": 1.0}.

Complexity

Let N be the number of validation examples (len(y_val)).

  • Time: O(N log N). Counting positives takes one O(N) pass, pairing and sorting scored_examples takes O(N log N), and the nested while loop advances idx once per example across the entire sweep (O(N)).
  • Space: O(N). scored_examples stores N (score, label) tuples so the caller's input lists remain untouched, while all running counters use O(1) extra space.

Edge cases

  • No cutoff reaches target_precision: best_result stays at its initial value and returns {"threshold": None, "precision": None, "recall": None}.
  • Zero positive labels ([0, 0, 0]) or empty lists ([]): total_positives == 0 returns the all-None dictionary immediately without dividing by zero.
  • Tied scores (scores = [0.8, 0.5, 0.5], y_val = [1, 1, 0]): Both 0.5 examples satisfy score >= 0.5, so the inner loop absorbs the whole tied group before computing precision = 2 / 3.
  • Precision exactly equals target_precision (3 / 4 == 0.75 or 19 / 20 == 0.95): Accepted because the precision requirement uses >=.
  • Precision dips and recovers: Continuing the sweep all the way to the minimum score catches lower cutoffs where true positives pull precision back up (Example 1).
  • Single positive example (y_val = [1], scores = [0.42]): Returns {"threshold": 0.42, "precision": 1.0, "recall": 1.0}.

Common mistakes

  • Checking precision after each individual item instead of each distinct score group: When a positive and a negative share score 0.5, tuple sorting places (0.5, 1) first; checking mid-group invents an impossible cutoff that separates identical scores.
  • Stopping early or binary-searching tau: Misses valid cutoffs whenever precision dips temporarily and later rebounds.
  • Breaking recall ties by higher precision instead of smaller tau: In Example 2, tau = 0.75 (precision = 1.0, recall = 1.0) and tau = 0.50 (precision = 2/3, recall = 1.0) tie on recall, and the specification breaks ties by smaller threshold (0.5).
  • Using strict score > tau while drawing candidates from scores: Then tau = 0.95 fails to flag the 0.95 item itself. Always pair candidate scores with >=.
  • Tuning tau on the test split: Peeking at test precision to adjust tau leaks test labels and inflates reported generalization precision.

Alternative approaches

Leak-free scikit-learn workflow. Carve out an untouched test split first using a stratified split (a random partition that preserves the positive class fraction inside every subset), split the remaining development data into train and validation, and pick the lowest qualifying cutoff via precision_recall_curve (in scikit-learn >= 1.2, thresholds is sorted ascending and precisions[:-1] aligns with thresholds):

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, precision_score, recall_score
from sklearn.model_selection import train_test_split

# 1. Isolate the test split once before any modeling or cutoff search.
X_dev, X_test, y_dev, y_test = train_test_split(
    X, y, test_size=0.20, stratify=y, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
    X_dev, y_dev, test_size=0.25, stratify=y_dev, random_state=42
)

# 2. Fit on train, then choose the smallest valid cutoff on validation.
model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
val_probs = model.predict_proba(X_val)[:, 1]
precisions, recalls, thresholds = precision_recall_curve(y_val, val_probs)
valid = precisions[:-1] >= 0.95
tau = float(thresholds[valid].min()) if valid.any() else None

# 3. Score the held-out test split a single time using the locked tau.
if tau is not None:
    test_preds = model.predict_proba(X_test)[:, 1] >= tau
    test_p = precision_score(y_test, test_preds, zero_division=0)
    test_r = recall_score(y_test, test_preds, zero_division=0)

To select tau via cross-validation on X_dev rather than a single validation split, wrap a custom make_scorer inside TunedThresholdClassifierCV(model, scoring=..., cv=5).fit(X_dev, y_dev) while still keeping X_test untouched until final reporting.

Follow-up questions

  • After locking the cutoff on validation data, how should you evaluate the held-out test split and estimate false alerts per batch? Freeze tau, compute test_preds = (test_scores >= tau) once on the untouched test split, and report test precision p, test recall, and the count of predicted positives sum(test_preds). Across a production batch of B flagged alerts (say B = 1,000), the expected count of false positives is B * (1 - p) — for instance, 50 false alerts per 1,000 flags when p = 0.95. Because high-precision cutoffs often flag only a modest number of test rows, pair the point estimate of p with a Wilson confidence interval (an accurate binomial confidence interval for proportions on small or extreme counts) so stakeholders see the sampling uncertainty around the precision target.
  • What remedies would you try if no validation score cutoff reaches the required precision, and what trade-offs do they introduce? First avoid a classic misconception: global monotonic recalibration such as Platt scaling (fitting a monotonic logistic curve to map raw scores onto calibrated probabilities) leaves the relative ordering of scores unchanged, so it produces the exact same precision–recall curve and cannot create a feasible cutoff where none existed. Effective remedies must improve top-end ranking or change the decision policy: (1) Stronger features, richer model families, or cohort-specific abstention — add domain interaction signals, move from linear models to gradient-boosted trees, audit mislabeled negatives at the top of the ranking, or restrict automated flagging to high-precision user segments while abstaining elsewhere (risks: engineering cost, noisy cutoff estimates on small segments, and validation overfitting across repeated iterations). (2) Human-in-the-loop top-k review — route only the k highest-scoring candidates matching daily analyst capacity to manual verification before taking downstream action (risks: review latency, staffing cost, and fluctuating precision under fixed k when base rates shift).
  • Why does heavy class skew make high precision difficult to achieve, and why can ROC AUC rank models poorly for this goal? Define true positive rate (TPR) as TP / P and false positive rate (FPR) as FP / N. Suppose only 5% of examples are positive (P / N = 1 / 19) and we require TP / (TP + FP) >= 0.95, which rearranges to FP <= TP / 19. Substituting TP = TPR * P and FP = FPR * N yields FPR <= TPR / 361 — catching half of all positives (TPR = 0.50) demands FPR <= 0.00138 (fewer than 1.4 false alarms per 1,000 negatives)! ROC AUC (Area Under the Receiver Operating Characteristic Curve, which integrates TPR uniformly across FPR from 0 to 1) is insensitive to class prevalence and devotes over 99% of its area to FPR > 1% regions where precision is far too low, so a model with higher ROC AUC can easily have zero recall at 0.95 precision; select models using PR AUC or recall at target precision instead. Meanwhile, probabilistic calibration (where examples scored 0.95 truly turn out positive 95% of the time) makes tau directly interpretable (tau sits near 0.95) and lets you adapt tau analytically via Bayes' rule if production prevalence drifts.

Follow-up questions

Similar questions

More Boston Consulting Group interview questions

All 23 Boston Consulting Group questions →