← back

Implement Precision Metric

#46 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Implement the precision metric for binary classification. Precision is the ratio of true positives to the total number of predicted positives (true positives + false positives).

Solution

1
2
3
4
5
6
7
8
9
10
import numpy as np

def precision(y_true, y_pred):
    y_true = np.array(y_true)
    y_pred = np.array(y_pred)
    true_positives = np.sum((y_pred == 1) & (y_true == 1))
    predicted_positives = np.sum(y_pred == 1)
    if predicted_positives == 0:
        return 0.0
    return float(true_positives / predicted_positives)

Explanation

  1. Count true positives: samples where both the prediction and the true label are 1.
  2. Count predicted positives: all samples where the prediction is 1.
  3. Precision = true_positives / predicted_positives.
  4. If there are no predicted positives, return 0 to avoid division by zero.

Complexity

  • Time: O(n) where n is the number of samples
  • Space: O(n) for the boolean arrays