Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Tree classifiers: decision trees and random forests

Decision trees split data by simple rules (using measures like entropy or Gini) to form interpretable classifiers; random forests build many randomized trees (bagging + feature subsampling) to reduce variance and improve accuracy.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Decision trees are simple, fast and interpretable classifiers used in engineering tasks such as fault diagnosis, feature selection and rule extraction. Random forests are ensembles of many trees that keep interpretability at the feature-importance level while giving much better accuracy and robustness for real-world noisy data.

Key ideas

Exact statement: A decision tree T is a finite rooted tree with internal nodes N and leaves L. Each internal node n ∈ N is associated with a splitting rule f_n(x) that directs x to one child; each leaf ℓ ∈ L is associated with a class label y_ℓ or a class distribution P(y|ℓ). Assume features are fixed-length real vectors and splits are deterministic.

  • Impurity: a scalar measure of class-mixing in a node. Lower impurity means the node is more “pure” (mostly one class). Common impurities: entropy, Gini impurity, misclassification error. Define them before use (see Formulas).

  • Information gain: the reduction of impurity when a parent node is split into children. For entropy impurity, Information Gain(S, split) = H(parent) − weighted average H(children). ID3 uses information gain; C4.5 primarily uses gain ratio to counter a bias toward many-way splits. Assumption: classes are categorical and class probabilities estimated by frequencies.

  • CART: Classification And Regression Trees. For classification it commonly uses Gini impurity and binary splits; for numeric features it finds the threshold that gives best impurity reduction. Assumes i.i.d. training samples. For regression it minimizes squared error (variance) and predicts the mean at leaves.

  • Overfitting and pruning: Fully grown trees fit training data and can overfit. Pruning reduces size to improve generalization. Two main kinds: pre-pruning (stop splitting early by constraints like max-depth, min-samples) and post-pruning (grow full tree then prune). A standard post-pruning is cost-complexity pruning: choose subtree T that minimizes R_alpha(T) = R(T) + alpha · |T| where R(T) is the empirical error of T on training data and |T| is number of leaves; alpha ≥ 0 controls tradeoff. In CART, one computes a sequence of subtrees via weakest-link pruning and selects alpha by cross-validation (e.g., the 1-SE rule).

  • Bagging (bootstrap aggregating): build many trees on bootstrap samples (sample with replacement) of the training set, then aggregate predictions by majority vote (classification) or average (regression). Bagging reduces variance of unstable learners (like trees) assuming errors are not perfectly correlated.

  • Random forest: an ensemble that adds an extra source of randomness: at each node of each tree, select a random subset of m_try features and find the best split among those features only. Typical choices: m_try = sqrt(p) for classification (p = number of features); for regression, a common choice is m_try ≈ p/3. Random forests use unpruned trees (grow fully) and aggregate. Approximate computational cost: training O(M · n · m_try · log n) for M trees and n samples (assuming efficient sorted split searches), prediction O(M · depth) ≈ O(M · log n).

  • Out-of-bag (OOB) estimate: for each training sample, trees that did not include that sample in their bootstrap can be used to predict it; majority vote over those trees gives an OOB prediction. The OOB error is an approximately unbiased estimate (under usual assumptions) of test error without needing separate validation data. Expected fraction of samples not included in a bootstrap sample ≈ (1 − 1/n)^n ≈ e^(−1) ≈ 0.368 (and thus ≈ 0.632 are included at least once).

  • Feature importance: Random forests estimate importance by (a) average decrease in impurity (sum over trees of impurity reduction caused by splits on a feature) or (b) permutation importance (measure drop in OOB accuracy after permuting one feature). Permutation importance is more reliable when features are correlated.

Diagram to draw for an exam (exact labels): draw a root node at top labelled “Node 0: N samples”; draw two child nodes with arrows labelled “Split: x_j ≤ t ? yes / no”; label each child with sample counts and class counts; at leaves write predicted class and probability. Also draw ensemble box showing many such trees and a majority-vote combiner.

Derivation commonly asked: show Information Gain formula. Start with parent impurity H(S) = − Σ_c p_c log2 p_c where p_c are class frequencies in S. After split into S_left and S_right, information gain = H(S) − (|S_left|/|S|) H(S_left) − (|S_right|/|S|) H(S_right). This is an exact subtraction of expected entropy after split from current entropy (see Formulas for symbols).

Assumptions to state in answers: class prior estimated by frequency, samples independent and identically distributed (i.i.d.), numeric log base 2 gives bits but choice of base only scales entropy.

Formulas

H(S) = − Σ_{c} p_c · log2(p_c) where p_c is fraction of samples in S with class c; unit: bits (dimensionless). Applies to categorical class distributions.

Gini(S) = 1 − Σ_{c} p_c^2 where p_c defined as above; unit: dimensionless. Used by CART for impurity.

Error(S) = 1 − max_c p_c misclassification impurity; unit: dimensionless.

Gain(S, split) = H(S) − Σ_{k} (|S_k|/|S|) · H(S_k) where S_k are child subsets after split; unit: bits. Applies for entropy impurity.

GainRatio = Gain / IV where IV = − Σ_k (|S_k|/|S|) log2(|S_k|/|S|) is intrinsic value; unit: dimensionless. Used in C4.5 to penalize splits with many small children.

R_α(T) = R(T) + α · |T| cost-complexity pruning measure where R(T) is empirical error (e.g., misclassification rate) of tree T and |T| is number of leaves; α ≥ 0 regularization parameter; unit: dimensionless.

E_var(ensemble) = ρ · σ^2 + (1 − ρ)/M · σ^2 approximate variance of an ensemble of M identically distributed base learners with variance σ^2 and average pairwise correlation ρ between base learner predictions; unit: (error units)^2. This explains why reducing ρ (by random feature selection) helps.

