LIME, anchors and counterfactual explanations
Study local surrogate explanations with LIME and its relationship to KernelSHAP, anchor rules, counterfactuals and actionable recourse. Examine how similarly accurate models in a Rashomon set can explain the same data differently.
After this lesson you can
- Formulate LIME as optimization and show KernelSHAP is a special case.
- Measure LIME instability with kernel width and seed.
- Calculate counterfactuals with validity, proximity, sparsity and plausibility, and recourse with immutable variables.
- Distinguish counterfactual explanation from causal counterfactual and causal recourse.
- Quantify explanation multiplicity within a Rashomon set.
Before you start
One decision and three questions
An application receives an unfavorable score. A local surrogate asks how the prediction changes near that case; an anchor rule asks under what conditions the prediction tends to remain; a counterfactual seeks a different input with another decision. None itself guarantees the person can make the change or that doing so changes the world as the model assumes.
In the taxonomy these are local, post-hoc explanations. Their usefulness depends on audience, perturbation type and decision. For an appeal, a person may need to verify data and procedure; debugging the model calls for surrogate fidelity; recommending action requires studying feasibility and downstream effects.
A small model around a point
The LIME local surrogate approximates predictor with interpretable model around (Ribeiro et al.). Its objective is
where are perturbations in the original representation, their interpretable representation, weights proximity and limits complexity. In text, for example, can indicate word presence; in tables an implementation can discretize columns. Representation, generator, distance, width and regularization are part of the explanation. Weighted regression on probabilities answers a different question from regression on logits or labels.
The figure’s classifier is . Samples are , , and weight is . Unpenalized weighted linear regression is solved. For very small , few samples have effective weight and the fit can be unstable; for large , a larger area is approximated and the plane need not describe the immediate neighborhood. Repeat seeds, report local error and inspect support. Good local fit on perturbed data does not prove fidelity on natural examples.
The raw number of perturbations can mislead when almost all weights are tiny. A diagnostic is effective size : it equals with equal weights and approaches one if a single observation dominates. It does not replace an uncertainty interval or detect impossible samples, but helps distinguish a supported local fit from one sustained by a few points. Vary both seed and width and retain an independent perturbation sample to evaluate the surrogate.
Coefficient interpretation also depends on encoding. In regression on binary word masks, the difference between presence and absence of a token is estimated under the chosen replacement mechanism. In a standardized table, magnitude is expressed per transformed-feature unit. Neither a large nor a negative coefficient identifies a real intervention if the predictor uses dependencies between variables or perturbation creates combinations absent from the data.
The relationship with KernelSHAP is exact under a specific choice: use binary coalitions, their value function, squared loss, Shapley kernel and empty- and full-coalition constraints, without a penalty changing the solution. Then the LIME problem becomes the constrained problem proved in the previous lesson. Ordinary LIME does not impose these choices and need not produce Shapley values. Lasso regularization can select few variables, but two correlated features may swap across seeds with little prediction change.
Rules that fix a prediction
An anchor is a rule satisfied by the explained case, seeking high precision under a defined perturbation distribution. Its coverage is the probability that the rule holds. High precision and high coverage compete: adding conditions usually makes the rule more specific. Ribeiro et al. propose searching for rules by sampling and sequential selection related to best-arm identification.
Estimated precision 0.95 describes the distribution used to generate examples, not all possible sentences or necessarily future data. The uncertainty interval and budget matter, especially after selecting among many rules. If words are replaced by an artificial marker, the classifier may respond to unnatural sentences; a precise rule under that mechanism may not be precise under another. Later we measure agreement between methods without assuming matching words equal fidelity.
An empty rule can result from a search: if the predicted class is already preserved often enough under unconditional perturbation, no words need be added to meet the estimated threshold. It can also reflect a specific implementation decision when no rule is found; therefore record status and budget instead of automatically interpreting it as absence of factors. Coverage and precision are estimated under the chosen distribution: a rule with very low coverage can be precise yet of little use for many cases.
Changing the input is not yet an action
A counterfactual explanation seeks with a desired output and a small change. A penalty formulation is
where measures distance and penalizes implausible points. Wachter et al. propose contrastive explanations without opening the model. Validity requires actually checking the new decision; a finite penalty does not guarantee it. Small distance does not guarantee plausibility either, and a density score is only an approximation dependent on data and density model. Several diverse solutions can offer alternatives; DiCE formalizes diversity and feasibility objectives.
The figure exactly minimizes the objective on that grid, not the whole plane. For each valid candidate it uses L1 or L2 distance plus , the Mahalanobis distance to the center of a normal with correlation 0.7. Its minimum illustrates the tradeoff between proximity and a chosen notion of plausibility. Variables use homogeneous demonstration units; real data require justification of scales, categories and costs. If the point is already approved, the minimum can be the point itself when plausibility weight is zero; with positive weight, the objective can prefer another approved point.
Algorithmic recourse seeks feasible actions with cost and desired outcome, not just a nearby vector. Age, birth date or historically recorded states may be immutable; income and debt may have limits, allowed directions, costs and delays. Ustun et al. formulate recourse for linear classification using integer programming. In a linear model with discrete actions, domain constraints and costs, an integer program can encode the boundary and select feasible combinations; if no solution exists, the system must say so.
A structural causal model adds an action’s consequences for downstream variables. A proposal changing salary while holding fixed a balance dependent on salary may not describe a reachable world. A causal counterfactual needs assumptions about mechanisms and unobserved variables, plus validation of the action in context. It does not follow from optimizing classifier input. A numerical penalty also does not replace optimality conditions or a feasibility proof; nonconvex problems can have local optima.
Scale changes minimum recourse. If one feature is measured in euros and another in thousands of euros, unweighted L1 distance changes when units change. Costs must represent available actions, not just normalize numbers; they can depend on the person and be asymmetric. For example, reducing debt and increasing income can have different times and constraints. A solution crossing the boundary in a static model must be checked against the model and domain rules before being communicated as an option.
Many models, several explanations
A Rashomon set collects models in a class whose validation loss is within a tolerance of the best observed. It is defined relative to a metric, sample and family: it does not claim all have the same population risk or that the true model is in the set. Models can use correlated features differently and propose different counterfactuals despite similar metrics.
The figure’s data come from a documented run on the public UCI dataset from lesson 30.8. Two payment-status columns are used; training, validation and test are separated, and logistic regressions and trees fitted on training resamples. We choose the first 20 with validation accuracy within 0.01 of the best of 40 candidates. In that run validation values range from 0.803 to 0.813 and test values from 0.813 to 0.825; descriptive closeness does not prove statistical equivalence. The eight shown pairs are most frequent in test, selected without looking at explanations. The SHAP background contains 200 training rows; counterfactuals search among pairs actually observed in training and minimize Euclidean distance in their codes. Changing payment codes does not equal an available action. Download the generator to reproduce models and data, with source and hash verified.
The Rashomon set depends on threshold and search: finding twenty candidates does not prove all admissible models were found. For an audit, show the distribution of explanations, verify on a separate sample that metrics remain acceptable and examine which individual decisions change across models. If a conclusion depends on choosing among similarly performing models, report that dependence; it does not imply all explanations are equally valid under every criterion.
Laboratory: LIME, recourse and multiplicity
First we fit a surrogate to a known predictor. Weighted squared error is measured on a new perturbation sample from the same distribution, not data used by the surrogate. Compare coefficients and errors across seeds: width and noise effects depend on the chosen point.
import numpy as np
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error
def f2(X):
return 1/(1+np.exp(-2*(X[:,0]+.6*X[:,1]**2-.5)))
def lime_local(x, width, seed, n=600):
random=np.random.default_rng(seed)
Z=x+random.normal(size=(n,2))
weights=np.exp(-np.sum((Z-x)**2,axis=1)/(2*width**2))
surrogate=Lasso(alpha=.001,max_iter=10000).fit(Z,f2(Z),sample_weight=weights)
return surrogate
x=np.array([.2,.7])
for width in (.25,.7,1.5):
coefficients=np.array([lime_local(x,width,seed).coef_ for seed in range(20)])
print('ancho',width,'media',np.round(coefficients.mean(axis=0),3),
'desviación',np.round(coefficients.std(axis=0),3),
'signos negativos x2',int(np.sum(coefficients[:,1]<0)))local=lime_local(x,.7,1)
random=np.random.default_rng(999); hold=x+random.normal(size=(600,2))
weights=np.exp(-np.sum((hold-x)**2,axis=1)/(2*.7**2))
print('MSE ponderado de nuevas perturbaciones:',round(mean_squared_error(f2(hold),local.predict(hold),sample_weight=weights),6))
print('probabilidad real y sustituta:',round(float(f2(x[None,:])[0]),4),round(float(local.predict(x[None,:])[0]),4))Now we seek counterfactuals for logistic regression. A small penalty can prioritize the probability objective, but each candidate must be validated. Then we enumerate feasible discrete actions, keeping the third variable fixed. Exhaustive search certifies the minimum only within the declared grid and constraints.
from scipy.optimize import minimize
from scipy.special import expit
w=np.array([2.,1.,.7]); b=-1.; start=np.array([-1.,-1.,.5]); target=.8
def prob(z): return expit(w@z+b)
def objective(z,lam): return (prob(z)-target)**2+lam*np.sum((z-start)**2)
for lam in (.1,.01,.001):
result=minimize(objective,start,args=(lam,),method='BFGS')
print('lambda',lam,'probabilidad',round(float(prob(result.x)),4),
'distancia',round(float(np.linalg.norm(result.x-start)),4),'éxito optimizador',result.success)
grid=np.linspace(-1,3,81)
candidates=np.array([[a,c,start[2]] for a in grid for c in grid])
feasible=candidates[expit(candidates@w+b)>=target]
dist=np.sum(np.abs(feasible-start),axis=1)
best=feasible[np.argmin(dist)]
print('recurso discreto:',np.round(best,3),'probabilidad',round(float(prob(best)),4),
'coste L1',round(float(np.min(dist)),4),'tercera variable fija:',best[2]==start[2])rank=np.argsort(dist)
choices=[]
for idx in rank:
candidate=feasible[idx]
if all(np.linalg.norm(candidate-old)>=.5 for old in choices): choices.append(candidate)
if len(choices)==3: break
print('alternativas válidas:',np.round(choices,2))
print('probabilidades:',np.round([prob(z) for z in choices],3))The greedy rule separates alternatives by distance, but does not globally optimize diversity and cost or implement DiCE. The third coordinate is preserved by construction. If no action were valid, return “no solution” rather than recommending a change that does not cross the threshold.
To illustrate multiplicity without downloading data in the browser, we retrain small models on Wisconsin Breast Cancer, available in scikit-learn. This differs from the dataset used in the figure. Selection uses validation while test remains held out; the observed range does not prove equivalence.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
X,y=load_breast_cancer(return_X_y=True); X=X[:,[0,2]]
Xtr,Xrest,ytr,yrest=train_test_split(X,y,test_size=.4,stratify=y,random_state=17)
Xval,Xtest,yval,ytest=train_test_split(Xrest,yrest,test_size=.5,stratify=yrest,random_state=18)
random=np.random.default_rng(11); candidates=[]
for seed in range(20):
idx=random.integers(0,len(Xtr),len(Xtr))
model=(LogisticRegression(C=1,max_iter=1000) if seed%2==0 else
DecisionTreeClassifier(max_depth=3,min_samples_leaf=5,random_state=seed))
model.fit(Xtr[idx],ytr[idx]); candidates.append((accuracy_score(yval,model.predict(Xval)),model))
best_val=max(a for a,_ in candidates)
rashomon=[m for a,m in candidates if a>=best_val-.03]
print('candidatos',len(candidates),'seleccionados',len(rashomon),'mejor validación',round(best_val,3))
print('exactitudes de test:',np.round([accuracy_score(ytest,m.predict(Xtest)) for m in rashomon],3))case=Xtest[0]; bg=Xtr[:80]
def marginal_attributions(model,case,bg):
f=lambda rows:model.predict_proba(rows)[:,1]
both=float(f(case[None,:])[0]); base=float(f(bg).mean())
one=bg.copy(); one[:,0]=case[0]
two=bg.copy(); two[:,1]=case[1]
v1=float(f(one).mean());v2=float(f(two).mean())
return np.array([(v1-base+both-v2)/2,(v2-base+both-v1)/2])
phis=np.array([marginal_attributions(m,case,bg) for m in rashomon])
print('rangos SHAP por variable:',np.round(np.column_stack([phis.min(axis=0),phis.max(axis=0)]),4))
print('variable de mayor magnitud por modelo:',np.bincount(np.argmax(abs(phis),axis=1),minlength=2))Comparing text explanations
Download the full local laboratory. It needs PyTorch, Transformers, pandas, pyarrow, spaCy, LIME, SHAP and anchor-exp; it downloads the model and public data when not cached. Run it from a terminal with python text_lab.py --output resultados.json. Output is saved after each case so an interruption is visible. Option --limit 1 checks installation, but the requested comparison requires the default of 100.
The script pins revision 714eb0fa89d2f80546fda750413ed43d93601a13 of DistilBERT fine-tuned on SST-2 and verifies the hash of SST-2 validation at the revision specified in code. It chooses the first 100 texts with 3–12 spaCy tokens that retain the same tokenization after joining with spaces, without looking at labels. This limits length and produces a selection not necessarily representative of all SST-2. The classifier was fitted on training; comparison uses validation without refitting the predictor on these sentences.
The model’s predicted class is used and absent words replaced by UNK: LIME estimates a surrogate with 256 perturbations, KernelSHAP uses a baseline of all tokens replaced and a budget of 128 coalitions for fitting, and anchors searches rules of up to three tokens with target precision 0.9 under its perturbation distribution. For each sentence the sets of three highest-absolute-value positions for LIME and SHAP are compared with anchor-rule positions using Jaccard, . Unequal set sizes and an empty rule affect the metric. This agreement is descriptive: methods have different objectives and sampling, and texts with UNK can fall outside the natural distribution. The script also saves rule precision, LIME local fit and classification accuracy on this selection, not a measurement of human fidelity.
In the hundred-case run, mean Jaccard was 0.702 between LIME and KernelSHAP, 0.284 between LIME and anchor, and 0.298 between SHAP and anchor; classification accuracy on this selection was 0.94. In 42 cases the resulting rule was empty, directly affecting both anchor agreements. Median LIME local fit was 0.618, and mean estimated precision of the 58 nonempty rules was 0.949 under their perturbations. These are statistics for this selection and configuration, not a causal-quality comparison or accuracy estimate over the full sentence distribution.
Exercises
Step 1 of 3. What do the empty and full coalitions fix?
import numpy as np
def linear_recourse(w,b,x,mutable,costs):
pass