🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Explainable AI: Attention, Gradients, SHAP and LIME

🟢 Free Lesson

Explainable AI: Attention, Gradients, SHAP and LIME

A model approves a loan application and the applicant asks why. A physician wants a second opinion on a diagnosis suggestion. A debugging session needs to know which input feature flipped a prediction from one class to another. In each case the question is the same: what inside this black box produced this output? Explainable AI is the toolkit for answering it — and, just as importantly, knowing when the answer is trustworthy.

Two kinds of explanation are needed for different jobs. Local explanations justify a single prediction: this specific input was classified this way because of these features. Global explanations characterize the model as a whole: across all inputs, these are the patterns that drive its decisions. No method serves both well, and a common failure is presenting a local explanation as if it revealed global behavior.

This lesson covers the main families — attention visualization for transformers, gradient-based attribution, perturbation methods like LIME, and Shapley values via SHAP — with working implementations, a comparison of what each actually claims, and a method for validating explanations rather than assuming they are correct.

Why black boxes hit a wall

The case for explanation is partly regulatory and partly operational. Regulations like GDPR give individuals a right to meaningful information about automated decisions; domain-specific rules in credit and healthcare demand rationale, not just a score. Operationally, explanations are a debugging instrument: when a classifier fails, an explanation that points at an unexpected feature (a watermark, a length artifact, a demographic proxy) usually identifies the bug faster than more data analysis.

The danger is mistaking plausibility for fidelity. An explanation can look compelling and still misrepresent the model's true computation. Techniques differ precisely in how strong their fidelity guarantee is: gradient methods differentiate the actual network, so they are faithful by construction (subject to noise), while perturbation methods fit a local surrogate to observed behavior and inherit whatever distortion that approximation introduces.

Attention is a window, not a verdict

Transformer attention maps are the most accessible explanations available: the model literally records how much each token attended to each other token. Extracting them is straightforward when you request attention outputs:

python
import torch
import numpy as np
from typing import List, Tuple

class AttentionInspector:
    def __init__(self, model, tokenizer):
        self.model = model
        self.tokenizer = tokenizer

    def attention_matrix(self, text: str, layer: int = -1) -> Tuple[np.ndarray, List[str]]:
        inputs = self.tokenizer(text, return_tensors="pt")
        with torch.no_grad():
            out = self.model(**inputs, output_attentions=True)
        attn = out.attentions[layer][0]
        weights = attn.mean(dim=0).numpy()
        tokens = self.tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
        return weights, tokens

    def top_influential_tokens(self, text: str, k: int = 5,
                               layer: int = -1) -> List[Tuple[str, float]]:
        weights, tokens = self.attention_matrix(text, layer)
        received = weights.mean(axis=0)
        order = received.argsort()[::-1][:k]
        return [(tokens[i], float(received[i])) for i in order]

The caveat is well known from the "attention is not explanation" debate: attention weights show where information was gathered, not what the model did with it afterwards. Subsequent layers can transform gathered information in ways attention alone does not predict, and attention patterns can be manipulated without changing outputs. The responsible use of attention maps is as a hypothesis generator — a starting point for probing — not as a definitive rationale to show a stakeholder. For that, pair them with a gradient-based method that measures actual influence on the output.

Gradient-based attribution

If the model is a differentiable function, the most direct question is: how does the output change when this input element changes? The gradient answers it, and two variants matter in practice.

Vanilla gradients take the gradient of the target class logit with respect to the input and rank features by magnitude. They are cheap but noisy — small weight perturbations can swing gradients, and saturated activations can produce vanishing gradients that understate a feature's role. Integrated gradients fixes this by integrating the gradient along a path from a baseline (usually zeros) to the actual input, and it carries a formal completeness property: the attributions sum to the difference between the baseline and actual output.

python
import torch

