Module contents
Lesson 8 of 39Core 90 min

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 ff be a fixed predictor, LL a loss where lower is better and (X,Y)(X,Y) an evaluation distribution. Marginal permutation importance of feature jj is

Ijmarg=EL(Y,f(X−j,Xj′))−EL(Y,f(X)),I_j^{\mathrm{marg}}=\E L\big(Y,f(X_{-j},X'_j)\big)-\E L\big(Y,f(X)\big),

where Xj′X'_j is an independent copy with the marginal of XjX_j. In a sample, permute the column and recalculate loss without refitting ff. 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 XjX_j with an independent sample from XjX_j given X−jX_{-j}. It preserves the joint input distribution if the conditional generator is correct, but breaks the residual link with YY. It asks how much this model uses information in jj 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 jj 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.

InteractiveCopies, three questions
00.10.20.30.40.5Marginal0.4938Conditional0.1778Remove and refit0.08889
2
Marginal0.494
Conditional0.178
Remove and refit0.089
Add noisy copies of a signal. Compare marginal and conditional permutation of the fixed predictor with removing a copy and refitting the optimal predictor. Bars are population values from the Gaussian model described below.

The example is verifiable: Z∼N(0,1)Z\sim N(0,1), Xi=Z+ϵiX_i=Z+\epsilon_i, independent ϵi∼N(0,0.25)\epsilon_i\sim N(0,0.25), Y=ZY=Z and f(X)=E[Z∣X]=∑iXi/(m+0.25)f(X)=\E[Z\mid X]=\sum_iX_i/(m+0.25). With squared loss, marginal permutation of one copy increases risk by 2(1.25)/(m+0.25)22(1.25)/(m+0.25)^2. Its conditional variance given the others is 0.25+0.25/(m−1+0.25)0.25+0.25/(m-1+0.25), giving 2Var⁡(Xi∣X−i)/(m+0.25)22\operatorname{Var}(X_i\mid X_{-i})/(m+0.25)^2 for conditional replacement. Removing it and refitting the optimal predictor increases risk by 0.25/(m−1+0.25)−0.25/(m+0.25)0.25/(m-1+0.25)-0.25/(m+0.25). 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 xx of variable jj, partial dependence and ICE are respectively defined as

PD⁡j(x)=EX−jf(x,X−j),ICE⁡ij(x)=f(x,xi,−j).\operatorname{PD}_j(x)=\E_{X_{-j}} f(x,X_{-j}), \qquad \operatorname{ICE}_{ij}(x)=f(x,x_{i,-j}).

The empirical mean of ICE curves is the empirical PDP. Centering each curve at value x0x_0 subtracts f(x0,xi,−j)f(x_0,x_{i,-j}) and reveals differences in change, not level. Goldstein et al. introduce ICE precisely to see heterogeneity hidden by the mean.

InteractiveA flat mean can hide opposing effects
  • z = +1
  • z = −1
  • PDP
In model f(x,z)=xz, half the cases have z=1 and the other half z=−1. Enable centering and observe the mean of the two curves.

The second difficulty appears when XjX_j and X−jX_{-j} are related. PDP crosses each xx with all observed values of X−jX_{-j}: 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 ff and a reference distribution, not a causal effect or a mean conditioned on Xj=xX_j=x.

Conditional mean E[f(X)∣Xj=x]\E[f(X)\mid X_j=x] avoids that crossing, but also changes the distribution of other variables as xx changes. It can therefore move even when ff does not directly use XjX_j: if f(x,z)=zf(x,z)=z and Z=XZ=X, the conditional mean is xx although the partial derivative with respect to xx is zero. PDP would keep the ZZ 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.

InteractivePDP crosses values from different observations
  • Observed
  • Evaluated by PDP
  • PDP
  • ALE
0.90
1.5
Centered PDP2.13
Centered ALE1.56
Move the slice and increase correlation. Red marks are combinations evaluated at the slice; curves use population formulas from the Gaussian example.

Here (X,Z)(X,Z) is bivariate standard normal with correlation ρ\rho and f(x,z)=x+(x−z)2/2f(x,z)=x+(x-z)^2/2. After centering with respect to the marginal of XX, PDP is x+(x2−1)/2x+(x^2-1)/2 and ALE is x+(1−ρ)(x2−1)/2x+(1-\rho)(x^2-1)/2. The latter follows local predictor change in the cloud when ρ\rho 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

ALE⁡~j(x)=∫axE ⁣[∂f(t,X−j)∂xj | Xj=t] ⁣dt,ALE⁡j(x)=ALE⁡~j(x)−EALE⁡~j(Xj).\widetilde{\operatorname{ALE}}_j(x)=\int_{a}^{x}\E\!\left[\frac{\partial f(t,X_{-j})}{\partial x_j}\,\middle|\,X_j=t\right]\dd t, \qquad \operatorname{ALE}_j(x)=\widetilde{\operatorname{ALE}}_j(x)-\E\widetilde{\operatorname{ALE}}_j(X_j).

The centering constant makes the mean zero. In practice divide the range into intervals, preferably by quantiles, and average the difference f(bk,Xi,−j)−f(bk−1,Xi,−j)f(b_k,X_{i,-j})-f(b_{k-1},X_{i,-j}) 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 f(x)=∑kfk(xk)f(x)=\sum_k f_k(x_k), the PDP of jj is fj(x)+∑k≠jEfk(Xk)f_j(x)+\sum_{k\ne j}\E f_k(X_k) even with correlated inputs. For ALE, the partial derivative is fj′(t)f'_j(t), independent of other coordinates. Its integral is fj(x)−fj(a)f_j(x)-f_j(a) and, after centering, becomes fj(x)−Efj(Xj)f_j(x)-\E f_j(X_j). 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 HH from partial dependences. For two variables with centered PDPs, one form is

Hjk2=∑i[PD⁡jk(xij,xik)−PD⁡j(xij)−PD⁡k(xik)]2∑iPD⁡jk(xij,xik)2.H_{jk}^2=\frac{\sum_i[\operatorname{PD}_{jk}(x_{ij},x_{ik})-\operatorname{PD}_j(x_{ij})-\operatorname{PD}_k(x_{ik})]^2}{\sum_i\operatorname{PD}_{jk}(x_{ij},x_{ik})^2}.

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 [0,1][0,1]. 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 g(E[Y∣X])=β0+∑jfj(Xj)g(\E[Y\mid X])=\beta_0+\sum_j f_j(X_j) with link gg. For binary classification, for example, gg can be the logit. An EBM adds functions learned by boosting and optionally pair terms: β0+∑jfj(xj)+∑j<kfjk(xj,xk)\beta_0+\sum_j f_j(x_j)+\sum_{j<k}f_{jk}(x_j,x_k). 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.

[ ]Data, predictor and lossBrowser
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))
[ ]Marginal and approximate conditional permutationBrowser
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.

