← Courses

Intro to Machine Learning

AI / ML

Building a Model · Lesson 6 of 7

Random forests

From one tree to a forest

A single decision tree leaves you stuck between two bad options: too deep and it overfits, too shallow and it underfits. Even advanced models live with this tension, but many use clever ideas to handle it better. The random forest is one of the most useful.

A random forest builds many decision trees, each slightly different, and makes its prediction by averaging the predictions of all of them. One tree might err in one direction and another in a different direction, so averaging cancels out much of the error. The result is usually more accurate than any single tree, and much less likely to overfit.

Building one

You build a random forest exactly like a decision tree, you just swap in the RandomForestRegressor class. Here we train both on the same data and compare their validation errors:

Python

Compare the two errors. With almost no extra effort, the forest usually does better.

Why it is a great default

The best part: a random forest works well straight out of the box. A single tree needs you to tune max_leaf_nodes carefully to find its sweet spot. A random forest gives strong results with its default settings, so it is an excellent model to reach for first, before you spend any time tuning. You can tune it later for a little more, but you rarely have to. That mix of high accuracy and low fuss is why it is so widely used.

Exercise

Exercise — check your understanding

Define a RandomForestRegressor called forest with random_state=1. The line that fits it on train_X and train_y is already written for you.

You’re reading for free. Sign in to keep your progress and earn a certificate when you finish.Sign in to keep my progress →