R2 Practice Problem
This data science coding problem helps you practice Evaluation Metrics for Regression, r2, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Evaluation Metrics for Regression.
- Problem ID: 19
- Problem key: 19-r2
- URL: https://datacrack.app/solve/19-r2
- Difficulty: easy
- Topic: Evaluation Metrics for Regression
- Module: Introduction to Machine Learning
Problem Statement
## 🧩 R² Score (Coefficient of Determination)
### 🎯 Goal
Measure how well a regression model explains the variation in the target values compared to a simple mean-based baseline.
---
### 📥 Input / 📤 Output
**Input**
- `y_true` (`list[float]`): true target values
- `y_pred` (`list[float]`): predicted values from a regression model
**Output**
- `float`: the R² score
---
### 💻 Task Description
1. Compute the mean of `y_true`
2. Compute the **residual sum of squares (RSS)**
3. Compute the **total sum of squares (TSS)**
4. Return the R² score:
$$R^2 = 1 - \frac{\sum (y_{\text{true}} - y_{\text{pred}})^2}{\sum (y_{\text{true}} - \bar{y}_{\text{true}})^2}$$
R² compares your model against a baseline that always predicts the mean.
---
### 🧩 Starter Code
```python
import numpy as np
def r2_score(y_true, y_pred):
"""
Returns the R² score.
"""
pass
```
---
### 💡 Example
```python
y_true = [3, -1, 2]
y_pred = [2, 0, 2]
r2_score(y_true, y_pred)
```
**Expected Output**
```
0.76923
```
---
Starter Code
import numpy as np
def r2_score(y_true, y_pred):
"""
Returns the R² score.
"""
pass