⚡0 XP🔥0

Decision Trees and Random Forests

Lesson 6 of 11 ⏱ 6 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs Python

How decision trees split data with Gini impurity and entropy, reading a tree, controlling overfitting with max_depth, feature importance, and ensembles - random forests and gradient boosting.

A decision tree makes predictions by asking a series of yes/no questions about the features - exactly like a flowchart a bank officer might use for a loan:

                 income > 6 LPA ?
                /               \
             yes                 no
     credit score > 700 ?     existing loans > 2 ?
       /        \               /          \
   APPROVE    REVIEW         REJECT      REVIEW

Trees are easy to explain to non-technical people, handle numbers and categories, need no scaling, and capture non-linear patterns.

How a tree chooses a split#

At every node, the algorithm tries every feature and many thresholds, and picks the split that makes the child groups purest - each group dominated by one class.

Gini impurity of a node: Gini = 1 - Σ pᵢ² where pᵢ is the share of class i.

▶ Try it YourselfPython
Ctrl + Enter to run
Output
pure node [10, 0]   : 0.0
mixed node [5, 5]   : 0.5
mostly one [9, 1]   : 0.18
split A: 0.253
split B: 0.495

Split A has much lower weighted impurity, so the tree would choose it. Entropy (-Σ pᵢ log₂ pᵢ, used to compute "information gain") is an alternative criterion that usually gives similar trees.

हिंदी में समझें

Decision tree हर कदम पर ऐसा सवाल चुनता है (जैसे "income > 6 LPA?") जिससे data दो ऐसे समूहों में बँटे जिनमें ज़्यादातर एक ही class हो - यानी समूह "शुद्ध" (pure) हों। शुद्धता Gini impurity से नापी जाती है: 0 मतलब पूरी तरह शुद्ध।

A tree in scikit-learn#

▶ Try it YourselfPython
Ctrl + Enter to run
Output
test accuracy: 0.978
|--- petal width (cm) <= 0.75
|   |--- class: 0
|--- petal width (cm) >  0.75
|   |--- petal length (cm) <= 4.75
|   |   |--- class: 1
|   |--- petal length (cm) >  4.75
|   |   |--- petal width (cm) <= 1.75
|   |   |   |--- class: 1
|   |   |--- petal width (cm) >  1.75
|   |   |   |--- class: 2

You can read the learned rules directly - try explaining that with a neural network!

▶ Try it YourselfPython
Ctrl + Enter to run

Overfitting and how to control it#

Left alone, a tree keeps splitting until every leaf is pure - memorising the training data, noise included:

▶ Try it YourselfPython
Ctrl + Enter to run
Output
max_depth=1    leaves=  2  train=0.932  test=0.889
max_depth=2    leaves=  4  train=0.942  test=0.906
max_depth=3    leaves=  8  train=0.980  test=0.901
max_depth=5    leaves= 15  train=0.997  test=0.912
max_depth=8    leaves= 16  train=1.000  test=0.906
max_depth=None leaves= 16  train=1.000  test=0.906

The unlimited tree scores 100% on training data, but not on the test set. Useful limits ("pruning" parameters):

Parameter Effect
max_depth maximum number of questions from root to leaf
min_samples_split a node needs at least this many samples to split
min_samples_leaf every leaf must keep at least this many samples
max_leaf_nodes cap on the number of leaves
ccp_alpha cost-complexity pruning strength

Random forests - the wisdom of the crowd#

One tree is unstable: small changes in the data can change it a lot. A random forest trains many trees, each on:

  • a random bootstrap sample of the rows (sampling with replacement), and
  • a random subset of features at each split,

and then lets them vote (classification) or averages them (regression). The individual trees make different mistakes, which cancel out.

▶ Try it YourselfPython
Ctrl + Enter to run
Output
single tree  : 0.906
random forest: 0.953
Top 5 features:
  worst radius           0.133
  worst perimeter        0.132
  worst concave points   0.128
  worst area             0.108
  mean concave points    0.098

Feature importance shows which inputs the forest relied on most - valuable for explaining a model to a business team.

Gradient boosting#

Another ensemble idea: build trees one after another, each new tree correcting the errors of the previous ones. Gradient boosting libraries (XGBoost, LightGBM, CatBoost, and scikit-learn's HistGradientBoostingClassifier) win most Kaggle competitions on tabular data.

▶ Try it YourselfPython
Ctrl + Enter to run
Output
gradient boosting: 0.93
Model Strengths Weaknesses
Decision tree explainable, fast, no scaling overfits, unstable
Random forest accurate, robust, little tuning slower, less explainable
Gradient boosting usually most accurate on tables more tuning, can overfit if not careful

Summary#

  • Trees split on the feature/threshold that gives the purest children (Gini or entropy).
  • Unlimited trees overfit; control with max_depth, min_samples_leaf and friends.
  • Random forests average many randomised trees for better, more stable predictions and give feature importances.
  • Gradient boosting builds trees sequentially to fix previous errors - the go-to for tabular data.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Tune tree depth

On the breast cancer data (test_size=0.3, random_state=0, stratify=y), train DecisionTreeClassifier(max_depth=d, random_state=0) for d in 1..10. Store test accuracies in a dict scores {depth: accuracy} and the depth with the best accuracy (smallest depth if tied) in best_depth. Print best_depth.

2

Random forest feature importance

Train RandomForestClassifier(n_estimators=200, random_state=42) on all of the wine data and print the names of the 3 most important features (highest feature_importances_ first) as a list stored in top3.

Quick Quiz

Q1.

A decision tree chooses each split to...

Q2.

What is the Gini impurity of a node with 50% class A and 50% class B?

Q3.

A very deep, unrestricted tree usually...

Q4.

A random forest is...

Q5.

Do decision trees need feature scaling?