Decision trees and forests
A decision tree asks a chain of yes/no questions. A random forest asks many slightly different trees and takes a vote.
In 60 seconds
Decision trees and forests
A decision tree asks a chain of yes/no questions. A random forest asks many slightly different trees and takes a vote.
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text
iris = load_iris()
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(iris.data, iris.target)
print(export_text(tree, feature_names=list(iris.feature_names)))
print("Classes:", list(iris.target_names))Strengths and weaknesses of one tree
- A deep tree can memorise the training data, noise and all
- Small changes in the data can give a very different tree
- Its boundaries are made of steps, not smooth curves
- Easy to explain when it is small
- No need to scale features
- Handles mixed features and curved patterns
Random forests: many trees vote
- 1
Sample
Each tree gets its own random sample of the training rows (with repeats). - 2
Grow
Each tree grows, choosing each split from a random subset of features. - 3
Vote
For a new row, every tree predicts; the forest takes the majority.
Feature importance, with care
feature_importances_: roughly, how much each feature helped the splits. It is a useful hint about what the model relies on.| Setting | What it controls |
|---|---|
| max_depth | How many questions deep a tree may go. Smaller means simpler. |
| min_samples_leaf | The fewest rows allowed in a leaf. Larger means smoother. |
| n_estimators | How many trees in a forest. More is steadier but slower. |
| random_state | Fixes the randomness so results repeat. |
max_depth=2 to max_depth=4 in the code. Are the extra rules still easy to follow?Watch and read more
Lab
One decision tree and one random forest on the wine data, compared on the same test rows, plus the forest's top feature.
The problem
- Run the starter. It loads the wine data as a table and splits it.
- Fit a
DecisionTreeClassifier(random_state=0)namedtreeand aRandomForestClassifier(n_estimators=100, random_state=0)namedforest, both on the training rows. - Set
tree_accandforest_accto their test accuracies. - Set
top_featureto the name of the feature with the highestforest.feature_importances_. - Print all three. Then change the forest's
random_stateto 1 and 2. Does the top feature stay the same?
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1The forest scores higher than the tree on this split. What would you need before claiming the forest is better in general?Reveal
More than one split. The test set here has only 45 wines, so one or two mistakes change the accuracy a lot. Repeat with several splits or use cross-validation, and see if the forest wins most of the time.
Q2If the top feature changes when you change random_state, what does that tell you?Reveal
That the importance scores of the top features are close, and the ranking is not stable. Several features may carry similar information. Do not build a story on the single top feature; look at the group of important features and check them with other methods.
Questions people ask
Does a tree need scaled features?
No. A tree only asks "is this feature above this value?", so the unit does not matter.
How many trees should a forest have?
A hundred is a common starting point and the scikit-learn default. More trees rarely hurt accuracy, but they cost time and memory. Stop adding when test results stop improving.
Can trees do regression?
Yes. DecisionTreeRegressor and RandomForestRegressor predict numbers. Each leaf predicts the average label of its training rows.
What about gradient boosting?
Boosting also combines many trees, but builds them one after another, each fixing the errors of the ones before. It is often very accurate on tables. scikit-learn has HistGradientBoostingClassifier. Try it after you are comfortable with forests.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.