Intermediate: machine learning · k-NN, decision trees and ensembles · topic 34 of 62 · 35 min
Decision trees
Explanation
Why trees?
People already decide with trees: "If the applicant has a regular income, check their existing loans; if those are low, approve." A decision tree learns such a flowchart from data. It handles numbers and categories, needs no scaling and can be drawn on paper, which is why banks, insurers and doctors like it.
The words
- Node: one question, such as "age < 30?".
- Root: the first question at the top.
- Branch: the path for one answer (yes or no).
- Leaf: an end point that gives the prediction (the majority class, or the average value for regression).
- Depth: how many questions lie between the root and the deepest leaf.
Choosing a split: purity
At each node, the tree tries many possible questions and picks the one that splits the data into groups that are as "pure" as possible, meaning each group is mostly one class. Gini impurity measures how mixed a group is: Gini = 1 − Σ pᵢ², where pᵢ is the share of class i. A pure group has Gini 0. A 50/50 mix of two classes has Gini 0.5.
def gini(labels):
n = len(labels)
return 1 - sum((labels.count(c) / n) ** 2 for c in set(labels))
print(gini(["yes", "yes", "no", "no"]), gini(["yes", "yes", "yes"]))For a split, compute the Gini of each side and take the weighted average by group size. The best split has the lowest weighted Gini; the drop from the parent's Gini is the information gain. Entropy (−Σ p·log₂ p) is an alternative measure that usually picks very similar splits.
Splitting on a number
For a numeric feature, the candidate thresholds are usually the midpoints between neighbouring sorted values. With incomes 20, 30, 50 and 70 thousand, the tree tries 25, 40 and 60, and keeps the threshold with the lowest weighted Gini.
Growing and stopping
The tree repeats the split search on each new group, again and again. Left alone, it keeps splitting until every leaf is pure, which usually means memorising noise. Limits stop this: max_depth caps the number of questions, min_samples_leaf requires every leaf to have enough examples, and pruning removes weak branches afterwards.
from sklearn.tree import DecisionTreeClassifier, export_text
tree = DecisionTreeClassifier(max_depth=3, min_samples_leaf=20, random_state=0)
tree.fit(X_train, y_train)
print(export_text(tree, feature_names=list(X_train.columns)))
# |--- income <= 42000.00
# | |--- existing_loans <= 1.50
# | | |--- class: approve
# ...Strengths and weaknesses
- Strengths: readable, no scaling needed, handles non-linear patterns and interactions ("young AND low income").
- Weaknesses: unstable (a small change in data can change the whole tree), overfits easily, and predictions are step-shaped, so it cannot extrapolate beyond the training range.
Common mistakes
- Leaving max_depth unlimited. Fix: tune depth and leaf size with cross-validation.
- Reading one tree's structure as "the truth" about the data. A slightly different sample may give a different tree.
- Expecting a tree to predict a house price above any price it saw in training. It cannot.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Decision trees · 1/7
A decision tree predicts by asking a series of yes or no questions.
Prefer a video by a teacher? Find free videos on “decision tree algorithm gini impurity explained” on YouTube ↗
In real life: Triage rules in a clinic
A district hospital wants a simple, explainable rule to decide which patients need a doctor first. A shallow decision tree trained on past cases produces three or four questions about fever, oxygen level and age that nurses can follow on a printed card. Accuracy is a little lower than complex models, but every decision can be explained and checked by the medical team, which matters more here.
Practice (0/2 done)
Write gini(labels) = 1 − Σ (share of each class)², rounded to 4 decimal places. Return 0.0 for an empty list.
Write best_split(xs, ys) for one numeric feature. Candidate thresholds are the midpoints between consecutive DISTINCT sorted x values. For threshold t, the left group has x <= t and the right group x > t. Score = weighted Gini = (n_left × gini_left + n_right × gini_right) / n. Return (threshold, score) for the lowest score, both rounded to 4 decimal places; on ties pick the smallest threshold. If there are fewer than 2 distinct x values, return None.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Random forests and baggingk-NN, decision trees and ensembles · same module
- Gradient boostingk-NN, decision trees and ensembles · same module
- Training: loss, backpropagation and optimisersNeural networks and deep learning
- Scaling and transforming numbersClustering, dimensionality reduction and feature engineering
- Tough interview questions: strengths, weaknesses, salarySpoken English: Zero to Fluent · English at work and interviews
- Recursive tree patternsData Structures and Algorithms (DSA) for interviews · Trees and binary search trees
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is the Gini impurity of a group where every example has the same class?
Answer: 0
A pure group has no mixing: 1 − 1² = 0.
How does a tree choose a split?
Answer: The split that gives the purest groups (lowest weighted impurity)
It searches candidate splits and keeps the purest one.
Which setting helps stop a tree from overfitting?
Answer: max_depth
Limiting depth limits how many questions the tree can ask.
A tree trained on flats priced ₹30–90 lakh is asked about a much bigger flat. What will it predict at most?
Answer: No more than the highest leaf average, around ₹90 lakh
Trees predict leaf averages, so they cannot go beyond the training range.
Do decision trees need feature scaling?
Answer: No; splits compare one feature at a time with a threshold
A threshold question works the same whatever the units.
Why can k-NN be slow at prediction time?Related
Answer: It must compare the new point with every stored example
Without an index, each prediction scans all training data.
From k-nearest neighbours
Why do random forests choose random feature subsets at each split?Related
Answer: To make the trees different from each other so their errors cancel
Diverse trees give a stronger combined vote.
Which optimiser adapts the step size for each weight and is a common default?Related
Answer: Adam
Adam keeps running averages of gradients per weight.
A hospital wants to miss as few sick patients as possible. Compared with 0.5, the threshold should usually be…Related
Answer: Lower
A lower threshold flags more people, catching more true cases at the cost of more false alarms.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 3 more topics in “k-NN, decision trees and ensembles” before its exam: Random forests and bagging, Gradient boosting, Choosing and explaining a model.
- Module 7 exam: k-NN, decision trees and ensembles · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Clustering, dimensionality reduction and feature engineering. 62 topics left in the course before the final exam.