InterviewPrepKit

Home / Coding / Machine Learning Coding / Metrics from Scratch / Accuracy Score

Accuracy Score

easy 00:00
Solving tips
  • Accuracy is just the fraction of positions where prediction equals truth — compare elementwise, then average.
  • y_true == y_pred gives a boolean array; np.mean of booleans treats True as 1 and False as 0, which is exactly the fraction correct.
  • Guard the empty-input case so you don't divide by zero.

Implement classification accuracy from scratch with NumPy, without using a library metric function. Accuracy is the most basic classification metric, and interviewers ask for it to check that you can turn a plain definition into clean vectorized code.

Definition

For n paired labels, accuracy is the fraction of positions where the prediction matches the truth:

accuracy = (1/n) * sum_i 1[y_pred[i] == y_true[i]]

where 1[...] is 1 when the condition holds and 0 otherwise.

Task

Complete accuracy_score(y_true, y_pred) so it returns the accuracy as a float in [0, 1]. Both inputs are 1-D NumPy arrays of integer labels of the same length. Do not call sklearn or any built-in accuracy helper.

Example

y_true = np.array([0, 1, 2, 1, 0])
y_pred = np.array([0, 2, 2, 1, 0])
accuracy_score(y_true, y_pred)   # -> 0.8

Four of the five positions match (only index 1 differs), so the accuracy is 4 / 5 = 0.8.

Constraints

  • 1 <= n <= 10^6; use vectorized NumPy, not a Python loop.
  • Labels are non-negative integers; both arrays have the same length.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug