F1 Score Practice Problem
This data science coding problem helps you practice Evaluation Metrics for Classification, f1 score, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Evaluation Metrics for Classification.
- Problem ID: 147
- Problem key: 147-f1-score
- URL: https://datacrack.app/solve/147-f1-score
- Difficulty: easy
- Topic: Evaluation Metrics for Classification
- Module: Introduction to Machine Learning
Problem Statement
## š§© F1 Score
### šÆ Goal
Compute the **F1 Score** ā a metric that balances both precision and recall into a single value.
---
### š„ Input / š¤ Output
**Input**
- `y_true` (`list[int]`): true labels (0 or 1)
- `y_pred` (`list[int]`): predicted labels (0 or 1)
**Assumption:**
- `y_true` and `y_pred` have the same non-zero length.
- Labels are binary (0 or 1).
**Output**
- `float`: F1 score
---
### š» Task Description
The F1 Score is the **harmonic mean** of precision and recall. It provides a better measure of a model's performance on imbalanced datasets than accuracy.
It is defined as:
$$
F_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}
$$
Steps to compute:
1. Calculate **TP**, **FP**, and **FN**.
2. Compute **Precision** = $TP / (TP + FP)$.
3. Compute **Recall** = $TP / (TP + FN)$.
4. Compute **F1 Score** using the formula above.
ā ļø **Edge Case:** If (Precision + Recall) is 0, the F1 Score should be `0.0`.
---
### š§© Starter Code
```python
def f1_score(y_true, y_pred):
"""
Returns the F1 Score.
"""
pass
```
---
### š” Example
```python
y_true = [1, 0, 1, 1, 0]
y_pred = [1, 1, 1, 0, 0]
f1_score(y_true, y_pred)
```
**Expected Output**
```
0.7272727273
```
---
Starter Code
def f1_score(y_true, y_pred):
"""
Returns the F1 Score.
"""
pass