A decision tree makes predictions by asking a series of yes/no questions about the features, such as “Is petal width at most 0.7 cm?”, until it reaches an answer. Trees are easy to read, need no feature scaling and handle both numbers and categories. On their own they overfit easily, but combining hundreds of them into a random forest gives one of the most reliable models in machine learning.
In this lesson you will learn
- How a decision tree chooses its questions
- Printing a tree as readable rules
- Feature importance
- Controlling overfitting with
max_depth - Why random forests usually beat a single tree
A Readable Decision Tree
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.3, random_state=42, stratify=iris.target
)
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(X_train, y_train)
print(f"Test accuracy: {tree.score(X_test, y_test):.3f}\n")
print(export_text(tree, feature_names=iris.feature_names))
for name, imp in zip(iris.feature_names, tree.feature_importances_):
print(f"{name:18s} importance {imp:.2f}")
Output
Test accuracy: 0.889
|--- petal width (cm) <= 0.70
| |--- class: 0
|--- petal width (cm) > 0.70
| |--- petal width (cm) <= 1.55
| | |--- class: 1
| |--- petal width (cm) > 1.55
| | |--- class: 2
sepal length (cm) importance 0.00
sepal width (cm) importance 0.00
petal length (cm) importance 0.00
petal width (cm) importance 1.00
- At each step the tree tries every feature and threshold and keeps the question that best separates the classes. “Best” is measured by Gini impurity by default: a group containing only one class has impurity 0.
- With
max_depth=2the tree asks at most two questions. One feature, petal width, is enough to separate the three species fairly well, andexport_textprints the rules in plain language. feature_importances_shows how much each feature contributed to the splits. Here petal width does all the work. Importance shows what this tree used, not what matters in the real world; correlated features such as petal length can be ignored simply because petal width was chosen first.
Depth, Overfitting and Random Forests
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_validate
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
def report(name, model):
r = cross_validate(model, X, y, cv=5, return_train_score=True)
print(f"{name:16s} train {r['train_score'].mean():.3f} test {r['test_score'].mean():.3f}")
for depth in [1, 3, 5, None]:
report(f"tree depth={depth}", DecisionTreeClassifier(max_depth=depth, random_state=0))
report("random forest", RandomForestClassifier(n_estimators=200, random_state=0))
Output
tree depth=1 train 0.924 test 0.900
tree depth=3 train 0.974 test 0.917
tree depth=5 train 0.991 test 0.916
tree depth=None train 1.000 test 0.917
random forest train 1.000 test 0.960
- The scores are averages over 5-fold cross-validation, which is fairer than a single split.
- As depth grows, training accuracy climbs to 100%: an unlimited tree keeps splitting until it has memorised every training sample. Test accuracy stops improving after depth 3. That widening gap is overfitting.
- A random forest trains many trees, each on a random sample of rows (bootstrapping) and choosing from a random subset of features at each split, and then lets them vote. The individual trees make different mistakes, so the vote cancels much of the noise. Test accuracy rises from about 0.92 to 0.96.
- Gradient boosting, covered in the XGBoost lesson, also combines trees, but builds them one after another so that each fixes the previous ones’ errors.
Settings That Control a Tree
| Parameter | What it does |
|---|---|
max_depth | Maximum number of questions from root to leaf |
min_samples_leaf | Minimum samples allowed in a final leaf; larger values give smoother trees |
min_samples_split | Minimum samples needed before a node may split |
n_estimators (forest) | Number of trees; more is steadier but slower |
max_features (forest) | How many features each split may consider |
Tree vs Forest
| Decision tree | Random forest | |
|---|---|---|
| Explainability | Excellent; rules can be printed | Harder; hundreds of trees |
| Accuracy | Moderate | Usually high |
| Overfitting | Prone to it | Much more resistant |
| Training speed | Very fast | Slower, but parallel with n_jobs=-1 |
Common Mistakes
- Leaving depth unlimited and trusting a 100% training score.
- Scaling features for trees. It is harmless but unnecessary, because splits compare values within one feature.
- Treating feature importance as causation.
- Using a single tree when accuracy matters most; try a forest or boosting.
Practice Exercises
Exercise 1. Using the printed rules, which species does a flower with petal width 1.2 cm belong to?
Show answer
1.2 is above 0.70 and at most 1.55, so the tree predicts class 1, versicolor.
Exercise 2. Print the five most important features of a random forest trained on the breast cancer data.
Show answer
data = load_breast_cancer()
forest = RandomForestClassifier(n_estimators=200, random_state=0).fit(data.data, data.target)
ranked = sorted(zip(forest.feature_importances_, data.feature_names), reverse=True)
for imp, name in ranked[:5]:
print(f"{name:25s} {imp:.3f}")
Frequently Asked Questions
Can decision trees do regression?
Yes. DecisionTreeRegressor and RandomForestRegressor predict numbers. Each leaf predicts the average target value of the training samples that reach it.
What is the difference between Gini and entropy?
Both measure how mixed the classes in a group are. They usually lead to very similar trees; Gini is slightly faster to compute, which is why it is the default.
Summary
- Decision trees split data with yes/no questions chosen to purify the classes.
- They are easy to read but overfit when grown too deep.
- Limit
max_depthormin_samples_leafto generalise better. - Random forests average many randomised trees for higher, steadier accuracy.
