R-squared Score
~15 mincode completion
Implement r_squared(y_true, y_pred).
Examples
Perfect predictions: R2 = 1.0
- Input
- r_squared([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
- Output
- 1
Predicting the mean: R2 = 0.0
- Input
- r_squared([2, 4, 6, 8, 10], [6, 6, 6, 6, 6])
- Output
- 0
Good but not perfect predictions
- Input
- r_squared([1, 2, 3], [1.5, 2, 2.5])
- Output
- 0.75
Hints
Hint 1
Sum with , and check which axis you are summing over.
Hint 2
Watch for this: computed ss tot as variance not sum.
Requirements
y_true: Ground truth values, shape (m,)y_pred: Predicted values, shape (m,)Return R² score (float). Can be negative.
Constraints
Allowed library: NumPy only
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~15 min
••••••••••••••••
8 employers weight this skill
2 health and bio companies, 2 quant funds, 2 enterprise vendors, 1 AI product company, 1 frontier lab. Top match scores 87.
Python
import numpy as np
def r_squared(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""
Compute the R-squared score.
Args:
y_true: Ground truth values, shape (m,)
y_pred: Predicted values, shape (m,)
Returns:
R² score (float). Can be negative.
"""
# YOUR CODE HERE
pass