Lessons › Chapter 6: Trees and ensembles
Random forests
A random forest is bagging with decision trees, plus one twist: at each question, a tree may only consider a few randomly chosen features. That stops every tree from leaning on the same strong clue.
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 forest for fraud
For fraud, accuracy matters more than being able to read the model, so Leo grows a whole forest.
Bagging, plus a twist
A random forest is bagging with decision trees, plus one twist: at each question, a tree may only consider a few randomly chosen features. That stops every tree from leaning on the same strong clue.
Grow a whole forest
Grow dozens or hundreds of these trees. Each one sees different rows and different features, so each has its own quirks.
Every tree votes
For a new example, each tree votes. Here 14 say “yes” and 6 say “no”, so the forest says yes, with a sense of confidence (70%) for free.
Why it works so well
Because the trees are different, their mistakes are different too, and they cancel out in the vote. Random forests are accurate, need little tuning, and rarely overfit badly, which is why they are a favorite first model for table data.
In real life: spotting fraud
Random forests are a workhorse for table data: spotting card fraud, predicting which customers might cancel, and scoring credit risk. They are fast, accurate and robust, so many teams try one first.
Quick check: What makes the trees in a random forest different from each other?
- Random samples of rows and random subsets of features (correct)
- Each uses a different loss function
- They are trained on the test set
Random rows (bagging) plus random features at each split make the trees diverse.
Pseudocode
forest = []
repeat 100 times:
bag = random sample of the rows
tree = train_tree(bag, each split looks at only a few random features)
forest.add(tree)
answer = majority vote of all the trees
Key terms
- random forest
- Many decision trees, each trained on random rows and random features, voting together.
Build it: Loan decisions with trees and forests (35 min, runs in your browser)
See the project