Explainable Machine Learning
An explanation can describe how a fitted model behaves across many cases or why it gives one particular prediction. It can also help investigate which inputs are replaceable after retraining. Those questions need different calculations. None of the model-explanation methods below establishes a real-world causal effect by itself; that requires a causal question, assumptions, and suitable evidence.
A small decision tree or a linear model may be understandable directly, although correlated predictors and preprocessing still affect interpretation. Post-hoc methods summarize a fitted model using score changes, response curves, local surrogates, or feature attributions. Judge a summary by the question it answers and how faithfully it represents the model on relevant inputs. An understandable explanation does not establish that the model is accurate or appropriate to deploy.
Training impurity and held-out reliance
A treeโs impurity importance aggregates sample-weighted reductions in its training splitting criterion. Forests combine and normalize these contributions. For squared-error regression, this tracks reductions in within-node squared error. Features offering many distinct split points can accumulate importance by fitting noise; this is a bias to inspect, not a guarantee of a strictly increasing order by cardinality.
Permutation importance holds the fitted model fixed, shuffles one column, and measures the decrease in a declared evaluation score. If held-out Rยฒ falls from 0.8 to 0.6, the decrease is 0.2. This quantity need not sum to one and can exceed one because Rยฒ can be negative. A negative decrease means that particular shuffled evaluation scored better. Use an evaluation set representative of the intended application, and preserve suitable groups or time structure if unrestricted row shuffling would answer the wrong question.
The first generator gives only x0 a population relationship with the target. The other columns are independent noise. Their lack of predictive information in the generator does not force a finite fitted forest to ignore them. Run the Python blocks in order with NumPy and scikit-learn installed. The examples use 120-tree forests and ten permutation repeats.
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
g = np.random.default_rng(0); n = 3000
X = np.column_stack([
g.normal(size=n), # x0: the ONLY feature related to y
g.integers(0, 2, n), # x1: noise, 2 levels
g.integers(0, 10, n), # x2: noise, 10 levels
g.integers(0, 1000, n), # x3: noise, 1000 levels
g.normal(size=n), # x4: noise, continuous
])
y = 2.0 * X[:, 0] + g.normal(0, 1.0, n)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.4, random_state=0)
rf = RandomForestRegressor(120, random_state=0, max_features=1.0).fit(Xtr, ytr)
perm = permutation_importance(rf, Xte, yte, n_repeats=10, random_state=0, scoring="r2")
names = ["x0 SIGNAL", "x1 noise(2)", "x2 noise(10)", "x3 noise(1000)", "x4 noise(cont)"]
print(f"{'feature':16s} {'impurity':>10} {'R2 decrease':>13} {'shuffle SD':>11}")
for i, nm in enumerate(names):
print(f"{nm:16s} {rf.feature_importances_[i]:10.4f} {perm.importances_mean[i]:13.4f} {perm.importances_std[i]:11.4f}")
# feature impurity R2 decrease shuffle SD
# x0 SIGNAL 0.8666 1.6066 0.0746
# x1 noise(2) 0.0060 0.0008 0.0009
# x2 noise(10) 0.0247 0.0019 0.0023
# x3 noise(1000) 0.0522 -0.0011 0.0028
# x4 noise(cont) 0.0504 -0.0004 0.0023
The 1,000-level noise column receives impurity credit 0.0522, while the continuous noise column receives 0.0504. The ordering is therefore not strictly the ordering of distinct-value counts. Their held-out permutation decreases are near zero in this run. The impurity and Rยฒ-decrease columns use different scales. Inspect how the known-noise features compare within each measure; do not read their numerical difference as a discrepancy in units of one common importance. The shuffle SD measures variation across ten permutations of this fixed test set and fitted model. It excludes variation from refitting or drawing another test set and is not a confidence interval.
Built-in importance is a description of training splits, not a direct feature-removal rule. Held-out permutation can help expose reliance that does not improve evaluation performance, but it also depends on the model, metric, data, and perturbation. Correlated inputs make that perturbation particularly consequential.
Correlated inputs: disrupt a model or retrain it?
from sklearn.metrics import r2_score
g = np.random.default_rng(1); n = 4000
z = g.normal(size=n)
noise1, noise2 = g.normal(size=n), g.normal(size=n)
y = 3.0 * z + g.normal(0, 1.0, n)
for label, second in (("exact duplicate", z),
("correlated r=0.90", 0.9 * z + np.sqrt(1 - 0.81) * g.normal(size=n))):
X = np.column_stack([z, second, noise1, noise2])
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.4, random_state=0)
rf = RandomForestRegressor(120, random_state=0, max_features=1.0).fit(Xtr, ytr)
p = permutation_importance(rf, Xte, yte, n_repeats=10, random_state=0, scoring="r2")
print(f"\n--- {label} --- corr(A,B) = {np.corrcoef(X[:, 0], X[:, 1])[0, 1]:.4f}")
print(f" permutation: A {p.importances_mean[0]:.4f} B {p.importances_mean[1]:.4f}")
r_all = r2_score(yte, rf.predict(Xte))
r_a = r2_score(yte, RandomForestRegressor(120, random_state=0, max_features=1.0)
.fit(Xtr[:, [1, 2, 3]], ytr).predict(Xte[:, [1, 2, 3]]))
r_none = r2_score(yte, RandomForestRegressor(120, random_state=0, max_features=1.0)
.fit(Xtr[:, [2, 3]], ytr).predict(Xte[:, [2, 3]]))
r_b = r2_score(yte, RandomForestRegressor(120, random_state=0, max_features=1.0)
.fit(Xtr[:, [0, 2, 3]], ytr).predict(Xte[:, [0, 2, 3]]))
shuffle = np.random.default_rng(2)
joint = []
for _ in range(10):
permuted = Xte.copy()
order = shuffle.permutation(len(Xte))
permuted[:, :2] = Xte[order, :2]
joint.append(r_all-r2_score(yte, rf.predict(permuted)))
print(f" joint permutation A+B R2 decrease {np.mean(joint):.4f}")
print(f" refit R2 all {r_all:.4f} drop A {r_a:.4f} drop B {r_b:.4f} drop both {r_none:.4f}")
# --- exact duplicate --- corr(A,B) = 1.0000
# permutation: A 0.4663 B 0.4651
# joint permutation A+B R2 decrease 1.8161
# refit R2 all 0.8881 drop A 0.8877 drop B 0.8877 drop both -0.1642
#
# --- correlated r=0.90 --- corr(A,B) = 0.9011
# permutation: A 1.8172 B -0.0002
# joint permutation A+B R2 decrease 1.8137
# refit R2 all 0.8911 drop A 0.6965 drop B 0.8877 drop both -0.1642
With exact duplicates, the separate Rยฒ decreases are 0.4663 and 0.4651; joint permutation decreases it by 1.8161. Refitting after dropping either copy changes Rยฒ from 0.8881 to 0.8877. These quantities describe different comparisons and need not add up. Shuffling one copy independently creates combinations absent from training, while a refitted model can use the remaining copy. The regressor here has max_features=1.0, so it considers all features at a split; it is not a forest in which half the trees only saw one copy. Random tie resolution, bootstrap samples, and earlier splits can affect how redundant features are used.
Joint permutation uses the same row shuffle for A and B, preserving their relationship to each other while breaking their alignment with the target and other inputs. It measures disruption to this fixed model. The refit comparison asks how this training procedure performs with a reduced feature set. Neither is a causal intervention on the data-generating process.
In the correlated case, Bโs permutation decrease is โ0.0002, yet refitting without A still reaches Rยฒ 0.6965 using B and the noise features, compared with โ0.1642 after removing both A and B. A small individual permutation score can coexist with useful information in that feature after another one is removed. Conversely, a large permutation score does not establish that a refitted model needs that exact column. Compare removals on validation data, keep tuning budgets comparable, and reserve a later test set if these comparisons drive feature selection. A single-seed refit is not an exact measure of the best achievable performance without a feature.
Shapley values require a defined value function
A Shapley value averages a featureโs added value over all possible orders in which features could be introduced. A coalition is simply the subset already present. For a fixed value function, efficiency means the attributions sum to the full-set value minus the empty-set value; symmetry gives equal credit to players with identical contributions in every coalition. Together with the dummy-player and additivity axioms, these characterize the Shapley allocation. โFairโ here refers to those mathematical properties, not social fairness or a unique choice of what value should mean.
The next example defines value as held-out Rยฒ after retraining on a subset, minus the Rยฒ of a constant predictor fitted to the training mean. The empty subset has value zero. Negative gains are retained, so an unhelpful subset is not silently clipped to zero. The factorial weight in the loop is the fraction of feature orders in which exactly subset S precedes the feature being credited. With four features there are sixteen subsets and fifteen model fits. This is an exact enumeration for this measured performance game; it is not an explanation of one prediction from one fixed forest.
import itertools, math
X = np.column_stack([z, z, noise1, noise2]) # A and B are the same column
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.4, random_state=0)
baseline_r2 = r2_score(yte, np.full(len(yte), ytr.mean()))
def value(S): # what a model on subset S achieves
S = list(S)
if not S: return 0.0
m = RandomForestRegressor(120, random_state=0).fit(Xtr[:, S], ytr)
return r2_score(yte, m.predict(Xte[:, S])) - baseline_r2
feats = [0, 1, 2, 3]
cache = {S: value(S) for r in range(5) for S in itertools.combinations(feats, r)}
shapley = []
for i in feats:
others = [f for f in feats if f != i]
total = 0.0
for r in range(len(others) + 1):
for S in itertools.combinations(others, r):
w = (math.factorial(len(S)) * math.factorial(len(feats) - len(S) - 1)
/ math.factorial(len(feats)))
total += w * (cache[tuple(sorted(S + (i,)))] - cache[tuple(sorted(S))])
shapley.append(total)
for nm, v in zip(["A (=z)", "B (=z)", "noise1", "noise2"], shapley):
print(f"{nm:10s} exact Shapley {v:+.4f}")
print(f"baseline R2 {baseline_r2:.4f}")
print(f"sum {sum(shapley):.4f} full-model gain over baseline {cache[(0, 1, 2, 3)]:.4f}")
# A (=z) exact Shapley +0.5234
# B (=z) exact Shapley +0.5234
# noise1 exact Shapley -0.0732
# noise2 exact Shapley -0.0856
# baseline R2 -0.0000
# sum 0.8881 full-model gain over baseline 0.8881
The efficiency identity applies to the cached subset values, including their finite-data and fitting variation. A and B are identical columns and occupy interchangeable positions in these subset fits, so their computed credits coincide. Equal raw columns only imply equal Shapley values when the defined game treats them symmetrically.
Here A and B each receive about 0.5234, while the noise features receive โ0.0732 and โ0.0856. Their negative contributions offset some of the positive credit, giving a total gain of about 0.8881 over the nearly zero-Rยฒ constant baseline. A noise feature can receive a nonzero performance contribution in this experiment through changes in fitting and finite-sample scores. That does not establish population information in the generator. The allocation summarizes all coalition comparisons, so it also differs from the single comparison of dropping one feature from the full model.
Explain one prediction with a separate game
For a local prediction attribution, keep the function fixed and define how missing inputs are represented. Here the background is the single vector [0, 0], the point is [1, 2], and the function is f(a,b)=2a+3b+ab. A coalition keeps its coordinates from the point and substitutes zero for the others. Its four values are 0, 2, 6, and 10. Feature A adds 2 when it arrives first and 4 when it arrives after B, giving attribution 3; B similarly receives 7. The interaction contribution is shared between them.
def prediction(x):
return 2*x[0] + 3*x[1] + x[0]*x[1]
point = np.array([1.0, 2.0])
background = np.array([0.0, 0.0])
def local_value(indices):
mixed = background.copy()
mixed[list(indices)] = point[list(indices)]
return prediction(mixed)
v0, vA, vB, vAB = (local_value(s) for s in ((), (0,), (1,), (0, 1)))
phiA = 0.5*((vA-v0)+(vAB-vB))
phiB = 0.5*((vB-v0)+(vAB-vA))
print("coalition values", v0, vA, vB, vAB)
print("prediction", prediction(point), "baseline", v0, "attributions", phiA, phiB)
print("reconstructed", v0+phiA+phiB)
# coalition values 0.0 2.0 6.0 10.0
# prediction 10.0 baseline 0.0 attributions 3.0 7.0
# reconstructed 10.0
Real prediction explainers often integrate over a background sample instead of a single zero vector. Replacing missing coordinates with background values and conditioning on observed coordinates define different games for dependent features. Model output also matters: an attribution in log-odds is not a change in probability. Report the background, treatment of missing features, and output scale along with the explainer.
Exact enumeration is exponential in the number of features, but not every practical method approximates every Shapley value. TreeSHAP has efficient exact algorithms for supported tree models under specified value-function assumptions. Tree-path-dependent calculations use path frequencies and are not generally the true observational conditional expectation for an arbitrary joint distribution. Background replacement can break dependence between retained and replaced inputs. These choices affect meaning independently of numerical approximation; the word โinterventionalโ does not by itself establish a causal explanation.
Response curves and local explanations
A partial dependence plot (PDP) replaces one feature with a grid value across a reference dataset and averages the predictions. Individual conditional expectation (ICE) retains a curve for each reference row; its variation can reveal interactions hidden by the average. These curves describe the model on the constructed inputs. They are not generally conditional means of the observed outcome or effects of changing a real-world variable.
Accumulated local effects (ALE) average local prediction differences within bins of the feature being varied, then accumulate and center them. Keeping the other coordinates from rows in the bin usually reduces long-range extrapolation compared with PDP. It does not guarantee that bin-endpoint substitutions lie on the data manifold. Bin width, sparse regions, and model quality still matter.
Other local summaries include a simple surrogate fitted near one prediction and counterfactual inputs that change the modelโs output. A surrogate needs a stated neighborhood and a fidelity check there. A counterfactual needs feasible, actionable changes; flipping a prediction on an impossible input is not a plan for changing an outcome. Explanation stability across nearby cases and refits is useful to inspect alongside predictive performance.
References
- scikit-learn: permutation importance discusses score dependence and correlated inputs.
- scikit-learn documentation. partial_dependence distinguishes brute and recursive calculations.
- SHAPโs TreeExplainer documentation describes exact tree algorithms and background/dependence options.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
