← back

Calculate R-squared for Regression Analysis

#69 · Machine Learning · Easy

⊣ Solve on deep-ml.com

Problem

Calculate the R-squared (coefficient of determination) value for a regression model. R-squared measures how well the predicted values approximate the actual data points.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
def r_squared(y_true, y_pred):
    n = len(y_true)
    mean_y = sum(y_true) / n

    ss_total = sum((y - mean_y) ** 2 for y in y_true)
    ss_residual = sum((yt - yp) ** 2 for yt, yp in zip(y_true, y_pred))

    if ss_total == 0:
        return 1.0

    r2 = 1 - (ss_residual / ss_total)
    return round(r2, 4)

Explanation

  1. Compute the mean of the actual values.
  2. SS_total (Total Sum of Squares): sum of squared differences between actual values and their mean.
  3. SS_residual (Residual Sum of Squares): sum of squared differences between actual and predicted values.
  4. R-squared = 1 - SS_residual / SS_total.
  5. A value of 1.0 means perfect prediction; 0 means the model is no better than predicting the mean.

Complexity

  • Time: O(n) where n is the number of data points
  • Space: O(1)