Lessons › Chapter 6: Trees and ensembles
Bagging
Draw random samples from the data, putting each row back after picking it. Some rows show up twice and others not at all. Each sample is a bootstrap bag.
Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.
Start the interactive lessonStep by step
A fickle tree
Leo’s tree changes a lot every time a new month of data arrives.
One model is jumpy
A single decision tree can change a lot if you change the training data even slightly. That’s high variance. What if we trained many trees and let them vote?
Make bootstrap bags
Draw random samples from the data, putting each row back after picking it. Some rows show up twice and others not at all. Each sample is a bootstrap bag.
One model per bag
Train a separate tree on each bag. Because the bags differ, the trees learn slightly different things and make different mistakes.
Let them vote
For a new example, every tree gives its answer and the majority wins: here 2 votes to 1. Individual mistakes tend to cancel out. This is bagging: bootstrap aggregating.
In real life: asking several doctors
Getting a second and third opinion from doctors with different experience, then going with the majority, is bagging in everyday life. Each opinion alone might be off; together they are more reliable.
Quick check: In bagging, what are the many models trained on?
- Different random samples of the data (correct)
- Different subsets of the test set
- Exactly the same data
Each model gets its own bootstrap sample, which makes their mistakes different so voting helps.
Pseudocode
models = []
repeat 3 times:
bag = random sample of the data, with replacement
models.add(train_tree(bag))
new example → each model votes
answer = majority vote (or the average for numbers)
Key terms
- bootstrap
- A random sample of the data, drawn with replacement, so some rows repeat and others are left out.
- bagging
- Training many models on bootstrap samples and letting them vote.