#69 · Machine Learning · Easy
⊣ Solve on deep-ml.comCalculate the R-squared (coefficient of determination) value for a regression model. R-squared measures how well the predicted values approximate the actual data points.
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)