Knowledge / Artificial Intelligence and Data Science / Decision trees and random forests

Decision trees and random forests

Artificial Intelligence and Data Science (B.E./B.Tech) · Machine learning · free study notes for exams, placements and interviews

In short

A decision tree is a flowchart-like model that repeatedly splits data on one feature at a time until each leaf is reasonably pure, giving a prediction rule a human can read off the diagram. A random forest grows many de-correlated trees on bootstrap samples with random feature subsets and averages (or votes over) them, trading the single tree's interpretability for much lower variance and strong accuracy on tabular data. Both are standard in GATE DA/CS (entropy, information gain, Gini numericals), in university ML papers (ID3/C4.5/CART algorithms, pruning) and in placement rounds at TCS, Infosys, Wipro, Mu Sigma, Fractal, ZS, Flipkart and bank/NBFC analytics teams. In Indian industry they are the default first model for credit scoring, fraud flags, churn and claim triage because they handle mixed feature types, need little scaling and produce auditable rules — useful under RBI's expectation that a lender can explain a rejection.

Explained

Structure and basic definitions

Split criteria (impurity measures)

Building a tree step by step (CART)

  1. Start with all n training rows at the root.
  2. For every feature and every candidate threshold, compute the impurity of the two children and the weighted impurity.
    • Numeric feature: sort the distinct values, test midpoints between consecutive values (at most n−1 thresholds) with test x ≤ t.
    • Categorical feature: binary partitions of the category set; for a two-class target the categories can be ordered by the positive-class rate, which reduces 2m−1−1 subsets to m−1 cuts.
  3. Pick the split with the largest impurity decrease; create two children and send each row down the matching branch.
  4. Recurse on each child.
  5. Stop when: node is pure, node size < min_samples_split, a child would be smaller than min_samples_leaf, depth = max_depth, impurity decrease < min_impurity_decrease, or no feature separates the rows.
  6. Label each leaf (majority class / mean) and optionally prune.
  7. Complexity: training is roughly O(d · n log n) with pre-sorted features; prediction is O(depth) ≈ O(log n) for a balanced tree — one reason trees are used in low-latency scoring.
  8. Missing values: C4.5 sends a fractional instance down every branch weighted by branch frequency; CART uses surrogate splits (a correlated backup feature). scikit-learn's trees accepted missing values in numeric features from version 1.3 onward (behaviour depends on version — check before relying on it); the usual Indian-industry practice is still explicit imputation or a "missing" category.

Overfitting and pruning

Bagging and random forests

Feature importance and interpretability

Advantages and limitations

Single decision treeRandom forest
InterpretabilityHigh — readable rulesLow — needs SHAP/PDP
Bias / varianceLow bias, high varianceLow bias, low variance
Training costVery lowB × tree cost (parallelisable)
Scaling / encoding neededNo scaling; handles mixed typesSame
ExtrapolationCannot predict beyond training target rangeSame
StabilityOne changed row can alter the whole treeVery stable
Typical accuracy on tabular dataModerateHigh

Key points

Formulas and examples

Entropy: H(S) = − Σᵢ₌₁ᵏ pᵢ log₂ pᵢ (pᵢ = fraction of class i in node S; unit = bits)
Information gain: IG(S, A) = H(S) − Σⱼ (|Sⱼ|/|S|) · H(Sⱼ) (Sⱼ = subset in branch j)
Split information: SplitInfo(S, A) = − Σⱼ (|Sⱼ|/|S|) log₂(|Sⱼ|/|S|); Gain ratio = IG / SplitInfo
Gini index: G(S) = 1 − Σᵢ pᵢ²; Gini gain = G(S) − Σⱼ (|Sⱼ|/|S|) G(Sⱼ)
Misclassification error: E(S) = 1 − maxᵢ pᵢ
Regression split: SSE(S) = Σ (yᵢ − ȳ)²; variance reduction = Var(S) − Σⱼ (|Sⱼ|/|S|) Var(Sⱼ)
Cost-complexity: R_α(T) = R(T) + α·|leaves(T)| (R = misclassification/SSE cost, α ≥ 0 in the same units per leaf)
OOB fraction: (1 − 1/n)n → e⁻¹ ≈ 0.368, so ≈63.2% of rows are in-bag
Ensemble variance: Var = ρσ² + (1 − ρ)σ²/B (σ² = single-tree variance, ρ = pairwise correlation, B = number of trees)
Majority vote: ŷ = mode{h_b(x)}; soft vote: ŷ = argmax_c (1/B) Σ_b P_b(c|x); regression: ŷ = (1/B) Σ_b h_b(x)

Example 1 — Entropy and information gain (ID3), placement-offer data (14 rows). Target: Placed (Yes/No) — 9 Yes, 5 No.

Example 2 — Gini index for the same two candidate splits.

Example 3 — Numeric threshold for a regression tree (salary in ₹ lakh per annum). Experience (years) x = 1, 2, 3, 4, 5; Salary y = 4, 5, 7, 10, 14 (₹ lakh).

Example 4 — Cost-complexity pruning. A subtree with 4 leaves misclassifies 10 of 200 training rows; collapsing it to one leaf misclassifies 22.

Example 5 — Forest variance and OOB. Single tree variance σ² = 0.09, pairwise correlation ρ = 0.4, B = 100 trees.

AspectID3C4.5CARTCHAID
CriterionInformation gainGain ratioGini / SSEChi-square
SplitsMulti-wayMulti-wayBinary onlyMulti-way
FeaturesCategorical onlyBothBothBoth
TargetClassificationClassificationClassification + regressionBoth
PruningNoneRule/error-basedCost-complexitySignificance stopping
Missing valuesNot handledFractional instancesSurrogate splitsSeparate category
from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.inspection import permutation_importance

tree = DecisionTreeClassifier(criterion="gini", max_depth=4,
                              min_samples_leaf=20, ccp_alpha=0.002,
                              class_weight="balanced", random_state=42).fit(X_tr, y_tr)
print(export_text(tree, feature_names=list(X_tr.columns)))   # auditable rules

rf = RandomForestClassifier(n_estimators=500, max_features="sqrt",
                            min_samples_leaf=5, oob_score=True,
                            class_weight="balanced_subsample",
                            n_jobs=-1, random_state=42).fit(X_tr, y_tr)
print(rf.oob_score_)                                          # free validation estimate
print(permutation_importance(rf, X_te, y_te, n_repeats=10, random_state=42).importances_mean)

Where it is used

Interview questions

Common mistakes

Related topics

Ensemble methods and gradient boosting · Overfitting, bias-variance and regularisation · Model evaluation metrics · Feature selection and model interpretability · Machine learning workflow · Linear and logistic regression

Open in the Knowledge reader →Find jobs →