Interpretability: framework, glass-box models and feature importance
Frame explainability around what is explained, to whom and for which decision. Compare transparent models with post-hoc explanations, implement marginal and conditional permutation importance, feature removal, PDP, ICE and ALE, and examine correlated features, GAMs and EBMs.
After this lesson you can
- Classify explanation methods as transparent or post hoc, global or local, model-agnostic or specific.
- Implement marginal and conditional permutation importance and feature removal, and explain their differences for correlated features.
- Build PDP, ICE and ALE from scratch and detect extrapolation beyond the data.
- Fit an EBM and compare accuracy and interpretability with gradient boosting.
- Explain when a transparent model is preferable to explaining a black box.
Before you start
Before asking why
A model rejects a credit application. A person asks for a reason to appeal; an engineer wants to discover data leakage; a researcher wants to know whether reducing debt would change real risk. All three questions use the word “explanation”, but require different evidence. A model curve can help debug a prediction; it does not itself identify the effect of an intervention on a person.
This distinction extends the dimensions of trustworthiness. Before drawing a figure, fix the audience, decision and object explained. Is it a particular prediction or average behavior? Is the fitted function explained, or the phenomenon that generated the data? Which perturbations are possible? Lipton distinguishes different meanings of interpretability; Doshi-Velez and Kim call for evaluating explanations in relation to their use.
Rudin argues for designing interpretable models for high-stakes decisions instead of relying solely on approximate black-box explanations. This is a design argument, not a theorem that every simple model predicts better. Compare out-of-sample performance, calibration, stability, constraints and error costs for the specific problem. A transparent model can also use unfair proxies or leaked data and must be audited.
Permuting does not remove information from the world
Let be a fixed predictor, a loss where lower is better and an evaluation distribution. Marginal permutation importance of feature is
where is an independent copy with the marginal of . In a sample, permute the column and recalculate loss without refitting . Positive importance indicates that breaking this association hurt the predictor on that sample. A negative value can arise from noise, overfitting or variability. Repeated permutations quantify shuffle randomness, but not all training or sampling uncertainty. The latter requires, for example, an appropriate bootstrap of observations or independent units, with refitting where appropriate.
The conditional version replaces with an independent sample from given . It preserves the joint input distribution if the conditional generator is correct, but breaks the residual link with . It asks how much this model uses information in not predicted by the others. Estimating that distribution is difficult with mixed variables; a defective generator changes the question. Column removal trains a new predictor without and compares losses on a common test set. It asks how much the training procedure loses without the feature: it measures another model and depends on fitting. Fisher, Rudin and Dominici also study how dependence on a variable varies within a class of equally good models.
The difference appears with two exact copies. If the predictor uses only the first, marginally permuting it breaks prediction even though the second remains. Refitting without the first can learn to use the second and lose very little. Conversely, if the second exactly determines the first, valid conditional replacement returns the same value and conditional importance is zero. Zero does not mean the signal is useless: it means no unique variation remains to perturb once the copy is fixed. If variables are correlated but not identical, the result depends on remaining noise and the fitted function.
The unit of analysis matters. Separately permuting several indicators encoding a category can create rows representing no valid category; permute the entire group using the same row order. In time series, permuting isolated rows also destroys temporal dependence: a block or domain-designed perturbation answers another, more plausible question. Always evaluate on data separate from fitting and state the loss: importance for squared error is not necessarily importance for classification, calibration or asymmetric costs.
Impurity-reduction importance returned by a random forest sums split improvements attributed to each variable during fitting. This is not the same as test-loss change on permutation, and can favor variables with many possible splits, as seen in impurity importance bias. A variable may often appear in trees yet be replaceable by a correlated one. In a boosting ensemble, importance also depends on how each sequential correction was constructed. Comparing both indicators requires stating their definition and dataset.
The example is verifiable: , , independent , and . With squared loss, marginal permutation of one copy increases risk by . Its conditional variance given the others is , giving for conditional replacement. Removing it and refitting the optimal predictor increases risk by . All three quantities decrease when copies are added even though the joint signal remains informative. This pattern is not universal: with another fitted function marginal importance can rise or fall, and permutation can create impossible combinations.
The mean hides individuals and impossible combinations
For an input of variable , partial dependence and ICE are respectively defined as
The empirical mean of ICE curves is the empirical PDP. Centering each curve at value subtracts and reveals differences in change, not level. Goldstein et al. introduce ICE precisely to see heterogeneity hidden by the mean.
The second difficulty appears when and are related. PDP crosses each with all observed values of : some pairs may be far from the training cloud. In those regions predictor behavior may be poorly identified by data. A PDP is a property of and a reference distribution, not a causal effect or a mean conditioned on .
Conditional mean avoids that crossing, but also changes the distribution of other variables as changes. It can therefore move even when does not directly use : if and , the conditional mean is although the partial derivative with respect to is zero. PDP would keep the marginal fixed and be constant; ALE would also be constant for this function. This distinction between association and partial function change is itself distinct from a causal intervention.
Here is bivariate standard normal with correlation and . After centering with respect to the marginal of , PDP is and ALE is . The latter follows local predictor change in the cloud when is high; it does not show the model learned a real effect or prove causality. In finite data even ALE evaluates interval endpoints, so wide intervals and sparse regions require caution.
Accumulating local changes
First-order accumulated local effect (ALE) is defined, for a differentiable model and relevant integrability conditions, by
The centering constant makes the mean zero. In practice divide the range into intervals, preferably by quantiles, and average the difference in each interval over cases falling there. Accumulate these differences and center using observation frequency. Repeated boundaries for discrete variables must be merged, and an empty interval does not permit estimating its difference. Apley and Zhu develop this estimator and contrast its properties with PDP and conditional mean.
If , the PDP of is even with correlated inputs. For ALE, the partial derivative is , independent of other coordinates. Its integral is and, after centering, becomes . These identities concern the predictor, not a causal mechanism.
Interactions and transparent models
An interaction means the prediction change when one variable varies depends on another variable’s value. Friedman and Popescu propose statistic from partial dependences. For two variables with centered PDPs, one form is
The denominator can be zero, in which case the ratio is undefined. With correlated inputs PDs may evaluate implausible combinations; estimation can be unstable and the empirical ratio need not lie in . It does not replace a causal design or identify which interaction is useful for an individual decision. The result also depends on output scale: an additive sum in logit is not necessarily additive after the logistic function. Before comparing interactions fix both scale and reference population.
A generalized additive model (GAM) represents with link . For binary classification, for example, can be the logit. An EBM adds functions learned by boosting and optionally pair terms: . Functions contribute on the link scale, not as independent probabilities. Show data distributions, intervals and interaction terms alongside them. InterpretML presents EBMs as glass-box models and permits comparison with post-hoc explanations (Nori et al.). Monotonic and interaction constraints can help, but require domain justification and validation.
A GAM extends polynomial regression: rather than imposing a straight line, each shape function can be represented by a basis expansion and regularized to avoid unsupported oscillation. EBMs build shapes from step functions, combining many small boosting updates. The final shape can be inspected even if each individual update is uninformative. If pairs are added, the one-dimensional graph no longer tells the full contribution for a case: inspect the two-dimensional term and add both parts.
Laboratory: out-of-sample inspection
The scikit-learn diabetes dataset is small and bundled with the library. Split training and test before fitting. The target is continuous and we measure mean squared error. This example’s approximate conditional replacement fits linear regression of the column on the others on training only, then resamples residuals: it is not generally an exact conditional sample. The interval between repetition quantiles is a permutation interval, not a population confidence interval.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.inspection import permutation_importance, partial_dependence
X, y = load_diabetes(return_X_y=True)
names = load_diabetes().feature_names
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=17)
model = GradientBoostingRegressor(n_estimators=60, max_depth=2, random_state=17).fit(Xtr, ytr)
j = names.index('bmi')
baseline = mean_squared_error(yte, model.predict(Xte))
print('tamaños:', len(Xtr), len(Xte), 'variable:', names[j])
print('MSE de prueba:', round(baseline, 2))def perm_importance(f, X, y, j, repeat=30, seed=23, conditional=None):
rng = np.random.default_rng(seed)
base = mean_squared_error(y, f.predict(X))
values = []
for _ in range(repeat):
xp = X.copy()
xp[:, j] = (rng.permutation(X[:, j]) if conditional is None
else conditional(X, rng))
values.append(mean_squared_error(y, f.predict(xp)) - base)
return np.asarray(values)
others = np.arange(Xtr.shape[1]) != j
cond = LinearRegression().fit(Xtr[:, others], Xtr[:, j])
resid = Xtr[:, j] - cond.predict(Xtr[:, others])
def conditional_draw(X, rng):
return cond.predict(X[:, others]) + rng.choice(resid, size=len(X), replace=True)
marg = perm_importance(model, Xte, yte, j)
cimp = perm_importance(model, Xte, yte, j, conditional=conditional_draw)
sk = permutation_importance(model, Xte, yte, scoring='neg_mean_squared_error',
n_repeats=30, random_state=23).importances[j]
for label, values in [('marginal', marg), ('condicional aproximada', cimp), ('sklearn', sk)]:
print(label, 'media:', round(values.mean(), 2), 'cuantiles:', np.round(np.quantile(values, [0.025, 0.975]), 2))Both marginal methods perform independent permutations and use different generators: their means need not match exactly. The sign of neg_mean_squared_error is correctly reversed in the sklearn score decrease. Column removal refits a model with the same design; it does not alter the input of a model still expecting all columns.
drop = GradientBoostingRegressor(n_estimators=60, max_depth=2, random_state=17)
drop.fit(Xtr[:, others], ytr)
loss_diff = (yte - drop.predict(Xte[:, others]))**2 - (yte - model.predict(Xte))**2
drop_delta = loss_diff.mean()
rng = np.random.default_rng(19)
boot = np.array([rng.choice(loss_diff, size=len(loss_diff), replace=True).mean() for _ in range(500)])
print('Cambio de MSE al quitar bmi y reajustar:', round(drop_delta, 2))
print('Bootstrap pareado, cuantiles 2.5% y 97.5%:', np.round(np.quantile(boot, [.025, .975]), 2))For ICE and PDP we use a common grid. For ALE we merge repeated quantiles and assign the maximum endpoint to the last interval. The last two cells check algebraic equality between mean ICE and PDP and compare with sklearn’s implementation on the same explicit grid.
def ice(f, X, j, grid):
out = np.empty((len(X), len(grid)))
for k, x in enumerate(grid):
xp = X.copy(); xp[:, j] = x
out[:, k] = f.predict(xp)
return out
def ale_1d(f, X, j, n_bins=10):
edges = np.unique(np.quantile(X[:, j], np.linspace(0, 1, n_bins + 1)))
if len(edges) < 2:
raise ValueError('La variable debe tener al menos dos valores')
bins = np.clip(np.searchsorted(edges, X[:, j], side='right') - 1, 0, len(edges) - 2)
diffs, counts = [], []
for k in range(len(edges) - 1):
rows = X[bins == k]
if not len(rows):
raise ValueError('Intervalo vacío: reduce n_bins o cambia los cortes')
lo, hi = rows.copy(), rows.copy()
lo[:, j], hi[:, j] = edges[k], edges[k + 1]
diffs.append(np.mean(f.predict(hi) - f.predict(lo)))
counts.append(len(rows))
values = np.cumsum(diffs)
values = values - np.average(values, weights=counts)
return edges, values, np.array(counts)
grid = np.quantile(Xte[:, j], np.linspace(.05, .95, 11))
curves = ice(model, Xte, j, grid)
centered = curves - curves[:, :1]
edges, ale, counts = ale_1d(model, Xte, j)
print('ICE y PDP:', curves.shape, np.round(curves.mean(axis=0)[:3], 3))
print('ALE centrado:', round(np.average(ale, weights=counts), 10), 'intervalos:', len(counts))pd_sk = partial_dependence(model, Xte, features=[j], kind='average', method='brute',
custom_values={j: grid})['average'][0]
print('Máxima diferencia PDP:', float(np.max(np.abs(pd_sk - curves.mean(axis=0)))))
print('ICE centradas en primer punto:', bool(np.allclose(centered[:, 0], 0)))import matplotlib.pyplot as plt
from sklearn.inspection import PartialDependenceDisplay
fig, ax = plt.subplots(figsize=(6, 3))
PartialDependenceDisplay.from_estimator(model, Xte, [j], kind='both',
subsample=30, random_state=17, method='brute', ax=ax)
ax.set_title('PDP e ICE de bmi en prueba')
plt.tight_layout()
plt.show()In this discrete estimator each observation receives the accumulated value at its interval’s upper endpoint. Other conventions interpolate within each interval; state this when comparing curves. Large differences between PDP and ALE warrant inspecting support and interactions, not automatically choosing the most convincing curve. The removal bootstrap resamples paired test losses while keeping both models fixed: it reflects evaluation uncertainty conditional on those fits, not variation from repeating training. The latter requires resampling training and refitting both models.
EBM and gradient boosting for credit
The next local laboratory compares EBM and LightGBM on credit and adds deliberate leakage to learn how to locate it. It is a diagnostic demonstration, not a credit-granting evaluation. The leak is a copy of the label, artificially available in training and test: a random split alone does not detect a feature unavailable at decision time. The no-leak experiment is the valid comparison; the one with it shows the failure. Libraries interpret-core, lightgbm and xlrd must be installed locally. The download is SHA-256 verified before reading.
import numpy as np
import pandas as pd
import hashlib, io, urllib.request, zipfile
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score
from interpret.glassbox import ExplainableBoostingClassifier
from lightgbm import LGBMClassifier
url = 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip'
raw = urllib.request.urlopen(url, timeout=120).read()
assert hashlib.sha256(raw).hexdigest() == '56c885f84457f6680f8438f02bfcdac9579323d8a94465ee5f26e32baa727602'
with zipfile.ZipFile(io.BytesIO(raw)) as z:
table = pd.read_excel(io.BytesIO(z.read('default of credit card clients.xls')), header=1)
X = table.drop(columns=['ID', 'default payment next month'])
y = table['default payment next month'].to_numpy(dtype=int)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=.3, stratify=y, random_state=17)
def comparar(train, test):
ebm = ExplainableBoostingClassifier(interactions=0, max_rounds=500, random_state=17, n_jobs=1)
lgbm = LGBMClassifier(n_estimators=150, verbosity=-1, random_state=17, n_jobs=1)
for label, clf in [('EBM', ebm), ('LightGBM', lgbm)]:
clf.fit(train, ytr)
p = clf.predict_proba(test)[:, 1]
print(label, 'accuracy', round(accuracy_score(yte, p >= .5), 3),
'AUC', round(roc_auc_score(yte, p), 3))
return ebm, lgbm
print('Sin fuga'); clean_ebm, clean_lgbm = comparar(Xtr, Xte)
print('Con fuga artificial');
leak_tr, leak_te = Xtr.copy(), Xte.copy()
leak_tr['fuga_etiqueta'] = ytr; leak_te['fuga_etiqueta'] = yte
leak_ebm, leak_lgbm = comparar(leak_tr, leak_te)
term = leak_ebm.term_names_.index('fuga_etiqueta')
print('Término de fuga, puntuaciones en logit:', np.round(leak_ebm.term_scores_[term], 3))
print('Características de entrada:', Xtr.shape[1], 'filas:', len(Xtr), len(Xte))npm run lab and open the connection link.import matplotlib.pyplot as plt
shape = leak_ebm.explain_global().data(term)
fig, ax = plt.subplots(figsize=(6, 3))
ax.stairs(shape['scores'], shape['names'])
ax.set_xlabel('Fuga de etiqueta'); ax.set_ylabel('Contribución al logit')
ax.set_title('Función de forma aprendida')
plt.tight_layout(); plt.show()
print('Bordes:', np.round(shape['names'], 3), 'contribuciones:', np.round(shape['scores'], 3))npm run lab and open the connection link.In one run on this split without leakage, EBM obtained accuracy 0.819 and AUC 0.786, and LightGBM 0.818 and 0.779. These are results of this particular fit, not an equivalence guarantee or definitive comparison with hyperparameter search. With artificial leakage both reached 1.0 on both metrics. The shape function shows how the model uses that column, and when the label becomes known explains why it must be removed.
The dataset is UCI Default of Credit Card Clients. Categorical columns encoded as numbers are treated numerically here: this simplifies the demonstration and can impose an improper order. For real work identify categories, use current data available at decision time, temporal validation, appropriate costs and subgroups. High accuracy with a leaked label is precisely the alarm, not a legitimate improvement.
Exercises
Step 1 of 3. What happens when averaging f(x, X_{−j})?
import numpy as np
def ale_1d(model, X, j, n_bins):
passSummary
- Marginal and conditional permutation examine a fixed predictor; removing a variable and refitting examines a different procedure.
- PDP averages ICE and can hide heterogeneity or evaluate combinations outside support. ALE accumulates local changes and also needs sufficient data.
- A GAM or EBM exposes its terms, but transparency does not replace predictive evaluation, causal analysis or data auditing.