SHAP & LIME Explainability
Master SHAP & LIME for explainable AI: model interpretability, feature importance, and production deployment of XAI systems.
What is model explainability?
Model explainability is the practice of producing evidence about how a model's inputs relate to one output. SHAP (SHapley Additive exPlanations) assigns additive feature contributions relative to a reference. LIME (Local Interpretable Model-agnostic Explanations) fits a simple surrogate around one example and uses that local approximation to describe the black-box model.
Explainability matters when engineers must debug unexpected behavior, reviewers must inspect an individual decision, model owners must compare population slices, or governance teams must reproduce what evidence was shown. It complements the measurement discipline in Model Evaluation and Testing; it does not replace model quality, fairness, security, or causal analysis.
Core invariant: an explanation describes model behavior under a declared output, reference population, feature representation, and estimator. It is not proof that a feature caused the real-world outcome.
A plausible chart can be wrong for the decision. Never present an attribution without naming what output was explained, what the baseline represents, how unavailable features were modeled, and how stability or fidelity was tested.
Write the explanation contract before choosing SHAP or LIME
The method is only one part of the system. First define the question, audience, semantics, evidence threshold, and action the explanation is allowed to support.
f(x)
Output
Name the exact class score, probability, logit, regression value, ranking score, or loss being explained.
E[f(X)]
Reference
Version the population, cohort query, or perturbation distribution that defines the comparison.
local or global
Scope
One prediction, a bounded cohort summary, and an organization-wide claim require different evidence.
gate
Trust threshold
Set fidelity, additivity, repeatability, slice, latency, and privacy criteria before generating a chart.
A production contract names seven things
- User and decision: engineer debugging a case, reviewer investigating an outcome, customer receiving a notice, or model owner monitoring a cohort
- Explained output: model version, feature-pipeline version, output name, class index, and output scale
- Reference semantics: background records, cohort filters, weighting, missing-feature rule, and dependence assumption
- Interpretable representation: raw field, engineered feature, grouped concept, token, phrase, superpixel, or another human-facing unit
- Estimator configuration: SHAP variant or LIME implementation, seed, sample count, kernel, sparsity, and numerical tolerance
- Validation policy: fidelity, reconciliation, seed stability, background sensitivity, critical slices, and human review
- Allowed action: investigate, monitor, communicate, contest, or propose an experiment; never silently turn attribution into causal recourse
Which explainer fits the decision you need to support?
Choose the user, access boundary, latency envelope, and dependence risk. The result recommends a starting method and the evidence needed to trust it.
Recommended starting point
TreeSHAP
Use the model structure for efficient additive attributions.
Local
Local packets and aggregated global summaries
Model-native
Order-of-magnitude planning envelope
Profile first
Against a 1,000 ms response budget
Medium
Driven by dependence, sampling, and representation
Method fit
Fit is contextual, not a universal accuracy score.
Reconcile base value plus contributions to the explained model output.
Immutable case packet with model output and reference cohort
Treat the result as model-behavior evidence under a declared reference and representation, never as proof of real-world causality.
SHAP distributes a prediction difference
For a local additive explanation, SHAP represents the explained model output as f(x) = base value + sum(feature contributions). The base value is an expected output under the chosen background and semantics. Each SHAP value is one feature's allocated share of the difference from that base.
Reconciliation
Local accuracy
The base value plus all contributions should recover the explained model output within the method's numerical tolerance and on the same output scale.
No contribution
Missingness
A feature that is absent from the modeled coalition contributes zero under the explainer's missing-feature semantics. Those semantics must match the data domain.
Model comparison
Consistency
When a model changes so a feature's marginal contribution never decreases, a consistent attribution method should not assign that feature a smaller value.
Question definition
Reference dependence
The same prediction can have different valid base values and contribution splits when the comparison population or feature-dependence rule changes.
Choose the SHAP algorithm that matches model access
- TreeSHAP: exploits tree structure and is usually the first choice for supported tree ensembles.
- Linear SHAP: uses linear-model structure; feature dependence still changes the interpretation.
- Deep or gradient variants: approximate attributions for differentiable networks and require architecture-specific validation.
- Kernel or permutation methods: query an arbitrary prediction function but can require many evaluations and produce sampling variance.
- Grouped explanations: combine related encoded features into a human concept when individual columns would split meaning or reveal internals.
Efficiency and mathematical guarantees describe an algorithm under its assumptions. They do not prove that the chosen background, feature groups, or output scale answer the stakeholder's real question.
LIME builds a weighted local surrogate
LIME does not decompose the black-box model directly. It samples perturbed examples, evaluates the black box, weights those examples by proximity to the case, and fits a simple interpretable model to that neighborhood.
1 Map
Choose an interpretable representation
Define what can be switched or varied: tabular bins, tokens, phrases, superpixels, or domain-specific groups.
2 Sample
Generate plausible neighbors
Perturb the case without creating impossible people, transactions, text fragments, or images that the model never encounters.
3 Approximate
Weight and fit locally
Query the black box, apply the proximity kernel, and fit a sparse linear model or another deliberately simple surrogate.
4 Validate
Measure the approximation
Report weighted local fidelity, seed stability, neighborhood coverage, coefficient signs, and the configuration that produced them.
LIME has several independent failure controls
- Neighborhood realism: perturbed records must respect types, constraints, feature relationships, and the production support.
- Kernel width: too narrow yields too little evidence; too wide makes the explanation less local.
- Representation: token deletion, category bins, and engineered features ask materially different questions.
- Sparsity: a short explanation is easier to read but can omit interacting or offsetting features.
- Sampling: low budgets or unlucky seeds can change selected features and coefficient signs.
- Fidelity: the surrogate must reproduce black-box behavior in the weighted neighborhood before its coefficients are interpreted.
Treat SHAP and LIME as different evidence contracts
Neither method wins universally. Match the estimator to model access, explanation scope, latency, and the validation burden the organization can operate.
Model structure available
Specialized SHAP
Prefer an exact or efficient model-specific method when supported. Verify output scale, base value, additivity, feature dependence, and behavior after model-library upgrades.
Additive query evidence
Model-agnostic SHAP
Use when additive semantics matter but only prediction queries are available. Budget many evaluations and gate seed, sample, and background sensitivity.
Fast local hypothesis
LIME
Use for a bounded local investigation with a meaningful interpretable representation. Gate local fidelity and do not promote one surrogate into global importance.
Simpler alternative
Interpretable model
Use a monotonic model, scorecard, small tree, rule list, or generalized additive model when the real requirement is stable, inspectable decision logic.
The reference population defines the question
“Why was this score 72?” is incomplete. An attribution answers why the score differs from a reference such as the full training population, recent production traffic, or a matched peer group. Each comparison can be legitimate, but they are not interchangeable.
Loading explanation evidence
Preparing cases, reference cohorts, and estimator behavior.
Separate semantic change from estimator noise
- Changing the reference cohort deliberately changes the comparison question.
- Changing a random seed under the same frozen contract should not wildly reorder important features.
- Increasing a sampling budget should reduce approximation variance but cannot repair unrealistic perturbations.
- Exact computation can remove sampling noise while leaving dependence and grouping assumptions unresolved.
- A stable explanation can still be unfaithful; a faithful local explanation can still be unsuitable for a global claim.
Validate explanation payloads as production artifacts
An explanation record needs enough metadata and arithmetic evidence to be reproduced after the model, feature store, or explainer library changes.
Persist the evidence bundle
- request and case identifier under the appropriate retention and access policy;
- model, calibration, feature-pipeline, schema, and label versions;
- explainer implementation and library version;
- reference dataset manifest or cohort-query version;
- method parameters, seed, sample count, kernel, and feature groups;
- prediction, base value, contributions, local fidelity, reconciliation gap, and stability metrics;
- audience, presentation template, policy decision, reviewer action, and expiry time.
Do not use feature values as cache keys. Cache only when the model, feature pipeline, reference, explainer configuration, output scale, and authorization context are identical.
Correlation, interaction, and causality need separate treatment
Attribution methods allocate model behavior. They do not identify an intervention unless causal assumptions and evidence are added.
Credit can move
Correlated substitutes
Income, occupation, location, and credit history may carry overlapping signal. Perturbing one independently can create unrealistic records or shift credit to its substitute.
Effects combine
Feature interactions
A contribution can depend on other feature values. Inspect interaction values, grouped concepts, or targeted slices instead of assuming every effect is independent.
Governance risk
Proxy behavior
A permitted feature can encode protected or sensitive information. Attribution may reveal the proxy, but policy and fairness tests must decide whether its use is acceptable.
Causal question
Actionable intervention
To recommend a change, define a feasible intervention, hold the right variables fixed, estimate counterfactual outcomes, and validate the action through domain or experimental evidence.
Use recourse language carefully
- State what the model used, not what caused the real outcome.
- Distinguish immutable facts, controllable actions, administrative corrections, and model artifacts.
- Do not suggest manipulating a proxy when the underlying decision policy would not recognize that change.
- Test whether proposed actions remain valid after model, policy, and data updates.
- Provide a contest or human-review path when an explanation affects a person.
Build an explanation service around versioned evidence
The algorithm belongs inside a controlled system. Separate online prediction from heavier explanation generation so an expensive query cannot overload the decision path.
A production explanation is a governed evidence pipeline
Every arrow carries a versioned artifact, authorization context, and trace identifier. The explanation store is not a public copy of model internals.
Predict
Decision service
Returns the model output and records model, feature, calibration, and policy versions without waiting for optional heavy explanation work.
Authorize and route
Explanation orchestrator
Selects the approved contract by audience, enforces budgets, obtains a consistent feature snapshot, and routes to a compatible explainer.
Compute and validate
Explainer workers
Load the pinned model and reference, generate evidence, check fidelity or reconciliation, repeat unstable estimates, and reject failed outputs.
Audit and communicate
Evidence store and UI
Stores immutable payloads under retention policy and renders only stakeholder-appropriate features, caveats, confidence, and review actions.
Bound the operational path
- Rate-limit explanation requests separately from predictions and require an authorization purpose.
- Queue expensive cohort or sampled jobs; reserve synchronous work for a profiled bounded method.
- Pin model and background artifacts for the full job so a rollout cannot mix versions mid-explanation.
- Redact sensitive inputs, internal fraud rules, security features, and model details from audiences that must not see them.
- Use signed evidence manifests, immutable audit events, expiry, deletion workflows, and reproducible reruns.
- Fall back to a plain decision notice or human review when the explainer times out or fails its gate; never show an unvalidated partial ranking.
Gate explanation releases independently from model releases
A model can pass predictive evaluation while its explanations are unstable, misleading, too slow, or unsafe to disclose. The explanation policy therefore needs its own blocking criteria.
Behavior evidence
Faithfulness
Measure additive reconciliation for SHAP or weighted local fidelity for LIME, then run deletion, insertion, sensitivity, and counterexample probes where appropriate.
Estimator evidence
Repeatability
Compare signs, top-feature overlap, rank correlation, and value variance across seeds, sample budgets, nearby cases, and repeated service calls.
Reference evidence
Semantic robustness
Vary plausible backgrounds, feature groupings, dependence assumptions, and output scales. Document expected movement and block unexplained reversals.
Decision evidence
Human usefulness
Test comprehension, calibrated trust, review time, contest quality, and error discovery with the actual audience instead of measuring chart preference alone.
Monitor after launch
- explanation latency, queue depth, timeout rate, cache hit rate, and model-query volume;
- fidelity, reconciliation, sign agreement, rank overlap, and failed-gate rate by model and slice;
- base-value and attribution-distribution drift against input and prediction drift;
- unknown feature versions, missing references, mixed model versions, and reproducibility failures;
- sensitive-feature disclosure, unauthorized requests, scraping patterns, and suspicious probing;
- reviewer overrides, user contests, action outcomes, and cases where explanations increased confidence in a wrong decision.
Know when not to generate a feature ranking
Feature attribution is a poor fit when the stakeholder needs a causal intervention, the model output itself is not sufficiently accurate, the input representation has no meaningful human units, or disclosure would expose security controls or personal data.
Prefer a different response when
- an interpretable model can meet the quality target with a more stable decision policy;
- the real question is counterfactual recourse and requires feasibility plus causal constraints;
- a data-quality or model-drift investigation should happen before any individual explanation;
- the explanation cannot pass fidelity or repeatability gates under a realistic compute budget;
- the audience needs policy reasons, evidence sources, and appeal options rather than internal model mechanics;
- the only available chart would imply precision, certainty, or causality the system cannot support.
The best explanation system sometimes refuses to manufacture a ranking and routes the case to a clearer model, a domain review, or a better-specified question.