← back

Calculate Accuracy Score

#36 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the accuracy score of predictions compared to true labels. Given two arrays (true labels and predicted labels), return the fraction of correct predictions.

Solution

1
2
3
4
5
6
7
import numpy as np

def accuracy_score(y_true, y_pred):
    y_true = np.array(y_true)
    y_pred = np.array(y_pred)
    correct = np.sum(y_true == y_pred)
    return correct / len(y_true)

Explanation

  1. Convert inputs to NumPy arrays for element-wise comparison.
  2. Compare predicted labels to true labels element-wise, producing a boolean array.
  3. Sum the True values (correct predictions).
  4. Divide by the total number of samples to get the accuracy ratio.

Complexity

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