Problems
Loading...
1 / 1

Implement R² Score (Coefficient of Determination)

Metrics & Evaluation
Easy

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=1i(yiy^i)2i(yiy)2R^2 = 1 - \frac{\sum_i (y_i - \hat{y}_i)^2}{\sum_i (y_i - \overline{y})^2}

where y\overline{y} is the mean of y.

Loading visualization...

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
Try Similar Problems