Gradient LabStart the lesson

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 lesson

Step by step

Story

A fickle tree

Leo’s tree changes a lot every time a new month of data arrives.

Problem

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?

Key idea

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.

Build

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.

Build

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.

Real life

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?

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.