Implement R² Score (Coefficient of Determination)
Implement R² Score (Coefficient of Determination)
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.
Examples
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)
Hint 1
Compute sse and sst using np.sum() .
Hint 2
Handle the constant-target case before dividing: if all y_true values are equal, check if predictions match exactly.
Requirements
-
Inputs: equal-length 1D arrays (NumPy arrays or lists convertible to arrays)
-
Vectorized (no Python loops)
-
Handle the constant-target edge case:
- If all y_true are equal: return 1.0 if y_pred == y_true elementwise, else return 0.0
-
Return a Python float
Constraints
- n ≤ 10⁶
- NumPy only
Log in to take notes on this problem
Accepts: array
Accepts: array
Implement R² Score (Coefficient of Determination)
Implement R² Score (Coefficient of Determination)
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.
Examples
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)
Hint 1
Compute sse and sst using np.sum() .
Hint 2
Handle the constant-target case before dividing: if all y_true values are equal, check if predictions match exactly.
Requirements
-
Inputs: equal-length 1D arrays (NumPy arrays or lists convertible to arrays)
-
Vectorized (no Python loops)
-
Handle the constant-target edge case:
- If all y_true are equal: return 1.0 if y_pred == y_true elementwise, else return 0.0
-
Return a Python float
Constraints
- n ≤ 10⁶
- NumPy only
Log in to take notes on this problem
Accepts: array
Accepts: array