AI/ML

Decision Trees and Random Forests Explained with Python and scikit-learn Ep03

KaveeshaGNov 29, 2026 • 14 min read
Decision Trees and Random Forests Explained with Python and scikit-learn Ep03
Part 3 of 18

Machine Learning: From 0 to Machine

“A decision tree is a flowchart the machine writes for you. A random forest is a committee of them.”

Linear and logistic regression from Ep02 draw one straight line (or flat boundary) through the data. That works until the real pattern looks like “play tennis if it’s overcast, or if it’s sunny with normal humidity, or if it’s raining but the wind is weak”. No single line captures rules like that, but a sequence of yes/no questions does.

That is exactly what a decision tree learns. In this post we build one by hand, with entropy and information gain, then let scikit-learn build it for us. We will watch it overfit, and fix that with the third and fourth algorithms of Module 2: the tree itself, and the random forest, one of the most dependable models for tabular data you will ever use.

The core idea: twenty questions

A decision tree is the game of twenty questions, learned from data. Each internal node asks a question about one feature (“Is the outlook sunny?”), each branch is an answer, and each leaf at the bottom holds a prediction. To classify a new example you start at the root and follow the answers down until you reach a leaf.

The classic example is 14 days of weather records and whether someone played tennis. The tree in the diagram says: if it’s overcast, play. If it’s sunny, play only when humidity is normal. If it’s raining, play only when the wind is weak. Every path from root to leaf is a readable rule, which is the single biggest reason trees are popular in banking, medicine and anywhere else a decision has to be explained.

Trees handle both kinds of supervised learning. A classification tree predicts a class at each leaf (the majority class of the training examples that land there). A regression tree predicts a number (their average).

How a tree chooses its questions

The tree is built top-down and greedily. At each node it tries every possible question on every feature and keeps the one that best separates the classes. Then it repeats the process on each branch, until the leaves are pure or a stopping rule kicks in.

“Best separates” needs a number. The most common one is entropy, a measure of how mixed a group is:

H(S) = −Σ pᵢ · log₂(pᵢ)

Here pᵢ is the share of examples in class i. A group that is all “play” has entropy 0 (perfectly pure). A 50/50 mix has entropy 1, the most uncertain a two-class group can be.

Information gain is how much a question reduces entropy: the parent’s entropy minus the weighted average entropy of the children it creates.

IG = H(parent) − Σ (nᵥ / n) · H(childᵥ)

The question with the highest information gain wins.

Step 1: Calculate information gain by hand

The tennis data has 9 “play” days and 5 “don’t play” days. Here is the whole calculation for each candidate feature in a few lines of Python:

from math import log2

def entropy(counts):
    total = sum(counts)
    return -sum(c / total * log2(c / total) for c in counts if c > 0)

def information_gain(parent, children):
    n = sum(parent)
    weighted = sum(sum(child) / n * entropy(child) for child in children)
    return entropy(parent) - weighted

parent = [9, 5]                          # 14 days: 9 play, 5 don't
splits = {
    "Outlook":     [[2, 3], [4, 0], [3, 2]],   # Sunny, Overcast, Rain
    "Humidity":    [[3, 4], [6, 1]],           # High, Normal
    "Wind":        [[6, 2], [3, 3]],           # Weak, Strong
    "Temperature": [[2, 2], [4, 2], [3, 1]],   # Hot, Mild, Cool
}

print(f"root entropy: {entropy(parent):.3f}")
for name, children in splits.items():
    print(f"{name:<12} IG = {information_gain(parent, children):.3f}")

Output:

root entropy: 0.940
Outlook      IG = 0.247
Humidity     IG = 0.152
Wind         IG = 0.048
Temperature  IG = 0.029

What’s actually happening here

Splitting on outlook gives three groups: sunny [2 play, 3 don’t] with entropy 0.971, overcast [4, 0] with entropy 0, and rain [3, 2] with entropy 0.971. Weighted by group size that is 5/14 × 0.971 + 4/14 × 0 + 5/14 × 0.971 = 0.694, so the gain is 0.940 − 0.694 = 0.247, the biggest of the four. Outlook becomes the root.

The overcast branch is already pure, so it becomes a “play” leaf straight away. The tree then repeats the same calculation inside the sunny days (humidity wins there) and the rainy days (wind wins), which produces exactly the tree in the first diagram. Temperature never gets used at all: the data says it barely matters.

scikit-learn defaults to Gini impurity instead of entropy: Gini = 1 − Σ pᵢ². It measures the same thing (0 = pure, 0.5 = a 50/50 two-class mix), is slightly faster to compute, and almost always picks the same splits. Use criterion="entropy" if you want the textbook version.