P(sample OOB for a single tree) = (1 − 1/n)^n ≈ e^(−1) ≈ 0.368 probability a given training sample is not selected in one bootstrap sample of size n (approximate for large n); unit: dimensionless.

Worked examples

Example 1 — split evaluation (exam-style numerical): Dataset: 10 training samples, 6 are Positive (P) and 4 are Negative (N). Consider binary feature A; A = true for 6 samples (4P, 2N), A = false for 4 samples (2P, 2N). Step 1: parent entropy H(parent) = −(6/10)·log2(6/10) − (4/10)·log2(4/10) = −0.6·(−0.736966) − 0.4·(−1.321928) = 0.4421796 + 0.5287712 = 0.9709508 bits. Step 2: entropy(A = true) = −(4/6)·log2(4/6) − (2/6)·log2(2/6) = −0.6666667·(−0.5849625) − 0.3333333·(−1.5849625) = 0.3899750 + 0.5283208 = 0.9182958 bits. Entropy(A = false) = −0.5·log2 0.5 − 0.5·log2 0.5 = 1.0000000 bit. Step 3: weighted child entropy = (6/10)·0.9182958 + (4/10)·1.0 = 0.5509775 + 0.4 = 0.9509775 bits. Step 4: information gain = 0.9709508 − 0.9509775 = 0.0199733 bits. Final answer: The information gain from splitting on A is ≈ 0.01997 bits.

Also compute Gini impurity reduction for same split: Parent Gini = 1 − (0.6^2 + 0.4^2) = 1 − (0.36 + 0.16) = 0.48. Gini(A = true) = 1 − ( (4/6)^2 + (2/6)^2 ) = 1 − (0.444444 + 0.111111) = 0.444445. Gini(A = false) = 1 − (0.5^2 + 0.5^2) = 0.5. Weighted Gini = 0.6·0.444445 + 0.4·0.5 = 0.266667 + 0.2 = 0.466667. Gini reduction = 0.48 − 0.466667 = 0.013333. Final answer: The Gini reduction is ≈ 0.01333.

Example 2 — model answer: Explain Random Forest and OOB estimate (exam long question) Answer outline to write in an exam:

  • Define bagging and bootstrap sampling; state that each tree is trained on a bootstrap sample of size n drawn with replacement from the n training samples. Mention expected OOB fraction ≈ 0.368.
  • Define random feature selection at each split: at each node, choose m_try random features (m_try typical choice = sqrt(p) for classification), then find best split among them.
  • State algorithm steps concisely: for t = 1..M: draw bootstrap sample, grow tree fully using random feature selection at each node, no pruning; add to forest. Prediction: majority vote over M trees.
  • Explain why variance is reduced: averaging uncorrelated estimators reduces variance by factor ≈ 1/M; for correlated trees use the formula E_var(ensemble) = ρ σ^2 + (1 − ρ)/M σ^2 and say random feature selection reduces ρ.
  • Explain OOB estimate computation: for each training sample x_i, get predictions from trees where x_i was not in bootstrap; majority vote is OOB prediction; OOB error is fraction misclassified. Note this uses no extra hold-out set.
  • Mention feature importance measures: mean decrease impurity and permutation importance; caution about correlated features.
  • Conclude by listing strengths (high accuracy, robust, works with mixed data, few hyperparameters) and weaknesses (less interpretable than a single tree, large memory/time for many trees).

This structured answer collects definitions, algorithm, theoretical reason and practical notes — enough for full marks.

Common mistakes

  • Using log base e but calling units “bits” — base must be specified (base 2 → bits). The numerical value changes by constant factor for different bases.
  • Not weighting child impurities by child sizes when computing gain.
  • In random forests, confusing bagging (bootstrap only) with random forest (bootstrap + feature subsampling). Both use bootstrap, but RF also restricts features at each split.
  • Claiming OOB error is always identical to test error: it is an unbiased estimate under usual assumptions but can differ if dataset is small or sampling assumptions fail.

For your exam

Kinds of questions:

  • Definitions (define entropy, Gini, decision tree, random forest). Answer must include formulas and units.
  • Short notes (advantages/disadvantages of trees and random forests; pruning methods). Answer lists points with short explanations.
  • Derivations (derive information gain formula and show weighted average step). Answer must show step-by-step substitution and algebra.
  • Numericals (compute entropy/Gini/gain for small data). Answer must show counts → probabilities → plug into formula → numeric final bold result.
  • Long questions (explain random forest algorithm, OOB, feature importance and reason for variance reduction). Answer should include algorithm steps, equation for variance decomposition, OOB explanation and practical advice on m_try.
  • Diagrams (draw a small decision tree and label node counts and predicted classes). Draw a root, two child nodes, label sample counts and class counts.

Full-marks answers include: precise definitions, assumptions stated (i.i.d., frequency estimates), step-by-step derivations, interpreted numerical answers and short conclusions about when a method is preferred.

Quick check

  1. Define entropy for a 3-class node with counts (3,3,4). Compute H.
  2. For a parent node with p = 0.8 positive, what is the Gini impurity?
  3. In a random forest with 500 trees and n large, approximately how many trees will leave a given sample OOB? Answers: 1) p = (0.3,0.3,0.4); H = −(0.3 log2 0.3 + 0.3 log2 0.3 + 0.4 log2 0.4) ≈ 1.571 bits. 2) Gini = 1 − (0.8^2 + 0.2^2) = 1 − (0.64 + 0.04) = 0.32. 3) ≈ 500 × 0.368 ≈ 184 trees.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?