Precision metricEasy

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 {0,1}\{0, 1\}:

precision=TPTP+FP\text{precision} = \frac{\text{TP}}{\text{TP} + \text{FP}}

where TP is the number of true-positive predictions and FP the number of false positives. Return 00 when the model predicts no positives.

Input

  • y_true — array-like of {0,1}\{0, 1\} ground-truth labels.
  • y_pred — array-like of {0,1}\{0, 1\} predictions, the same length.

Output

Returns a float in [0,1][0, 1].

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 =2/(2+1)=0.6667= 2/(2+1) = 0.6667.

Constraints

  • TP=#{y^=1 and y=1}\text{TP} = \#\{\hat{y}=1 \text{ and } y=1\}; FP=#{y^=1 and y=0}\text{FP} = \#\{\hat{y}=1 \text{ and } y=0\}.
  • If TP+FP=0\text{TP} + \text{FP} = 0 (no positive predictions), return 0.00.0 — do not divide by zero.
  • Labels are binary {0,1}\{0, 1\}.

Notes

  • Precision ignores false negatives entirely: a model that predicts positive exactly once, correctly, has precision 1.01.0 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.
Python
Loading...

This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.

  • Reference example: 2/3
  • All positive predictions correct -> 1.0
  • No positive predictions -> 0.0, not NaN
  • All false positives -> 0.0