[ ]Remove and refitBrowser
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.

[ ]ICE, PDP and ALE from scratchBrowser
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))
[ ]Comparison with sklearnBrowser
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)))
[ ]sklearn visualizationBrowser
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.

[ ]Credit, EBM, LightGBM and planted leakageLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Inspect the leakage shape functionLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with 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

Proof
Prove: For a differentiable additive model, PDP and ALE for variable j are its shape function up to constants.
0
Let f(x)=the sum of f_k(x_k), with existing expectations and integrals.

Step 1 of 3. What happens when averaging f(x, X_{−j})?

Numeric
Six observations have x = y = (0, 1, 2, 3, 4, 5) and fixed predictor f(x)=x. Permute x into order (1, 0, 3, 2, 5, 4). How much does MSE increase?
Quiz
A data cloud occupies a narrow diagonal band and a PDP curve evaluates points far from it. Which interpretation is most defensible?
Quiz
A second graph shows a flat PDP and two ICE groups with slopes equal in magnitude and opposite in sign. Which conclusion is justified?
Quiz
A third graph shows a well-covered rectangular cloud and a model additive in x and z. What relationship do you expect between PDP and the x shape function?
CodeOne-variable ALE
Implement ale_1d(model, X, j, n_bins). Return edges, accumulated interval values centered using case-count weights, and counts. Merge repeated quantiles and assign the maximum to the last interval; reject constant variables or empty intervals.
import numpy as np
def ale_1d(model, X, j, n_bins):
  pass
Shift+Enter to run

Summary

Key idea
An explanation makes sense only alongside its question, predictor, reference population and constructing perturbations. Correlation, support and model choice change what can be concluded.
  • 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.