2.3.8 · D3Tree-Based & Instance Methods

Worked examples — Feature importance from trees

3,271 words15 min readBack to topic

This page is the drill-ground for Feature importance from trees. The parent note built the machinery — the formula for Mean Decrease in Impurity (MDI). Here we throw every kind of situation at that machinery and grind out full answers, so you never meet a case you haven't already seen solved.

Before we compute anything, let's recall the one formula everything rests on. If it looks unfamiliar, go back to the parent — but here it is in plain words.

Every symbol above is a count or a fraction of counts — no calculus, no trig. If you can count marbles, you can do this whole page.

One more symbol we lean on constantly: . When we write the Gini impurity , the symbol means ==the fraction of the samples at node that belong to class == — i.e. (count of class- samples in the node) ÷ (total samples in the node). For a node with positives and negatives, and . Each is between and , and across all classes the add up to . The sum just runs over every class label present.


The scenario matrix

A tree-importance problem can only differ along a few axes. Here is the complete list of "case classes" — every worked example below is tagged with which cell it lands in.

# Case class What's different Covered by
A Root split, classification (Gini) weight , cleanest baseline Ex 1
B Deep split, small arrival weight weight , tests Ex 2
C Same feature used twice in one tree must sum two nodes Ex 3
D Regression tree (variance impurity) values, not classes Ex 4
E Degenerate split — no cleanup , useless feature Ex 5
F Already-pure parent , split can't help Ex 6
G Forest: average + normalize over trees many trees → one ranking Ex 7
H High-cardinality trap (word problem) MDI lies, needs the fix Ex 8
I Correlated twins share importance one feature steals the credit Ex 9

Cases A–D are the "signs and quadrants" — the ordinary geometry of the method. E and F are the degenerate / zero inputs (the equivalent of "what if the vector has length 0?"). G is the limiting/aggregation case. H and I are the real-world word problem and the exam twist where the naive number misleads.

The figure below is the picture behind Ex 1. What it encodes: the blue box at the top is the parent node with positives and negatives and impurity . Two coloured arrows fan downward: the green arrow (labelled ) carries samples to a perfectly pure left child (green box, impurity ); the orange arrow (labelled ) carries samples to a mostly-clean right child (orange box, impurity ). The arrow labels and are the child weights and . The gray line beneath shows the weighted-child arithmetic and the red banner at the very bottom is the final — read the figure now, then follow the arithmetic underneath it.

Figure — Feature importance from trees

Ex 1 — Case A: root split, Gini classification

Forecast: guess first — will the importance be closer to , to , or to ? (The left child is perfectly clean, so cleanup should be large-ish.) The blue parent box in the figure above is where we start.

  1. Parent impurity. Why this step? We need the baseline mess before we can measure how much we cleaned. Gini with (a perfect mix): This is the maximum possible Gini for two classes — a totally mixed node.

  2. Child impurities. Why? We must see how pure each side became — the two smaller boxes in the figure. For the left, ; for the right, :

  3. Weighted child impurity. Why? The right child holds more samples, so its (worse) purity should count more. Weight each child by its share of the parent's samples — the and labels on the arrows:

  4. Impurity decrease. Why? This is the actual cleanup: baseline minus leftover mess (the red banner):

  5. Arrival weight. Why? The root sees all data, so ; nothing shrinks.

Verify: cleanup can't exceed the starting mess: ✓. The left child is pure so all its "credit" is real. Sanity: a useless split would give ; we got a big positive number, matching the strongly separating right side.


Ex 2 — Case B: deep split, small arrival weight

Forecast: its local cleanup () is bigger than 's (). Does that make more important? Guess yes/no.

  1. Apply the arrival weight. Why this step? A split that only samples ever reach cannot matter as much as one touching everyone — even if locally it looks impressive. Multiply by :

  2. Rank against . Why? Importance is about total contribution, not local flashiness. So wins despite the smaller local drop — this is the entire reason exists.

  3. Normalize. Why? We usually report shares that sum to . Let be the total of all raw importances, ; dividing each importance by gives its share:

Verify: normalized shares sum to : ✓. The bigger raw importance stays the bigger share, as it must.


Ex 3 — Case C: same feature used twice, sum the nodes

Forecast: one term or two? (Re-read the definition: we sum over every node splitting on .)

  1. Compute each node's contribution. Why this step? The formula is a sum "" — a feature earns credit every time it's used.

  2. Sum them. Why? Total impurity work done by across the whole tree.

Verify: if we'd forgotten node we'd report — an undercount. Since is the only feature, its normalized importance is ✓ (everything must sum to with one feature).


Ex 4 — Case D: regression tree (variance impurity)

First we must define the impurity we'll use, since a regression node has no classes and Gini does not apply.

Forecast: the two children each contain values close together — big cleanup expected? Guess the .

  1. Parent impurity = variance about the mean. Why this step? In regression there are no classes; "mess" means "spread". Apply the definition above. Mean :

  2. Child variances. Why? Same measure, now for the tighter groups. Left mean , right mean :

  3. Weighted child impurity. Why? Equal-size children ( and ), so equal weights :

  4. Impurity decrease. Why? Cleanup = baseline spread minus leftover spread: Since arrival weight is , the contribution is .

Verify: children are much tighter than the parent, so a large drop is expected — and is of the original ✓. The feature that produced this split is separating extremely well.


Ex 5 — Case E: degenerate split, no cleanup

Forecast: the children look exactly like the parent. What cleanup can there be?

  1. Parent impurity. Why? Baseline. :

  2. Child impurities. Why? Check if either side got purer. Both children are , so again :

  3. Weighted child impurity + decrease. Why? Combine and subtract:

  4. Importance contribution. Why? .