Step 2: Let scikit-learn build the tree

import pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text

days = pd.DataFrame({
    "outlook":  ["sunny","sunny","overcast","rain","rain","rain","overcast",
                 "sunny","sunny","rain","sunny","overcast","overcast","rain"],
    "humidity": ["high","high","high","high","normal","normal","normal",
                 "high","normal","normal","normal","high","normal","high"],
    "wind":     ["weak","strong","weak","weak","weak","strong","strong",
                 "weak","weak","weak","strong","strong","weak","strong"],
    "play":     ["no","no","yes","yes","yes","no","yes",
                 "no","yes","yes","yes","yes","yes","no"],
})

X = pd.get_dummies(days[["outlook", "humidity", "wind"]])   # one-hot encode categories
y = days["play"]

tree = DecisionTreeClassifier(criterion="entropy", random_state=0).fit(X, y)
print(export_text(tree, feature_names=list(X.columns)))

Output:

|--- outlook_overcast <= 0.50
|   |--- humidity_high <= 0.50
|   |   |--- wind_weak <= 0.50
|   |   |   |--- outlook_rain <= 0.50
|   |   |   |   |--- class: yes
|   |   |   |--- outlook_rain >  0.50
|   |   |   |   |--- class: no
|   |   |--- wind_weak >  0.50
|   |   |   |--- class: yes
|   |--- humidity_high >  0.50
|   |   |--- outlook_rain <= 0.50
|   |   |   |--- class: no
|   |   |--- outlook_rain >  0.50
|   |   |   |--- wind_strong <= 0.50
|   |   |   |   |--- class: yes
|   |   |   |--- wind_strong >  0.50
|   |   |   |   |--- class: no
|--- outlook_overcast >  0.50
|   |--- class: yes

What’s actually happening here

scikit-learn needs numbers, so pd.get_dummies turns each category into its own 0/1 column (outlook_sunny, outlook_overcast, and so on). The tree it builds looks different from the hand-drawn one, because scikit-learn implements CART, which only ever makes binary splits (“is outlook_overcast above 0.5?”) rather than one branch per category.

Read it carefully and the logic is the same. Overcast days go straight to “yes”. Among the remaining days, the tree checks humidity and wind, and uses outlook_rain to tell sunny from rainy where it matters. Follow any path and you get one of the rules from the first diagram. export_text is worth remembering: it is how you hand a model’s logic to someone who will never read Python.

The catch: trees love to overfit

Left alone, a tree keeps splitting until every leaf is pure. On real data that means it ends up memorising noise, building a leaf for one odd patient or one mislabelled email. Let’s see it happen on the breast cancer dataset from Ep02:

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=1)

for depth in [1, 2, 3, 5, 8, None]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
    print(f"max_depth={str(depth):>4}  train={tree.score(X_train, y_train):.3f}"
          f"  test={tree.score(X_test, y_test):.3f}  leaves={tree.get_n_leaves()}")

Output:

max_depth=   1  train=0.922  test=0.906  leaves=2
max_depth=   2  train=0.962  test=0.947  leaves=4
max_depth=   3  train=0.970  test=0.953  leaves=7
max_depth=   5  train=0.992  test=0.947  leaves=13
max_depth=   8  train=1.000  test=0.947  leaves=16
max_depth=None  train=1.000  test=0.947  leaves=16

What’s actually happening here

Training accuracy keeps climbing to a perfect 1.000, because a deep enough tree can carve out a leaf for every training sample. Test accuracy, the number that matters, peaks at depth 3 with just 7 leaves and then stops improving. Everything the tree learns beyond that point is noise from the training set. That gap between train and test is overfitting, and Ep06 is dedicated to it.

You control a tree’s complexity with a few hyperparameters, a process called pruning:

  • max_depth, the maximum number of questions on any path.
  • min_samples_leaf, the minimum number of examples a leaf must hold, so no leaf exists for a single odd case.
  • min_samples_split, the minimum examples a node needs before it may split.
  • ccp_alpha, cost-complexity pruning: grow the full tree, then cut back branches that don’t earn their keep.

Choose them with cross-validation, never by looking at the test set.

There is a second, subtler problem. Trees are unstable: change a few training rows and the root question can change, which reshapes the whole tree. High variance like this is exactly what a forest fixes.

Random forests: the wisdom of many trees

