InterviewPrepKit

Home / Coding / Machine Learning Coding / Metrics from Scratch / R-Squared Score

R-Squared Score

easy 00:00
Solving tips
  • R^2 compares your model's residual error against the error of a baseline that always predicts the mean of y_true.
  • SS_res uses predictions; SS_tot uses the mean of the ground truth — do not mix them up.
  • When SS_tot is 0 the target is constant, so the usual formula divides by zero — decide and state what to return.

Implement the coefficient of determination (R^2) from scratch with NumPy, without using a library metric function. R^2 tells you how much of the variance in the target a model explains relative to a naive baseline that always predicts the mean, and interviewers use it to check that you understand both the formula and its edge cases.

Definition

For n paired values, R^2 is one minus the ratio of the residual sum of squares to the total sum of squares:

SS_res = sum_i (y_true[i] - y_pred[i])^2
SS_tot = sum_i (y_true[i] - mean(y_true))^2
R2     = 1 - SS_res / SS_tot

SS_res is the model’s squared error, and SS_tot is the squared error of always predicting mean(y_true).

Task

Complete r2_score(y_true, y_pred) so it returns the R^2 score as a float. Both inputs are 1-D NumPy arrays of the same length. Handle the case where SS_tot == 0 (the target is constant): return 1.0 when the predictions are also perfect (SS_res == 0), otherwise return 0.0. Do not call sklearn or any built-in R^2 helper.

Example

y_true = np.array([3.0, 5.0, 2.5, 7.0])
y_pred = np.array([2.5, 5.0, 4.0, 8.0])
r2_score(y_true, y_pred)   # -> 0.8135593220338984

The residuals are [0.5, 0.0, -1.5, -1.0], so SS_res = 0.25 + 0.0 + 2.25 + 1.0 = 3.5. The mean of y_true is 4.375, so SS_tot = 1.890625 + 0.390625 + 3.515625 + 6.890625 = 12.6875, and 1 - 3.5 / 12.6875 ≈ 0.8136.

Constraints

  • 1 <= n <= 10^6; use vectorized NumPy, not a Python loop.
  • Values fit in float64.
  • R^2 can be negative when the model is worse than predicting the mean; do not clamp it.

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