Bootstrap Sampling Practice Problem
This data science coding problem helps you practice Bagging Ensembles, bootstrap sampling, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Bagging Ensembles.
- Problem ID: 212
- Problem key: 212-bootstrap-sampling
- URL: https://datacrack.app/solve/212-bootstrap-sampling
- Difficulty: easy
- Topic: Bagging Ensembles
- Module: Supervised Learning
Problem Statement
# 🧩 Bootstrap Sampling
---
### 🎯 Goal
Create a bootstrap sample by randomly sampling rows from a dataset with replacement.
---
### 📖 Introduction
Bagging means **Bootstrap Aggregating**.
Before bagging can train many models, it first creates many slightly different training datasets.
A **bootstrap sample** is made by sampling from the original dataset **with replacement**.
With replacement means:
- the same row can be selected more than once
- some rows may not be selected at all
- the bootstrap sample can have any requested size
For example, if the original dataset is:
```python
["A", "B", "C", "D"]
```
and we ask for `4` sampled rows, the function should randomly choose 4 rows from the dataset.
Because sampling is random, the same code could produce different results each time. For this problem, `random_state` makes the randomness deterministic so the tests can check the output.
This is how bagging creates different versions of the training data before training many base models. In practice, these are usually many copies of the same model type, such as many decision trees.
---
### 💻 Task
Implement `bootstrap_sample(data, n_samples, random_state=0)`.
Your function should:
- Randomly sample rows from `data` with replacement.
- Return exactly `n_samples` rows.
- Allow the same row to appear more than once.
- Allow some original rows to be missing.
- Use `random_state` so the output is deterministic.
- Return `[]` when `n_samples` is `0`.
---
### 📥 Input / 📤 Output
**Input:** a dataset `data`, number of rows `n_samples`, and `random_state`.
**Output:** a bootstrap sample containing exactly `n_samples` rows.
---
### 🧩 Starter Code
```python
import random
def bootstrap_sample(data, n_samples, random_state=0):
rng = random.Random(random_state)
# Your code here
pass
```
---
### 💡 Example
```python
bootstrap_sample(["A", "B", "C", "D"], 4, random_state=0)
```
Expected output:
```python
["D", "D", "A", "C"]
```
---
### ⚠️ Common Mistakes
- Sampling without replacement.
- Returning each row at most once.
- Ignoring `random_state`, which makes tests nondeterministic.
- Returning the original dataset size instead of exactly `n_samples` rows.
- Removing duplicate sampled rows.
Starter Code
import random
def bootstrap_sample(data, n_samples, random_state=0):
rng = random.Random(random_state)
# Your code here
pass