Ask one doctor and you get one opinion, with all of that doctor’s quirks. Ask a hundred doctors who each studied a slightly different set of patients, and the majority is usually more reliable than any one of them. A random forest applies that idea to trees with two deliberate sources of randomness:

  1. Bootstrap samples (bagging). Each tree trains on a random sample of the rows, drawn with replacement, so every tree sees a slightly different dataset. This is called bagging, short for bootstrap aggregating.
  2. Random feature subsets. At every split, a tree may only choose from a random subset of the features (by default √n of them for classification). This stops every tree from asking the same dominant question first, so the trees make different mistakes.

To predict, every tree votes and the forest returns the majority class (for regression, the average). Individual trees may be noisy and overfit, but their errors point in different directions and largely cancel out. The result keeps the low bias of deep trees while removing much of their variance.

Step 3: A single tree vs a forest

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier

data = load_breast_cancer()
X, y = data.data, data.target

tree = DecisionTreeClassifier(random_state=0)
forest = RandomForestClassifier(n_estimators=300, random_state=0, n_jobs=-1)

for name, model in [("single tree", tree), ("random forest", forest)]:
    scores = cross_val_score(model, X, y, cv=5)      # 5-fold cross-validation
    print(f"{name:<14} accuracy = {scores.mean():.3f} ± {scores.std():.3f}")

forest.fit(X, y)
top = sorted(zip(forest.feature_importances_, data.feature_names), reverse=True)[:5]
for importance, feature in top:
    print(f"{feature:<22} {importance:.3f}")

Output:

single tree    accuracy = 0.917 ± 0.016
random forest  accuracy = 0.963 ± 0.022
worst radius           0.125
worst concave points   0.125
worst perimeter        0.120
worst area             0.110
mean concave points    0.102

What’s actually happening here

cross_val_score with cv=5 splits the data into five parts, trains on four and tests on the fifth, five times over, then reports the average. That is a far more trustworthy comparison than a single train/test split (more on this in Ep06).

The forest of 300 trees scores 0.963 against 0.917 for a single unpruned tree, with no tuning at all. n_jobs=-1 trains the trees in parallel on every CPU core, which is possible because each tree is independent.

feature_importances_ shows how much each feature reduced impurity across all the trees. Tumour size and shape measurements (radius, perimeter, area, concave points) dominate, which matches medical intuition. You lose the single readable flowchart of one tree, but you still get a clear ranking of what drives the predictions.

Trees vs forests: when to use which

  • Use a single decision tree when the model must be explained rule by rule: loan approvals, medical triage protocols, any decision a regulator or customer will question. Keep it shallow and prune it.
  • Use a random forest when accuracy on tabular data matters more than a readable flowchart: fraud detection, credit risk, churn, disease risk, sensor data. It is the strong default baseline that is hard to beat without effort.
  • Both need no feature scaling: a split on “radius > 15” works the same whatever the units. Both handle a mix of numeric and categorical features (after encoding) and capture non-linear patterns and feature interactions automatically.

Common first-tree mistakes

  • Leaving max_depth=None on a single tree and celebrating 100% training accuracy. Check the test score.
  • Tuning depth on the test set. Use cross-validation, and keep the test set for the very end.
  • Reading too much into one tree’s structure. Retrain on a slightly different sample and the root question may change. Trust forest feature importances over a single tree’s layout.
  • Trusting impurity-based importances blindly. They favour features with many distinct values (like IDs or continuous measurements). For important decisions, cross-check with sklearn.inspection.permutation_importance.
  • Assuming more trees always helps. Beyond a few hundred, accuracy plateaus while training time and memory keep growing.

The honest limitations

Decision trees split along one feature at a time, so their boundaries are staircases of axis-aligned steps; a smooth diagonal boundary needs many splits to approximate. They overfit easily and are unstable. Random forests fix most of that, but at a price: hundreds of trees are slower to predict and larger to deploy, and you can no longer print the model on one page. Neither can extrapolate: a regression forest trained on prices up to Rs. 50 million will never predict Rs. 80 million, because each leaf can only return an average of values it has already seen.


Where to go next

A random forest builds its trees independently and lets them vote. In Ep04 we flip that idea: gradient boosting builds trees one after another, each fixing the mistakes of the last, and it wins a huge share of tabular-data competitions. We will pair it with the support vector machine, which takes a completely different route: finding the widest possible gap between classes, and bending space with the kernel trick when no straight gap exists.


This post is part of the CeyTech series Machine Learning: From 0 to Machine – deep tech, no fluff. Try adding temperature back into the tennis data, or set max_depth=3 on the forest, and tell me what changed.




Share this story:

Comments (...)

You must be signed in to join the discussion.

Loading comments...