earns nothing here — a real greedy tree would never choose this split. This is the degenerate zero-input case: a feature can be present yet contribute .

Verify: is the floor — impurity decrease is never negative (the greedy algorithm never picks a worsening split). We hit exactly the boundary ✓.


Ex 6 — Case F: already-pure parent

Forecast: the parent is already perfect. Can splitting a pure node clean anything?

  1. Parent impurity. Why? Baseline. :

  2. Child impurities. Why? Both children are still all-positive ( each):

  3. Impurity decrease. Why?

The importance contribution is . A pure node has nothing to clean, so no feature can earn credit there. This is why trees stop splitting pure nodes: there's no impurity left to sell.

Verify: , and it cannot go negative from a baseline (children always). Boundary respected ✓.


Ex 7 — Case G: forest average and normalize (limiting/aggregation)

Forecast: feature is consistently high; is nearly absent. Which normalized share is largest?

  1. Average each row over the trees. Why this step? One tree is noisy; averaging is how Random Forests turn many unstable importances into a stable ranking (a small variance-reduction argument):

  2. Sum the averages. Why? To rescale so importances sum to (the usual reported form). Let denote the total of the three averaged importances:

  3. Normalize. Why? Shares are easier to compare across models. Divide each averaged importance by :

The bar chart below shows these two views side by side. What it encodes: three feature labels sit on the horizontal axis; the vertical axis is importance. For each feature there are two bars — the blue bar is the per-tree average from step 1 (, , ) and the orange bar is the normalized share from step 3 (, , ), each printed above its bar. The key visual message: the heights differ (normalizing rescaled everything) but the order blue-tall→short is identical to orange-tall→short, so the ranking is untouched.

Figure — Feature importance from trees

Verify: shares sum to : ✓. Ranking matches the raw averages ✓.


Ex 8 — Case H: high-cardinality trap (word problem)

Forecast: an ID is basically a name tag. Can a name tag really be the top predictor?

  1. Name the mechanism. Why this step? We must explain why MDI over-credits customer_id. A split point is a threshold the tree can test. customer_id has distinct values, so it offers up to possible split thresholds; income_bracket offers at most . More candidate splits = more chances to stumble onto a partition that happens to reduce impurity — even a partition that only isolates a few noisy training rows. Because MDI simply sums whatever impurity drop a feature achieved, this "many-tries advantage" inflates the score. This is the formal statement of Mistake 1 in the parent: MDI is biased toward high-cardinality / continuous features.

  2. Predict what happens on new data. Why? To see the score is fake, ask whether it generalizes. An ID memorized on training rows carries no signal for a customer the model has never seen — its true out-of-sample predictive value is ~. So the high training MDI is pure overfitting, an overfitting artifact (Mistake 4: MDI on training data overestimates).

  3. Quantify how misleading the raw ranking looks. Why? To feel the size of the trap. Treating these two as the whole story, let and normalize: The ID looks responsible for of all importance — a wildly confident, wrong conclusion.

  4. Apply the fix. Why? We need an honest measure. Use Permutation Importance: shuffle customer_id on a held-out set and measure the model's score drop. For a pure-memorization feature the held-out score barely moves → its importance collapses to ≈ . Cross-check with SHAP Values for a per-prediction, less-biased attribution.

Answer: No. The high MDI is a cardinality + overfitting artifact, not causation. After permutation importance on held-out data, customer_id drops to ≈ and income_bracket emerges as the real (if modest) predictor.

Verify: normalized shares sum to : ✓. The reasoning matches the parent's Mistake 1 and Mistake 4 ✓.


Ex 9 — Case I: correlated twins share importance (exam twist)

Forecast: the two features carry the same signal. Will MDI split the credit evenly? Guess before reading on.

  1. Compute each feature's MDI. Why this step? MDI only credits a feature at nodes where it was actually used to split. was used once (root, weight , ); was used zero times:

  2. Interpret the gap. Why? To expose the trap. Despite identical predictive content, one twin reads and the other . Once split the root, its twin became redundant — there was no impurity left for to reduce, so it earned nothing. A genuinely strong predictor is now hidden at importance (Mistake 2 in the parent).

  3. State the honest combined importance. Why? No impurity work was lost — it was all attributed to . So treating the twins as one unit, the pair did exactly:

  4. Recover it in practice. Why? To stop the credit-stealing. Cluster the correlated features and report importance per cluster, or use grouped Permutation Importance (shuffle both twins together and measure one combined score drop). Under grouping the pair correctly shows instead of the misleading " and ".

Answer: MDI gives , ; the true combined importance of the pair is , recoverable by clustering / grouped permutation.

Verify: the two raw numbers (, ) are wildly unequal despite identical signal — exactly the correlated-feature failure mode ✓. Their sum equals the single-use contribution, so no impurity work went missing ✓.


Recall Which cell does each pitfall live in?

Ex 5 shows from a useless split ::: a feature can be present yet contribute nothing. Ex 6 shows a pure parent ::: impurity is already , so no split can earn credit. Ex 8 is the high-cardinality trap ::: MDI over-credits many-valued features; fix with permutation/SHAP. Ex 9 is correlated twins ::: whichever is used first steals all the credit; the other reads .


Connections

  • Decision Trees — every here is the same quantity the tree maximized while growing.
  • Gini vs Entropy — swap and the numbers change but the procedure is identical.
  • Random Forests — Ex 7 is exactly the forest averaging step.
  • Gradient Boosting — same split-based importances (gain), same cardinality caveats.
  • Permutation Importance — the fix invoked in Ex 8 and Ex 9.
  • SHAP Values — per-prediction attribution that dodges Ex 8's bias.
  • Bias-Variance Tradeoff — training-set MDI (Ex 8) overestimates via overfitting.