R-Squared: How Much Better Than the Mean?

Metrics & EvaluationEasy+10 XP+10

R-Squared: How Much Better Than the Mean?

R² asks how much better your regression is than the laziest possible model — one that ignores the inputs and always predicts the mean.

1R² = 1 - SS_res / SS_tot
2
3SS_res = Σ (y - prediction)² your squared error
4SS_tot = Σ (y - mean(y))² the mean-predictor's squared error

Task: write r2_score(y_true, y_pred) returning R², rounded to 4 decimal places.

  • If SS_tot is zero (every true value identical) return 0.0.

The upper bound is 1, but there's no lower one. Predicting worse than the mean gives a negative R², which is a genuinely useful signal — it means the model isn't just weak, it's actively worse than a constant.

Examples

y_true = [3.0, -0.5, 2.0, 7.0]
y_pred = [2.5, 0.0, 2.0, 8.0]
returns 0.9486
y_true = [1.0, 2.0, 3.0]
y_pred = [1.0, 2.0, 3.0]
returns 1.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run