Precision metric
Background
Precision answers "when the model predicts positive, how often is it right?" It is the metric to optimise when false positives are costly (spam filters, fraud flags), and it pairs with recall — which controls false negatives — to form the F1 score.
Problem statement
Implement precision(y_true, y_pred) for binary labels in :
where TP is the number of true-positive predictions and FP the number of false positives. Return when the model predicts no positives.
Input
y_true— array-like of ground-truth labels.y_pred— array-like of predictions, the same length.
Output
Returns a float in .
Examples
Example 1
Input: y_true = [1, 0, 1, 1, 0], y_pred = [1, 1, 1, 0, 0]
Output: 0.6667
Explanation: the predicted positives are indices 0, 1, 2; of these, 0 and 2 are truly positive (TP = 2) and 1 is not (FP = 1), so precision .
Constraints
- ; .
- If (no positive predictions), return — do not divide by zero.
- Labels are binary .
Notes
- Precision ignores false negatives entirely: a model that predicts positive exactly once, correctly, has precision no matter how many positives it misses.
- High precision with low recall is a "cautious" classifier; the F1 score (their harmonic mean) balances the two.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •reference two of three correct
- •example one true one false positive
- •sample two of three positive predictions right