class GradientAttribution:
    def __init__(self, model):
        self.model = model

    def integrated_gradients(self, x: torch.Tensor, target_class: int,
                             steps: int = 64) -> torch.Tensor:
        baseline = torch.zeros_like(x)
        grads = []
        for i in range(steps + 1):
            alpha = i / steps
            point = (baseline + alpha * (x - baseline)).requires_grad_(True)
            logits = self.model(point)
            self.model.zero_grad()
            one_hot = torch.zeros_like(logits)
            one_hot[0, target_class] = 1.0
            logits.backward(gradient=one_hot)
            grads.append(point.grad.detach())
        avg = torch.stack(grads).mean(dim=0)
        return (x - baseline) * avg

    def occlusion_sensitivity(self, x: torch.Tensor, target_class: int,
                              patch: int = 8) -> torch.Tensor:
        baseline_score = self.model(x)[0, target_class].item()
        sens = torch.zeros_like(x)
        _, h, w = x.shape[0], x.shape[-2], x.shape[-1]
        for top in range(0, x.shape[-2], patch):
            for left in range(0, x.shape[-1], patch):
                occluded = x.clone()
                occluded[:, :, top:top + patch, left:left + patch] = 0.0
                score = self.model(occluded)[0, target_class].item()
                sens[:, :, top:top + patch, left:left + patch] = baseline_score - score
        return sens

Baseline choice is the underappreciated decision in integrated gradients. Zeros work for images (black is a neutral canvas) but are meaningless for text, where the empty sequence may be out of distribution entirely; for language models, a reference like padding tokens or a domain-average embedding is more defensible. Results can shift materially with the baseline, so report it — an attribution without a stated reference is uninterpretable.

Occlusion sensitivity is the model-agnostic cousin: mask a region, observe the score change. It is slow (one forward pass per region) but requires no gradients and no differentiability, which makes it the fallback for API-only models where you can query but not introspect.

LIME: local surrogate models

LIME fits a simple, interpretable model — usually weighted linear regression — to approximate the black box in the neighborhood of one prediction. It samples perturbations around the input, queries the model on each, and fits the surrogate with weights that decay with distance from the original point. The surrogate's coefficients become the explanation.

python
import numpy as np
from sklearn.linear_model import Ridge

class LimeTabular:
    def __init__(self, predict_fn, n_samples: int = 1000, kernel_width: float = 0.75):
        self.predict_fn = predict_fn
        self.n_samples = n_samples
        self.kernel_width = kernel_width

    def explain(self, instance: np.ndarray, top_k: int = 5) -> dict:
        n_features = instance.shape[0]
        perturbations = np.random.binomial(
            1, 0.5, size=(self.n_samples, n_features)
        ).astype(float)

        predictions = self.predict_fn(perturbations)

        distances = np.linalg.norm(perturbations - instance, axis=1)
        weights = np.exp(-(distances ** 2) / (self.kernel_width ** 2))

        surrogate = Ridge(alpha=1.0)
        surrogate.fit(perturbations, predictions, sample_weight=weights)

        order = np.argsort(np.abs(surrogate.coef_))[::-1][:top_k]
        return {
            "features": order.tolist(),
            "coefficients": surrogate.coef_[order].tolist(),
            "local_r2": surrogate.score(perturbations, predictions, sample_weight=weights),
        }

explainer = LimeTabular(model_predict, n_samples=2000)
result = explainer.explain(sample_row, top_k=5)

Report the local R² alongside the coefficients — it tells you how well the surrogate actually explains the model in this neighborhood. A low local R² means the coefficients are describing a bad fit, and the explanation should be discarded rather than presented. This check is what separates rigorous LIME usage from the pattern of running the library and pasting whatever comes out.

SHAP: Shapley values with theory behind them

SHAP frames feature attribution through cooperative game theory. The Shapley value is the unique attribution scheme satisfying a handful of fairness axioms: split the credit for a prediction among features, where each feature's contribution is its average marginal effect across all orderings of features. The axioms give SHAP a theoretical standing the heuristic methods lack.

