← back

Implement Recall Metric in Binary Classification

#52 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Implement the recall metric for binary classification. Recall (also known as sensitivity or true positive rate) is the ratio of true positives to the total number of actual positives.

Solution

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

def recall(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))
    actual_positives = np.sum(y_true == 1)
    if actual_positives == 0:
        return 0.0
    return float(true_positives / actual_positives)

Explanation

  1. Count true positives: samples where both prediction and true label are 1.
  2. Count actual positives: all samples where the true label is 1.
  3. Recall = true_positives / actual_positives.
  4. If there are no actual 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 comparison arrays