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 (1for a true positive instance,0for a negative instance).scores: real-valued model confidence scores or predicted probabilities aligned index-by-index withy_val.target_precision: the minimum acceptable precision (for example0.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
TPbe the count of flagged items (scores[i] >= tau) withy_val[i] == 1. - Let
FPbe the count of flagged items (scores[i] >= tau) withy_val[i] == 0. - Let
Pbe the total count of items acrossy_valwithy_val[i] == 1. - Define
precision = TP / (TP + FP)andrecall = TP / P.
Select tau according to the following rules:
- Precision floor: Keep only candidate cutoffs from
scoreswhereprecision >= target_precision. - Maximize recall: Among qualifying cutoffs, choose the one with the largest
recall. - Tie-breaking: If multiple qualifying cutoffs achieve the exact same maximum
recall, choose the smallesttau. - Infeasible or empty cases: If
y_valis empty, contains zero positive labels (P == 0), or has no candidate cutoff reachingtarget_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^5y_val[i]is either0or1.0.0 <= scores[i] <= 1.00.0 < target_precision <= 1.0
Step-by-step walkthrough
Understand the cutoff selection rules
We are given validation binary labels
y_val(0or1), model confidence valuesscores, and a required precision floortarget_precision. Let's pin down every rule of the selection contract:- Flagging rule: an item
iis predicted positive wheneverscores[i] >= tau(matching the inclusive convention ofscikit-learn'sprecision_recall_curve). - Candidate cutoffs: the distinct numbers appearing in
scores. Why restricttauto observed scores? Any number strictly between two adjacent scores (say0.80between0.85and0.70) flags the exact same subset of items as the higher score (0.85), while choosing0.85comes directly fromscores. - Metrics at
tau:precision = TP / (TP + FP)— among all flagged items (scores[i] >= tau), the fraction withy_val[i] == 1.recall = TP / total_positives— among all positive items iny_val, the fraction that got flagged.
- Objective & tie-breaker: keep only cutoffs where
precision >= target_precision. Among those, maximizerecall; if multiple cutoffs share the highestrecall, pick the smallesttau. - No valid cutoff / zero positives: when
y_valis empty, has zero positive labels (0 / 0recall), or has no cutoff reachingtarget_precision, return{"threshold": None, "precision": None, "recall": None}.
- Flagging rule: an item
Why rescanning per cutoff (or binary search) fails
A literal brute-force loop tests every distinct score
tauby scanning allNvalidation items from scratch to countTPandFP. When allNscores are distinct, that takesO(N^2)operations — billions of checks onceNreaches tens of thousands.Two tempting shortcuts also fail: binary search on
tau, and sweeping downward while stopping the momentprecisiondips belowtarget_precision. Both are incorrect because precision is not monotonic astaudecreases! 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! MISSAt
tau = 0.70, a negative item drops precision to0.67(below0.75), yet right below it attau = 0.60, another positive item pulls precision back up to0.75atrecall = 1.0! We must inspect every distinct score group from top to bottom without stopping early.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. Astausteps downward from one distinct score to the next, every previously flagged item stays flagged (score >= tauremains true), so we simply add the newly reached items to runningtrue_positivesandfalse_positivescounters.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 at0.5, settingtau = 0.5flags 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.67A two-level
whileloop handles ties cleanly: the outer loop recordscandidate_tau = scored_examples[idx][0], and the inner loop consumes all items withscore == candidate_taubefore evaluatingprecisionandrecall.Key idea 2: why the tie-breaker reduces to overwriting `best_result`
Track what happens to
recall = true_positives / total_positivesascandidate_taumoves strictly downward:- Lowering
candidate_tauonly adds items to the flagged prefix; nothing is ever removed. - Consequently,
true_positives(and thereforerecall) never decreases during the downward sweep.
Now compare an earlier qualifying cutoff
tau_highagainst any later qualifying cutofftau_low(tau_low < tau_high): - Eitherrecall(tau_low) > recall(tau_high), sotau_lowwins by higher recall; - Orrecall(tau_low) == recall(tau_high)(only negative items joined, while precision stayed>= target_precision), sotau_lowwins 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 overwritebest_result.- Lowering
Code the helper and sorted setup
First we write
count_positives(y_val)so we can return the all-Nonedictionary immediately whentotal_positives == 0, avoiding division by zero inrecall.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_positivesInside
select_precision_threshold, we copy(score, label)pairs into a fresh listscored_examples(keeping the caller'sy_valandscoresintact) and sort it withscored_examples.sort(reverse=True). Within equal scores, Python sorts(score, 1)ahead of(score, 0), which makes no difference because the innerwhileloop absorbs the entire tied block before computing metrics.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), wheretotal_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 | noLook closely at steps 2 and 3: both reach
recall = 1.0, and even thoughtau = 0.75has higher precision (1.00vs0.67), the tie-breaking rule prefers the lower cutoff among equal-recall candidates, so step 3 overwritesbest_resultwith{"threshold": 0.5, "precision": 0.6666666666666666, "recall": 1.0}. Similarly, on Example 1 (target_precision = 0.75), steps at0.95,0.85, and0.60all qualify, ending with{"threshold": 0.6, "precision": 0.75, "recall": 1.0}.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 oneO(N)pass, pairing and sortingscored_examplestakesO(N log N), and the nestedwhileloop advancesidxonce per example across the entire sweep (O(N)). - Space:
O(N).scored_examplesstoresN(score, label)tuples so the caller's input lists remain untouched, while all running counters useO(1)extra space.
Edge cases
- No cutoff reaches
target_precision:best_resultstays at its initial value and returns{"threshold": None, "precision": None, "recall": None}. - Zero positive labels (
[0, 0, 0]) or empty lists ([]):total_positives == 0returns the all-Nonedictionary immediately without dividing by zero. - Tied scores (
scores = [0.8, 0.5, 0.5],y_val = [1, 1, 0]): Both0.5examples satisfyscore >= 0.5, so the inner loop absorbs the whole tied group before computingprecision = 2 / 3. - Precision exactly equals
target_precision(3 / 4 == 0.75or19 / 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) andtau = 0.50(precision = 2/3, recall = 1.0) tie on recall, and the specification breaks ties by smaller threshold (0.5). - Using strict
score > tauwhile drawing candidates fromscores: Thentau = 0.95fails to flag the0.95item itself. Always pair candidate scores with>=. - Tuning
tauon the test split: Peeking at test precision to adjusttauleaks 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, computetest_preds = (test_scores >= tau)once on the untouched test split, and report test precisionp, test recall, and the count of predicted positivessum(test_preds). Across a production batch ofBflagged alerts (sayB = 1,000), the expected count of false positives isB * (1 - p)— for instance,50false alerts per1,000flags whenp = 0.95. Because high-precision cutoffs often flag only a modest number of test rows, pair the point estimate ofpwith 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-
kreview — route only thekhighest-scoring candidates matching daily analyst capacity to manual verification before taking downstream action (risks: review latency, staffing cost, and fluctuating precision under fixedkwhen 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) asTP / Pand false positive rate (FPR) asFP / N. Suppose only5%of examples are positive (P / N = 1 / 19) and we requireTP / (TP + FP) >= 0.95, which rearranges toFP <= TP / 19. SubstitutingTP = TPR * PandFP = FPR * NyieldsFPR <= TPR / 361— catching half of all positives (TPR = 0.50) demandsFPR <= 0.00138(fewer than1.4false alarms per1,000negatives)! ROC AUC (Area Under the Receiver Operating Characteristic Curve, which integratesTPRuniformly acrossFPRfrom0to1) is insensitive to class prevalence and devotes over99%of its area toFPR > 1%regions where precision is far too low, so a model with higher ROC AUC can easily have zero recall at0.95precision; select models using PR AUC or recall at target precision instead. Meanwhile, probabilistic calibration (where examples scored0.95truly turn out positive95%of the time) makestaudirectly interpretable (tausits near0.95) and lets you adapttauanalytically via Bayes' rule if production prevalence drifts.
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?
- What remedies would you try if no validation score cutoff reaches the required precision, and what trade-offs do they introduce?
- Why does heavy class skew make high precision difficult to achieve, and why can ROC AUC rank models poorly for this goal?
Similar questions
- Leakage-Safe SMOTE and Random Forest Pipeline
- Temporal Rare-Event Classification, Calibration, and Thresholding
- Calibrating Downsampled Credit Risk Scores for Proactive Outreach
- Leakage Audits and Point-in-Time Purchase Classification
- Retail Next-Month Purchase Pipeline and Generalization Tuning
- Curbing Tabular Overfitting Under a Tight Latency Budget
More Boston Consulting Group interview questions
- Code Review: Refactoring Python Data Pipeline Functions Medium
- Structuring Screening Behavioral Answers with STAR Easy
- Leakage-Safe SMOTE and Random Forest Pipeline Medium Pro
- Temporal Rare-Event Classification, Calibration, and Thresholding Medium Pro
- Binomial Probability and Moments for Die Rolls Easy Pro
- Fair-Coin and Without-Replacement Draw Probabilities Easy Pro
- Bayesian Coin Updating and Stopping-Time Expectation Medium Pro
- Calibrating Downsampled Credit Risk Scores for Proactive Outreach Medium Pro
- Leakage Audits and Point-in-Time Purchase Classification Hard Pro
- Presenting Your Core Engineering Stack and Workflow Easy Pro