Exact Shapley computation is exponential in feature count, so practical SHAP uses approximations — KernelSHAP (weighted regression over feature subsets, a generalization of LIME), TreeSHAP (exact and fast for tree ensembles), and DeepSHAP (gradient-based for neural networks).

python
import shap

class SHAPWrapper:
    def __init__(self, model, background: "np.ndarray", kind: str = "deep"):
        if kind == "deep":
            self.explainer = shap.DeepExplainer(model, background)
        elif kind == "kernel":
            self.explainer = shap.KernelExplainer(model.predict_proba, background)
        else:
            self.explainer = shap.TreeExplainer(model)

    def global_summary(self, data: "np.ndarray") -> None:
        values = self.explainer.shap_values(data)
        shap.summary_plot(values, data)

    def local_force(self, row: "np.ndarray") -> None:
        values = self.explainer.shap_values(row.reshape(1, -1))
        shap.force_plot(
            self.explainer.expected_value if not isinstance(values, list)
            else self.explainer.expected_value[1],
            values[1] if isinstance(values, list) else values,
            row,
        )

Two practical notes. Shap values are relative to the expected model output over the background distribution, so the choice of background set changes the baseline and therefore every attribution — a background that is unrepresentative of production traffic produces misleading explanations. And correlated features break the independence assumption the game-theoretic formulation relies on: when two features carry the same information, Shapley splits credit between them arbitrarily, and different coalitions can tell different stories. Group correlated features or interpret with that ambiguity in mind.

Choosing and validating an explainer

MethodScopeFidelitySpeedBest for
Attention mapsLocalIndirect (not causal)Very fastHypothesis generation on transformers
Vanilla gradientsLocalHigh (exact derivative)FastQuick feature ranking on differentiable models
Integrated gradientsLocalHigh (completeness)MediumDefensible single-prediction attributions
OcclusionLocalHigh (measured effect)SlowNon-differentiable or API-only models
LIMELocalApproximate (surrogate)MediumTabular, when a linear local story suffices
SHAP (Kernel/Tree)Local + globalAxiomatic approximationSlow to fastRegulatory-facing attribution, tree models

Validation should be part of the workflow, not an afterthought. Sanity checks include: randomize model weights and confirm attributions change (Adebayo et al.'s sanity test); delete or perturb the top-ranked feature and verify the prediction actually moves (faithfulness); and check that two methods with different assumptions — say, integrated gradients and LIME — agree on the headline features. When methods disagree, that disagreement is information: investigate before shipping any explanation to users.

Finally, explain with humility. Explanations serve a decision that still involves a human; presenting them as the model's true reasoning overstates what any current method can provide. Document the method, the baseline, and the known limitations next to every explanation your product displays.

Common Mistakes

Presenting attention weights as a causal explanation

Fix: Pair attention maps with gradient-based attribution before showing anything to a stakeholder.

Using zeros as the integrated-gradients baseline for text

Fix: Choose a meaningful reference (padding, empty input, or domain average) and document it with the result.

Ignoring local R² in LIME output

Fix: Discard explanations whose surrogate fits poorly — the coefficients describe a model that is not the black box.

Passing an unrepresentative background set to SHAP

Fix: Sample the background from production traffic; the baseline defines every attribution you will report.

Trusting a single method without sanity checks

Fix: Run weight-randomization and deletion tests — an explanation that survives no check is a story, not evidence.

Key Takeaways

  • Explanations are local (one prediction) or global (model behavior) — mixing the two is the most common misreading.
  • Gradient methods are faithful by construction; attention maps are hypotheses; surrogate methods inherit approximation error.
  • Integrated gradients needs a stated baseline, and completeness gives its attributions a checkable property.
  • SHAP's axiomatic foundation buys credibility for regulatory contexts, but correlated features still split credit arbitrarily.
  • Validate explanations with sanity and faithfulness tests before they influence any real decision.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement