Best Recall Cutoff That Meets a Minimum Precision Target
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Tests threshold search on a scored ranking: find the cut-point that maximises recall while keeping precision at or above a given floor, with correct tie-breaking.
Best Recall Cutoff That Meets a Minimum Precision Target
A binary classifier outputs a numeric confidence score for each item. You flag an item as positive whenever its score is at or above some cutoff τ. Raising τ flags fewer items; lowering it flags more.
Given the true labels and scores from a held-out validation set, find the cutoff that maximises recall among all cutoffs where precision is at least min_precision. Break ties in recall by preferring the lower cutoff (flags more items while keeping precision in bounds). If multiple cutoffs tie on both recall and the lower-cutoff rule, any one of them is acceptable.
Return a dictionary with three keys:
"threshold"— the chosen cutoff value (a float from the input scores)"precision"— exact precision at that cutoff"recall"— exact recall at that cutoff
If there are no positive labels in the validation set, or if no cutoff achieves precision ≥ min_precision, return {"threshold": None, "precision": None, "recall": None}.
Definitions
For a given cutoff τ:
- Predicted positives (PP): items whose score ≥ τ
- True positives (TP): items that are both predicted positive and actually positive
precision = TP / PP(undefined when PP = 0; such a cutoff is never a valid candidate)recall = TP / (total actual positives)
Tie-group rule
Items that share the same score value must be treated as a unit. Either all of them are above the cutoff or none of them are. When computing precision and recall at cutoff τ, include every item whose score equals τ.
Constraints
1 ≤ len(labels) ≤ 50 000len(labels) == len(scores)- Each element of
labelsis0or1 0.0 < min_precision ≤ 1.0- Scores are finite floats; duplicates are allowed
- The "flag nothing" operating point (PP = 0) is never a valid candidate because its precision is undefined
Examples
Example 1
Input: find_best_recall_cutoff([1, 0, 1, 0], [0.9, 0.8, 0.7, 0.1], 0.95)
Output: {'threshold': 0.9, 'precision': 1, 'recall': 0.5}
Example 2
Input: find_best_recall_cutoff([1, 0, 1, 0], [0.9, 0.8, 0.7, 0.1], 0.5)
Output: {'threshold': 0.1, 'precision': 0.5, 'recall': 1}
Hints
Hint 1
Sort items by descending score and walk the list once, accumulating true-positive and predicted-positive counts. Each distinct score value is one candidate cutoff — flush the counts only after processing the whole tie group at that score.
Hint 2
Precision is not guaranteed to decrease monotonically as you lower the cutoff. You cannot stop at the first violation; you must scan every distinct score and collect every candidate that meets the precision floor.
Hint 3
Store feasible candidates as (recall, -threshold, ...) so that a single call to max() gives the highest recall first, then the lowest threshold as the tie-breaker.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
Sorting the items by descending score turns the threshold-search problem into a single linear scan. As you lower the cutoff τ, you admit more items. Every distinct score value defines one meaningful operating point: the precision and recall you get when τ equals that score. Scores strictly between two adjacent values produce the same flagged set as the higher of the two, so nothing is missed by only checking distinct values.
Algorithm
- Check for the degenerate case: if there are no positive labels, recall is undefined everywhere and the function returns
Nonefor all fields. - Sort
(score, label)pairs in descending order of score. - Walk the sorted list, processing one tie group at a time — all items sharing the same score value. Add their labels to running totals for true positives and predicted positives only after the entire group is consumed. This ensures the rule "flag iff score ≥ τ" is respected: you cannot split a tie group.
- After each group, compute exact precision and recall for that operating point. If precision meets the floor, record the candidate as
(recall, -threshold, threshold, precision). - Take
maxover all candidates. Python's tuple comparison handles the tie-breaking automatically: it first maximises recall, then minimises-threshold(i.e. maximises the threshold magnitude negated, meaning it minimises the actual threshold). - If no candidates were collected, return all
None.
Why precision is not monotonic
Lowering the cutoff adds more items. If a cluster of positives sits just below the current cutoff, including them can raise precision temporarily. This means you cannot stop scanning at the first precision violation — every distinct score must be evaluated.
Why the tie-breaker (lower cutoff) is correct
Among all cutoffs with the same best recall, a lower cutoff only adds true negatives and possibly more true positives to the flagged set. Since we only keep candidates that already meet the precision floor, choosing the lower threshold gives strictly more coverage at no cost to the constraint.
Edge cases
- No positives in
labels: returns allNone. - No cutoff reaches
min_precision: returns allNone. - All scores identical: one candidate; precision equals dataset prevalence, which typically falls below a high target like 0.95.
min_precision = 1.0: feasible only if the top tie group contains exclusively positive items.
Complexity
- Time: O(n log n) for the sort, O(n) for the scan — dominated by sorting.
- Space: O(n) for the sorted pairs and the candidate list.
Full reference solution
from typing import Dict, List, Optional
def find_best_recall_cutoff(
labels: List[int],
scores: List[float],
min_precision: float,
) -> Dict[str, Optional[float]]:
total_positives = sum(labels)
if total_positives == 0:
return {"threshold": None, "precision": None, "recall": None}
# Sort by descending score so we can sweep from the most confident
# prediction down to the least confident.
pairs = sorted(zip(scores, labels), reverse=True)
true_positives = 0
predicted_positives = 0
candidates = []
i = 0
while i < len(pairs):
# Identify the current score level and consume the whole tie group.
cutoff = pairs[i][0]
while i < len(pairs) and pairs[i][0] == cutoff:
true_positives += pairs[i][1]
predicted_positives += 1
i += 1
# Evaluate precision and recall for the operating point: score >= cutoff.
precision = true_positives / predicted_positives
recall = true_positives / total_positives
if precision >= min_precision:
# Store (recall, -cutoff) so max() picks highest recall,
# then lowest cutoff (most permissive) as the tie-breaker.
candidates.append((recall, -cutoff, cutoff, precision))
if not candidates:
return {"threshold": None, "precision": None, "recall": None}
best_recall, _, threshold, precision = max(candidates)
return {"threshold": threshold, "precision": precision, "recall": best_recall}