Compute the coefficient of determination for a regression model.
R^2 = 1 - SS_res / SS_tot
SS_res = sum (y_true - y_pred)^2
SS_tot = sum (y_true - mean(y_true))^2
It is the fraction of the variance in the target that the model explains. 1.0
is a perfect fit and 0.0 means the model does no better than always predicting
the mean. It can go negative, which just means the model is worse than that
baseline, and that is a genuine result rather than an error.
If SS_tot is zero, every target is identical and the ratio is undefined.
Return 1.0 if the predictions are also exact (within 1e-12), and 0.0
otherwise.
def r_squared(y_true, y_pred):
Input
y_true = np.array([3.0, -0.5, 2.0, 7.0])
y_pred = np.array([2.5, 0.0, 2.0, 8.0])
r_squared(y_true, y_pred)
Output
0.9486081370449679
Reasoning
SS_res = 0.25 + 0.25 + 0 + 1 = 1.5. The mean of y_true is 2.875, so SS_tot = 29.1875. R^2 = 1 - 1.5 / 29.1875, about 0.9486.
SS_tot is 0, return 1.0 if the predictions are exact and 0.0 if not.Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell