Are explanations faithful? Evaluation and manipulation
Apply the same skepticism to explanation methods as to models. Run randomization sanity checks, measure faithfulness with deletion and insertion curves and ROAR, and study attribution fragility and manipulation by an adversary who controls the model. Finish with a checklist for using explanations in real audits.
After this lesson you can
- Run cascading randomization and label randomization tests and decide which methods pass them.
- Calculate deletion and insertion curves and explain the confounding effect of out-of-distribution evaluation.
- Implement ROAR and compare it with metrics that do not retrain the model.
- Build a model that deceives LIME and SHAP and a countermeasure.
- Distinguish human plausibility from faithfulness to the model.
Before you start
A nice map may not depend on the model
A map that follows edges can look reasonable for an image even after the learned weights have been destroyed. Visual plausibility asks whether the explanation looks convincing; faithfulness asks how it relates to the model’s behavior. These are different questions, and neither can be settled by looking at colors. Jacovi and Goldberg recommend defining faithfulness explicitly and in degrees, rather than assigning a binary label without a protocol.
The randomization sanity checks of Adebayo et al. compare maps before and after changing the model or the training process. Cascading randomization successively replaces parameters, for example from the head toward the first layers. The label test compares against another network trained with permuted labels. A method whose maps barely change may depend mainly on the image or architecture and may therefore be unsuitable for explaining the learned parameters in that test. A large change is a useful condition, but does not establish faithfulness on its own.
The result depends on the target being explained, the reinitialization procedure, the layer, and whether signed maps or magnitudes are compared. Spearman correlation measures rank agreement, not equality of values. If a map is constant, the correlation is undefined; do not replace it with zero without saying so. SSIM measures structural similarity for a chosen data range and is also not a direct measure of causality.
Randomization should preserve the target of the comparison. If the target class changes at the same time, a difference between maps may reflect that change rather than the loss of learned parameters. The figure therefore fixes the class predicted by the original model. Normalizing maps makes their shapes easier to compare but removes magnitude information; retain the absolute scale separately if it matters. Repeating reinitialization with different seeds and evaluating more images helps distinguish a single observation from a pattern across the sample.
In this run, reinitializing only the head gave Spearman correlations with the original map of 0.599 for gradient and 0.989 for guided backprop. After also reinitializing all the displayed layers, these fell to 0.278 and 0.380, respectively. Guided backprop’s initial persistence is notable in this case, but its maps do not remain identical after the full cascade; this also does not establish that the method always ignores the parameters. Maps are normalized individually, and SSIM uses a data range of one.
Deletion, insertion and distribution changes
Deletion-based faithfulness metrics rank features by attribution and progressively replace them while measuring a fixed predictor score. Insertion starts from a baseline and reveals features in that order. The area under each curve summarizes the trajectory, but its interpretation depends on the target, order, and baseline: in deletion, an early drop is usually expected when the ranking identifies components that support that score. There is no universal scale for comparisons across models, classes, and datasets.
In this figure and . The gradient ranks first; gradient times input ranks first. The baselines are zero , a hypothetical mean , and a blurred image , the average of the two pixels. Deleting a feature can even increase the score if the baseline has a higher value. The curve measures the predictor on modified inputs: if those combinations fall outside its training distribution, the effect includes extrapolation. The local image experiment evaluates the same problem with a trained classifier; this two-pixel model helps explain the reversal without presenting it as an empirical result.
For this image, the Grad-CAM deletion AUC was 4.535 with black and 3.642 with the mean baseline; guided backprop gave 5.491 and 3.403, respectively. Their ranking reverses when the baseline changes. This is an observation for one class and image, rather than a general ranking of methods. The area uses logits, not probabilities, so it can exceed one or be negative.
A curve does not have to descend monotonically. Deleting a region can remove evidence against the class and increase its logit; an artificial mask can also activate unexpected associations. In insertion, the initial point depends on the reference, so areas of two different references do not necessarily have the same origin. Compare methods with the same model, case, and replacement, and report the full path along with the area. A random order shows how much of the effect could be produced without using the explanation.
Another proposal is the infidelity metric of Yeh et al., for an explanation with units compatible with perturbations :
It measures whether the product of the explanation and perturbation predicts the score change under that distribution of . Changing the distribution changes the question. Sensitivity measures how much the explanation changes under small perturbations; a constant explanation can be very stable yet useless. Combine metrics with negative controls rather than optimizing a single number.
Remove and retrain
ROAR (remove and retrain) removes features in order of importance from both training and test data and retrains the model on the altered data. This reduces the problem of applying an unchanged predictor to masked inputs it has never seen. Hooker et al. study this family of tests. ROAR does not establish what the original model used: it measures how much a new procedure can learn from what remains, for a particular mask, dataset, and training budget.
Compare against a random order at several removal fractions, use multiple seeds, preserve the data splits, and retrain from independent initializations. Masks can leak information through their shape, and the replacement value can act as a signal. A negative result against the random control is informative; it does not justify changing the metric until the desired result appears. ROAR is expensive because each condition requires retraining.
The evaluation must also specify how rankings are computed: for example, the gradient of the original model’s predicted class, magnitude aggregated per pixel, and stable tie-breaking. In this lab, masks are built for training, validation, and test without using their labels to select pixels. Validation monitors fitting, and test is reserved for the final comparison. Multiple seeds reveal some training variability, but do not automatically make a small difference statistically conclusive.
The reproducible local lab uses the checkpoint produced in lesson 30.6. Install PyTorch, torchvision, Captum, SciPy, scikit-image, scikit-learn and Pillow, and run:
python sanity_roar.py --checkpoint ood_runs/resnet18-11-oe0.pt --data ood_data --out sanity_runs --task all
The sanity phase computes the maps and curves shown; roar trains new networks with two seeds, removal fractions of 0, 0.3 and 0.6, and a random control, as well as another network with permuted labels. It reserves 45,000 images for training, 5,000 for validation, and the official 10,000-image test set; each run uses five epochs. The code writes partial results after each run and saves a checkpoint per epoch, including optimizer and random state, so an interrupted run can resume under the same protocol. This comparison measures a specific procedure and budget; it is not an exact replication of a paper’s protocol.
The following values are observed test accuracies in the full execution. The original model with which the rankings are created was trained for 15 epochs with augmentations; the ROAR networks were trained for five epochs without them. For that reason, the row without deletion is the appropriate reference for these retrainings, and should not be directly compared with the accuracy of the original checkpoint.
| Fraction deleted and order | Seed 11 | Seed 23 |
|---|---|---|
| 0 %, without deletion | 0.7916 | 0.8029 |
| 30 %, gradient | 0.7048 | 0.6867 |
| 30 %, random | 0.6814 | 0.7248 |
| 60 %, gradient | 0.5620 | 0.5920 |
| 60 %, random | 0.6471 | 0.6648 |
At 30% removal, the ranking of gradient and random masks changes between seeds; at 60%, retraining retains less accuracy under the gradient mask for both seeds. Two seeds and five epochs are a bounded study, not a guarantee of stability. The pixel masks use the training RGB mean, and the order comes from the gradient of the class predicted by the original model. Accuracy measures what the new network can learn from the remaining information, not a demonstration of what the original model used.
The label control was also paired with a network trained on correct labels, using the same seed 71, architecture, preprocessing, and five epochs. Training accuracies were 0.8335 with correct labels and 0.1037 with permuted labels: the latter network did not memorize them within that budget. For the control’s fixed image and class, Spearman correlations between the two networks’ maps were 0.184 for gradient and 0.244 for guided backprop. The result shows differences in this case, but neither isolates all effects of learning nor establishes general faithfulness; more images and seeds would provide stronger evidence.
An explanation can be fragile
For a twice differentiable predictor, the change in gradient saliency under is
The integral identity requires a continuous Hessian along the segment; then . High curvature allows a small change to alter the gradient, but the bound guarantees neither that an arbitrary perturbation will do so nor that the label will remain unchanged. ReLU networks have kinks where the classical Hessian does not exist, and a perturbation can cross linear regions. Ghorbani et al. study changes in explanations for perceptually similar inputs with the same label in their experiments.
The fragility of explanations must be measured alongside the input change, score, class margin, and seed. A map can also be stable and wrong. Stability, model sensitivity, and faithfulness under perturbation are therefore complementary properties, rather than a complete ranking of methods.
A detector can separate audit queries from data
An auditor queries a predictor, but the party controlling it could detect artificial inputs created by the explainer. Explanation manipulation through scaffolding combines a biased classifier on natural data with an apparently benign classifier on detected perturbations. Slack et al. demonstrated this mechanism with LIME and SHAP on real datasets. The attack depends on how distinguishable the distributions are, the explainer, and the implementation; it does not imply that all methods fail equally.
The natural distribution contains exactly with equal probability. The sensitive model returns , the neutral model returns , and the scaffold returns the expectation of a gate that chooses the former with probability if , or otherwise. The explained point is . The figure lists the eight coalition values and computes exact Shapley values; the conditional version averages only rows consistent with the observed variables. Perfect correlation makes the group and proxy share information: conditional attribution cannot be promised to identify which is causal.
A countermeasure is to examine the detector explicitly and use perturbations that respect known constraints, together with controlled test pairs. There is no universal sampler over the manifold, and a single baseline is not enough. In the lab below, the mechanism is deliberately synthetic and its rules are known: it measures what the controls achieve, without justifying conclusions about real people.
A detector with high AUC separates two specific samples well, but does not guarantee the detection of all perturbations by another explainer or another population. Conversely, an AUC close to 0.5 with a weak detector does not demonstrate that the distributions are identical. Check new data, various classes of detectors, and changes in the construction of perturbations. Paired lab interventions preserve known group-proxy relationships; they show model sensitivity in that synthetic world, rather than identifying causal effects in a real population.
The model itself can also be manipulated during training. Heo et al. added a term to the optimization objective that changes saliency maps while preserving the predictive task in their experiments. This mechanism does not require detecting each explainer query: it changes the parameters to produce a desired presentation. Similar accuracy does not guarantee equivalent explanations. An audit should specify what the evaluated party controls, whether the model can adapt to the method, and which independent checks are applied.
Evaluate with people and in context
An explanation can help an expert find errors, an affected person check their data, or an operator decide when to review an output. These are different tasks. Doshi-Velez and Kim distinguish evaluation in real applications, simplified human tasks, and functional tests without participants. To study usefulness, compare groups with and without explanations on a defined task, measure decisions, errors, and time, and quantify uncertainty; a stated preference or feeling of confidence does not by itself show better decisions.
For a reproducible audit, document the model and its version, the explained output, examples and partitions, the method and its references, and the metrics with controls and seeds. Include negative results and limitations: what happens when parameters are randomized, how curves change with different replacements, if perturbations are plausible, and if the presenter of the model can adapt their behavior. Add a human evaluation when the claim is about utility for people. No isolated test converts a map into a faithful explanation for all uses.
Laboratory: detect the scaffolding
We generate a binary neutral group, four noisy proxies, and an independent variable. The detector is trained to distinguish coherent observations from samples that break those relationships. The sensitive function returns the group, and the neutral one returns a transformation of the last variable. This construction is defensive, self-contained, and without personal data. The agreement metric measures the frequency with which the scaffolding reproduces the sensitive function on natural test data.
import numpy as np
from scipy.special import expit
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from math import factorial, comb
rng=np.random.default_rng(21)
def natural(n):
g=rng.integers(0,2,n)
return np.column_stack([g,g[:,None]+rng.normal(0,.03,(n,4)),rng.normal(size=n)])
def synthetic(n):
g=np.where(rng.random(n)<.5,rng.integers(0,2,n),rng.uniform(0,1,n))
return np.column_stack([g,rng.normal(.5,.5,(n,4)),rng.normal(size=n)])
train=natural(1000);fake=synthetic(1000)
det=RandomForestClassifier(n_estimators=40,max_depth=7,random_state=7,n_jobs=1)
det.fit(np.r_[train,fake],np.r_[np.ones(len(train)),np.zeros(len(fake))])
real=natural(300);pert=synthetic(300)
auc=roc_auc_score(np.r_[np.ones(300),np.zeros(300)],det.predict_proba(np.r_[real,pert])[:,1])
print('AUC detector en datos nuevos:',round(float(auc),6))def biased(Z):return Z[:,0]
def safe(Z):return expit(3*Z[:,-1])
def wrapped(Z):return np.where(det.predict_proba(Z)[:,1]>.5,biased(Z),safe(Z))
x=np.array([1.,1.,1.,1.,1.,-1.])
print('acuerdo en test natural:',round(float(np.mean(wrapped(real)==biased(real))),4),
'predicción factual:',wrapped(x[None,:]))
z=synthetic(1000);weights=np.exp(-np.sum((z-x)**2,axis=1)/4);A=np.c_[np.ones(len(z)),z]
coef=np.linalg.lstsq(A*np.sqrt(weights[:,None]),wrapped(z)*np.sqrt(weights),rcond=None)[0]
print('coeficientes LIME, tras intercepto:',np.round(coef[1:],4))The LIME samples here come from a specific generator for this experiment, not the library implementation nor a realistic universal distribution. Many break the coherence between group and proxies. In the experiment, the coefficient of the neutral variable can dominate, although in natural data the model preserves the sensitive rule. The next cell calculates the marginal game on a natural background and all coalitions of six variables; the constrained weighted fit reproduces the exact value for that game.
bg=natural(100); values=np.zeros(64); base_values=np.zeros(64)
for mask in range(32):
rows=bg.copy()
for j in range(6):
if mask&(1<<j):rows[:,j]=x[j]
values[mask]=wrapped(rows).mean();base_values[mask]=biased(rows).mean()for mask in range(32,64):
rows=bg.copy()
for j in range(6):
if mask&(1<<j):rows[:,j]=x[j]
values[mask]=wrapped(rows).mean();base_values[mask]=biased(rows).mean()
def shapley(vals):
m=6;phi=np.zeros(m)
for j in range(m):
for S in range(1<<m):
if S&(1<<j):continue
k=S.bit_count();phi[j]+=factorial(k)*factorial(m-k-1)/factorial(m)*(vals[S|(1<<j)]-vals[S])
return phi
truth=shapley(base_values);hidden=shapley(values)
print('SHAP regla sensible:',np.round(truth,4))
print('SHAP andamiaje marginal:',np.round(hidden,4))
print('eficiencia:',np.isclose(hidden.sum(),values[-1]-values[0]))m=6; masks=np.arange(1,63);Z=np.array([[(s>>j)&1 for j in range(m)] for s in masks],float)
sizes=Z.sum(axis=1).astype(int)
kernel=np.array([(m-1)/(comb(m,int(k))*k*(m-k)) for k in sizes])
total=values[-1]-values[0]; A=Z[:,:-1]-Z[:,-1,None]
y=(values[masks]-values[0])-Z[:,-1]*total
first=np.linalg.lstsq(A*np.sqrt(kernel[:,None]),y*np.sqrt(kernel),rcond=None)[0]
estimate=np.r_[first,total-first.sum()]
print('diferencia KernelSHAP y exacto:',float(np.max(np.abs(estimate-hidden))))
u=real[:,-1]; noise=rng.normal(0,.03,(len(u),4))
zero=np.column_stack([np.zeros(len(u)),noise,u]);one=np.column_stack([np.ones(len(u)),1+noise,u])
print('cambio medio al modificar grupo y proxies juntos:',round(float(np.mean(wrapped(one)-wrapped(zero))),4))Consistent pairs change the group and proxies together: this synthetic intervention reveals joint dependence, but does not by itself identify which variable would be causal in a real system. Also observe that the group’s marginal SHAP attribution need not be zero: the tested detector and background determine how much credit shifts to other variables. The experiment measures the success of this particular manipulation; it does not establish that every explanation has been fooled.
Exercises
Step 1 of 2. What is the derivative of that curve?
import numpy as np
def deletion_auc(model,x,attribution,baseline,steps):
pass