Implement the R² score for 1D regression targets and predictions. R² measures how much variance in the target is explained by the model, compared to a baseline that always predicts the mean of the targets.
Formula:
R2=1−∑i(yi−y)2∑i(yi−y^i)2where y is the mean of y.
Input: y_true=[3,4,5], y_pred=[2.9,4.1,5.0]
Output: R² ≈ 0.99+ (close fit)
Input: y_true=[1,1,1], y_pred=[1,1,1]
Output: 1.0 (constant, perfect)
Input: y_true=[1,1,1], y_pred=[0,2,1]
Output: 0.0 (constant, not perfect)
Compute sse and sst using np.sum() .
Handle the constant-target case before dividing: if all y_true values are equal, check if predictions match exactly.
Inputs: equal-length 1D arrays (NumPy arrays or lists convertible to arrays)
Vectorized (no Python loops)
Handle the constant-target edge case:
Return a Python float
Sign in to take notes on this problem
Accepts: array
Accepts: array
Implement the R² score for 1D regression targets and predictions. R² measures how much variance in the target is explained by the model, compared to a baseline that always predicts the mean of the targets.
Formula:
R2=1−∑i(yi−y)2∑i(yi−y^i)2where y is the mean of y.
Input: y_true=[3,4,5], y_pred=[2.9,4.1,5.0]
Output: R² ≈ 0.99+ (close fit)
Input: y_true=[1,1,1], y_pred=[1,1,1]
Output: 1.0 (constant, perfect)
Input: y_true=[1,1,1], y_pred=[0,2,1]
Output: 0.0 (constant, not perfect)
Compute sse and sst using np.sum() .
Handle the constant-target case before dividing: if all y_true values are equal, check if predictions match exactly.
Inputs: equal-length 1D arrays (NumPy arrays or lists convertible to arrays)
Vectorized (no Python loops)
Handle the constant-target edge case:
Return a Python float
Sign in to take notes on this problem
Accepts: array
Accepts: array