Decision Trees (CART, Gini, Entropy)
Grow interpretable trees with impurity criteria and prune to control variance.
In plain words
A decision tree asks a series of questions about your data, like 'is the customer older than 40?', until it can confidently say which group the customer belongs to.
Think of it like…
A game of twenty questions: each question is chosen to split the remaining possibilities as cleanly as possible, and the game ends when the group left is so uniform that you can answer with confidence.
Where you’ve seen it
A node holds 10 customers: 6 churners and 4 non-churners. Its Gini impurity is 1 − (0.6² + 0.4²) = 0.48. A candidate split on support_tickets > 2 sends 5 customers left (4 churn, 1 stay: Gini 1 − (0.8² + 0.2²) = 0.32) and 5 right (2 churn, 3 stay: Gini 1 − (0.4² + 0.6²) = 0.48). The weighted child impurity is 0.5 × 0.32 + 0.5 × 0.48 = 0.40, so the Gini gain is 0.48 − 0.40 = 0.08. With entropy: parent = −(0.6 log₂ 0.6 + 0.4 log₂ 0.4) = 0.971 bits; children 0.722 and 0.971; weighted 0.847; information gain = 0.971 − 0.847 = 0.125 bits. A full-depth tree on 5,000 rows reaches 100% training accuracy but 71% test accuracy, with a depth of 20 and thousands of leaves; setting max_depth=5 and min_samples_leaf=30 gives 79% test accuracy, and cost-complexity pruning (ccp_alpha chosen by CV) gives 80% with a tree small enough to print on one page.
Words you’ll hear
- Gini impurity
- 1 − Σ p²: the chance two random samples from a node have different classes.
- Entropy / information gain
- Disorder in a node and the reduction in it produced by a split.
- Pruning / depth limits
- Constraints that stop the tree from memorising noise.
- Leaf
- A terminal node that outputs the prediction for all samples reaching it.
Visual diagram
Theory & deep dive
How CART grows a tree
At each node CART evaluates, for every feature, candidate thresholds (midpoints between sorted values for numeric features; subsets or one-vs-rest for categoricals) and measures the weighted impurity of the two children. For classification, Gini = 1 − Σ pₖ² is 0 for a pure node and 0.5 for a 50/50 binary node; entropy = −Σ pₖ log₂ pₖ is 0 for a pure node and 1 bit for 50/50. They usually pick nearly the same splits; Gini is slightly faster to compute. For regression trees the criterion is the reduction in variance (squared error) and the leaf predicts the mean. The best split is the one with the largest gain = parent impurity − Σ (nᵢ / n) × childᵢ impurity; recursion continues on each child until a stopping rule triggers (pure node, max depth, too few samples).
The worked example: parent 6 positive and 4 negative has Gini 0.48 and entropy 0.971; a split into (4+, 1−) and (2+, 3−) gives children Gini 0.32 and 0.48, weighted 0.40, so Gini gain 0.08; entropies 0.722 and 0.971 give weighted 0.847 and information gain 0.125 bits. The search is greedy (it takes the best immediate split and never reconsiders), which is efficient but not globally optimal. Because splits depend only on the ordering of values, trees are invariant to monotonic feature transformations and need no scaling; missing values need imputation or, in recent scikit-learn versions, native handling.
Parent (6, 4): Gini = 1 − 0.36 − 0.16 = 0.48; entropy = 0.6×0.737 + 0.4×1.322 = 0.971. Left (4, 1): Gini 0.32, entropy 0.722. Right (2, 3): Gini 0.48, entropy 0.971. Weighted Gini 0.40 → gain 0.08; weighted entropy 0.847 → gain 0.125.
Overfitting, pruning, strengths and weaknesses
An unrestricted tree keeps splitting until leaves are pure, memorising noise: a depth-20 tree on 5,000 rows can hit 100% training accuracy and 71% test accuracy. The number of leaves can reach 2^depth (1,024 at depth 10), so with 5,000 rows the average leaf has only about 5 samples. Control variance by pre-pruning (max_depth, min_samples_split, min_samples_leaf, max_leaf_nodes, min_impurity_decrease) or post-pruning with cost-complexity pruning, which minimises error + ccp_alpha × number of leaves (choose alpha by cross-validation using cost_complexity_pruning_path). Tune these hyperparameters with CV rather than the training score.
Strengths: interpretability (you can read the rules and draw the tree), handling of non-linearity and interactions, mixed data types, no scaling, fast prediction. Weaknesses: high variance (a small change in data can change the root split and the whole tree), piecewise-constant predictions (steps, no smooth extrapolation: a regression tree can't predict beyond the training range), bias toward features with many distinct values in impurity-based importances (prefer permutation importance for decisions), poor performance with additive linear relationships compared with linear models, and instability with correlated features. The cure for variance is ensembling (bagging into random forests, or boosting), which keeps the flexibility of trees and averages away their instability; single trees remain valuable for explanations, rule extraction and as weak learners.
Unpruned tree: depth 20, thousands of leaves, train 100%, test 71%. max_depth = 5 with min_samples_leaf = 30: test 79%. Cost-complexity pruning with ccp_alpha chosen by 5-fold CV: test 80% and a tree with 14 leaves that a stakeholder can read.
How it works, step by step
Step 1 of 41. Prepare the data
Encode categoricals, handle missing values and split with stratification; scaling is unnecessary.
- Leakage
- none through splits
When to use it & trade-offs
What it is
A decision tree predicts by asking a sequence of yes/no questions about features, splitting the data into ever purer groups until a leaf gives the prediction (majority class or mean value). CART (Classification and Regression Trees) builds binary trees greedily: at each node it tries candidate splits (a feature and a threshold) and picks the one that most reduces impurity, measured by Gini (1 − Σpₖ²) or entropy (−Σpₖ log₂ pₖ) for classification and by variance for regression. Left unchecked, a tree grows until it memorises the training data, so control complexity with max depth, minimum samples per leaf or cost-complexity pruning (ccp_alpha).
Why it matters: Trees are interpretable, handle mixed numeric and categorical features, need no scaling, capture non-linear effects and interactions automatically, and are the building block of random forests and gradient boosting, the dominant methods for tabular data. Their weakness (high variance: small data changes produce very different trees) is exactly what ensembles fix, so understanding a single tree explains why ensembles work.
When to reach for it
- Explainable rule-based segmentation and scoring
- Quick nonlinear baselines
- Weak learners inside ensembles
When to avoid or be careful
- Unpruned trees as final models
- Impurity-based importance for high-cardinality features
- Expecting trees to extrapolate trends
Single tree vs alternatives
Strengths: Readable; no scaling; handles interactions.
Watch out: High variance; step-wise predictions.
Strengths: Lower variance; robust defaults.
Watch out: Less interpretable; larger models.
Strengths: Strong performance; flexible losses.
Watch out: More tuning; sensitive to noise.
Interview signals & numbers to know
When this topic comes up
- “Give me interpretable rules”
- “The tree overfits”
- Gini versus entropy
- Cost-complexity pruning
- Greedy splitting
Benchmarks & rules of thumb
- Gini 0.48 → 0.40
- parent versus weighted-children impurity in the example
- 0.125 bits
- information gain of the example split
- 2^depth
- maximum number of leaves
Common mistakes & follow-ups
Common interview mistakes
- Reporting training accuracy of a full-depth tree.
- Trusting default feature importances on high-cardinality IDs.
- Scaling features for trees (unnecessary) while ignoring depth limits (necessary).
Likely interviewer follow-ups
- How does a decision tree choose a split?
- Why do decision trees overfit and how do you prevent it?
- What's the difference between Gini and entropy?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Decision Trees (CART, Gini, Entropy) with data science interview Q&A and hands-on practice.