Sub topic 4
Bootstrap sampling
This chapter assumes you know what a training set is, can read basic NumPy, and have met decision trees and the idea of variance in a model. Bootstrap sampling is the first of the two sources of randomness in a random forest. It decides which rows each tree sees.
What a bootstrap sample is
A bootstrap sample is a random sample drawn from your data with replacement, and it has the same size as the original. Suppose the training set has n rows. You pick a row at random, record it, and put it back. You repeat this n times. Because rows are put back, some rows appear two or three times in the sample and others never appear.
The key properties are:
- The sample has exactly
nrows, counting duplicates. - Each draw is independent of the others and uniform over all
nrows. - Each draw is made from the original data, not from the earlier draws.
The method comes from statistics, where Bradley Efron introduced it in 1979. The original use was to estimate how much a statistic would change if you could collect new data. You cannot collect new data, so you resample the data you have and treat it as a stand-in for the population.
Why resample at all in a forest
A fully grown decision tree has high variance. If you change a few training rows, the tree can change a lot. To reduce variance by averaging, you need many trees, and they must differ from each other. Averaging identical trees gives you one tree.
You usually have only one training set. Bootstrap sampling manufactures many slightly different training sets from it. Each tree trains on its own bootstrap sample, so each one makes different mistakes. Averaging their predictions cancels part of that noise. The next chapter covers that combination step, which is called bagging.
How much of the data each tree sees
Take one specific row. On a single draw, the chance of not picking it is 1 - 1/n. The sample makes n independent draws, so the chance that the row is never picked is:
(1 - 1/n)^n
As n grows, this approaches e^-1, which is about 0.368. So each row is missing from a given bootstrap sample with probability about 36.8%. It is present with probability about 63.2%.
Two consequences follow:
- A bootstrap sample contains about 63.2% of the distinct training rows. The rest of its
nslots are filled by duplicates. - About 36.8% of the rows are left out of any given tree's sample. These are the out-of-bag rows for that tree, and a later chapter uses them as a free validation set.
You can check this by simulation.
import numpy as np
rng = np.random.default_rng(0)
for n in [10, 100, 1_000, 100_000]:
idx = rng.integers(0, n, size=n) # n draws with replacement
frac_unique = len(np.unique(idx)) / n
print(f"n={n:>7}: fraction of distinct rows = {frac_unique:.3f}")
print("limit 1 - 1/e =", round(1 - np.exp(-1), 3))For small n the fraction is noisy and a little higher than 0.632, because (1 - 1/n)^n is below e^-1 at small n. For large n it settles near 0.632.
How often a row repeats
The number of times a given row appears in a bootstrap sample is a binomial count with n trials and success chance 1/n. For large n this is close to a Poisson distribution with mean 1. That gives the approximate probabilities below.
| Copies of a row in the sample | Approximate probability |
|---|---|
| 0 | 0.368 |
| 1 | 0.368 |
| 2 | 0.184 |
| 3 | 0.061 |
| 4 or more | 0.019 |
The average count is exactly 1, so the sample is the right size on average. But the spread matters. A row can appear three or four times, and then it has three or four times the influence on that tree's splits.
Bootstrap sampling in code
This example builds one bootstrap sample for 12 rows and separates the in-bag rows from the out-of-bag rows. It is the same bookkeeping a forest does for each tree.
import numpy as np
rng = np.random.default_rng(3)
n = 12
idx = rng.integers(0, n, size=n) # row indices drawn with replacement
counts = np.bincount(idx, minlength=n) # how many times each row was drawn
oob_rows = np.flatnonzero(counts == 0) # rows this tree never sees
print("drawn indices:", np.sort(idx))
print("counts per row:", counts)
print("out-of-bag rows:", oob_rows)
print("distinct in-bag rows:", np.count_nonzero(counts), "of", n)The vector counts is useful. Scikit-learn does not copy duplicated rows into a new array. It stores a weight per row equal to the number of times that row was drawn, and the tree uses those weights when it computes impurity. The result is the same as duplicating rows, with less memory.
The bootstrap as a way to estimate uncertainty
The original purpose of the bootstrap is worth seeing once, because it explains why resampling is trusted. Here you estimate the standard error of a sample mean by resampling, then compare the result with the textbook formula.
import numpy as np
rng = np.random.default_rng(1)
data = rng.exponential(scale=2.0, size=50)
boot_means = np.array([
rng.choice(data, size=len(data), replace=True).mean()
for _ in range(2_000)
])
print("bootstrap standard error:", round(boot_means.std(ddof=1), 3))
print("analytic standard error: ", round(data.std(ddof=1) / np.sqrt(len(data)), 3))The two numbers should be close. The spread of a statistic across resamples approximates its spread across real fresh samples. A forest uses the same idea. The variation between trees trained on resamples mimics the variation you would see if you trained on different datasets from the same source.
What bootstrapping does and does not do to the model
Bootstrap sampling changes the trees in several ways.
- It decorrelates the trees, but only partly. Two trees trained on different bootstrap samples still share about 40% of their distinct rows. If one feature dominates, every tree will still split on it near the root and the trees will look alike. This is why forests add random feature subsets, which the next chapters cover.
- It adds a little bias. Each tree sees about 63.2% of the distinct rows, so each individual tree is trained on less information than a tree fit on the full set. In practice the variance reduction outweighs this.
- It reweights rows. A duplicated row counts more in impurity calculations. Parameters such as
min_samples_leafcount samples, and in scikit-learn the weighted counts matter formin_weight_fraction_leaf, so duplicates can make a leaf look larger than its number of distinct rows. - It can underrepresent rare classes. If a class has 10 rows out of 10,000, a bootstrap sample could contain very few of them, or none. The chance that all 10 are missed is about
0.368^10, which is tiny, but the count of that class varies a lot between trees. For imbalanced data,class_weight="balanced_subsample"recomputes class weights on each tree's own bootstrap sample.
Controlling bootstrapping in scikit-learn
RandomForestClassifier and RandomForestRegressor expose two parameters.
| Parameter | Default | Effect |
|---|---|---|
| `bootstrap` | `True` | If `False`, every tree is trained on the full training set. Trees then differ only through feature subsampling and tie-breaking. |
| `max_samples` | `None` | With `bootstrap=True`, the size of each bootstrap sample. `None` means `n`. An integer is a row count and a float is a fraction of `n`. |
Setting max_samples=0.5, for example, makes each tree train on 500 draws out of 1,000 rows. Trees train faster and become less correlated, but each one sees less data. This is a useful tuning option on large datasets.
Be aware that oob_score=True requires bootstrap=True. With bootstrap=False there are no out-of-bag rows, and scikit-learn raises an error.
Common mistakes
- Treating a bootstrap sample as a train/test split. The in-bag and out-of-bag rows come from the same draw. Out-of-bag rows are a valid validation set for that tree, but a bootstrap sample itself is not a held-out test set.
- Resampling dependent rows as if they were independent. Bootstrap sampling assumes rows are independent draws. If your data has groups, such as several rows per patient, or has time order, rows from the same group land both in-bag and out-of-bag. The out-of-bag score then looks better than the true performance on new patients. Use group-aware cross-validation for the final estimate.
- Expecting the sample to be 63.2% of the rows. It is 63.2% of the distinct rows. The sample still has
nrows counting duplicates. - Forgetting the random seed. Different seeds give different samples. Set
random_statewhen you need reproducible forests.
Exercise
A training set has 500 rows. You draw one bootstrap sample of 500 rows. (a) Roughly how many distinct rows does the sample contain, and roughly how many rows are out-of-bag? (b) A teammate says a tree trained on this sample sees "only 63% of the data, so it must be 63% as accurate." What is wrong with that claim?
Show answer
(a) About 63.2% of 500, so roughly 316 distinct rows, and about 184 out-of-bag rows (36.8%). (b) The tree is trained on 500 weighted rows, some duplicated, so it is not a model of 63% of the data in any proportional sense. Accuracy does not scale with the share of distinct rows. The loss from seeing fewer distinct rows is small, and averaging many such trees reduces variance enough to more than offset it.
Exercise
You run RandomForestClassifier(bootstrap=False, oob_score=True). What happens, and why?
Show answer
Scikit-learn raises an error. With bootstrap=False every tree sees every row, so no row is ever out-of-bag and there is nothing to compute an out-of-bag score from.