AI Logic

Explainability (XAI)

Integrated Gradients

Updated:

Diagram of Integrated Gradients. The left side is a graph of the score along the path from a black image to the input, which flattens near the input so that the gradient becomes 0. The right side shows a computation example in which the gradients of 4 intermediate images are averaged and multiplied by the difference between the input and the baseline to obtain contributions, which are overlaid on an input image of abstract shapes

What is Integrated Gradients?

Integrated Gradients is a method that splits a model's prediction into contributions from each input feature. Along a straight path from a baseline input representing "nothing" (a black image, for images) to the actual input, it takes gradients step by step, adds them up, and multiplies the result by the difference between the input and the baseline to obtain contributions. Sundararajan, Taly, and Yan proposed it in 2017.

The defining property of this method is that the contributions sum exactly to the difference between the scores at the input and at the baseline. For example, if the class score for an image is 0.9 and the score for a black image is 0, the contributions of all pixels add up to 0.9. It numerically allocates how much of the score each pixel accounts for.

Looking only at the gradient at the input, as the gradient saliency map does, gives zero gradient even for important features wherever the model's output has leveled off (is saturated). Integrated Gradients avoids this problem by using all the gradients along the way from the baseline to the input.

There is no need to modify the trained model; it can be computed simply by repeating an ordinary gradient computation tens to hundreds of times. Besides image classification, it can be used for text classification, machine translation, predicting molecular properties, and more.

The baseline input is the point of comparison: "what if this feature were absent". When people think about causes, they also compare with "what would have happened without it". An Integrated Gradients contribution expresses how much that feature moved the score compared with the baseline input.

Background: two axioms that attribution methods should satisfy

The paper lists two properties (axioms) that methods for computing contributions should satisfy, and shows that many existing methods violate one or the other.

AxiomContentExamples of methods that violate it
SensitivityIf the input and the baseline differ in only one feature and the predictions differ, the contribution of that feature is nonzeroGradients at the input, DeconvNet, Guided Backpropagation
Implementation invarianceTwo networks that return the same output for every input are given the same contributions, even if their internals differDeepLIFT, LRP

As an example where gradients violate sensitivity, the paper gives f(x)=1−ReLU(1−x)f(x) = 1 - \mathrm{ReLU}(1 - x). Changing from the baseline x′=0x' = 0 to the input x=2x = 2 changes the output from 0 to 1. However, the function is flat for x≥1x \geq 1, so the gradient at the input x=2x = 2 is 0, and the contribution is also 0.

DeepLIFT and LRP, on the other hand, avoid the sensitivity problem by using differences from the baseline (discrete gradients), but because they backpropagate layer by layer, the chain rule does not hold, and the contributions can change for the same function if its implementation differs. Integrated Gradients uses only ordinary gradients, so it is implementation invariant, and because it looks at the whole path from the baseline, it also satisfies sensitivity.

Computation steps

The explanation follows the equations in Sections 3 and 5 of Sundararajan et al. (2017), who proposed the method. Let FF be the model's output, xx the input, and x′x' the baseline input.

  1. Choose the baseline input x′x'. A black image for images, or all-zero embeddings for text, are good starting points.
  2. On the straight path from x′x' to xx, take mm points x′+km(x−x′)x' + \tfrac{k}{m}(x - x') (k=1,…,mk = 1, \dots, m).
  3. At each point, compute the gradient of the output FF with respect to the input.
  4. Average the gradients and multiply by the difference between the input and the baseline, xi−xi′x_i - x'_i, to obtain the contribution of feature ii (Eq. 3).
  5. Check that the sum of the contributions is close to F(x)−F(x′)F(x) - F(x'). If it is not, increase mm.

Integrated Gradients is defined as the integral of the gradient along the path (Eq. 1).

IntegratedGradsi(x)=(xi−xi′)×∫01∂F(x′+α(x−x′))∂xi dα(1)\mathrm{IntegratedGrads}_i(x) = (x_i - x'_i) \times \int_{0}^{1} \frac{\partial F\big(x' + \alpha (x - x')\big)}{\partial x_i}\, d\alpha \qquad (1)

In practice, the integral is approximated by a sum (Eq. 3).

IntegratedGradsiapprox(x)=(xi−xi′)×∑k=1m∂F(x′+km(x−x′))∂xi×1m(3)\mathrm{IntegratedGrads}^{\mathrm{approx}}_i(x) = (x_i - x'_i) \times \sum_{k=1}^{m} \frac{\partial F\big(x' + \tfrac{k}{m} (x - x')\big)}{\partial x_i} \times \frac{1}{m} \qquad (3)

These contributions satisfy the following completeness property (Proposition 1). It is the fundamental theorem of calculus applied along the path.

∑i=1nIntegratedGradsi(x)=F(x)−F(x′)\sum_{i=1}^{n} \mathrm{IntegratedGrads}_i(x) = F(x) - F(x')

The top figure is an example of this computation. As in the graph on the left, the score rises as the path moves from the black image (α=0\alpha = 0) toward the input (α=1\alpha = 1), and levels off near the input. As a result, the gradient at the input itself (α=1\alpha = 1) is 0. Even so, at the intermediate points α=0.25\alpha = 0.25, 0.50.5, and 0.750.75 there are large gradients over the circle, and averaging them assigns the contributions to the circle. With m=4m = 4, the sum of the contributions is 0.66, short of the true F(x)−F(x′)=1F(x) - F(x') = 1, but it approaches that value as mm increases.

Why a straight path is used

Why a straight path? The path from the baseline to the input does not have to be straight. Citing a result on cost sharing in economics (Friedman, 2004), the paper shows that methods that integrate gradients along a path (path methods) are, as a family, the only methods that satisfy four properties: implementation invariance, completeness, zero contribution for irrelevant variables, and linearity. It then gives two reasons for choosing the straight path.

  • It is the simplest path: it has the simplest mathematical form.
  • It is the only path method that preserves symmetry: two variables that can be swapped without changing the function receive the same contribution if they have the same values in both the input and the baseline. The paper proves that the straight path is the only path method with this property (Theorem 1).

Integrated Gradients corresponds to a well-known cost-sharing method in economics (Aumann-Shapley). It gives different results from the Shapley-Shubik method, which averages over all orderings of the features. For example, for min⁡(x1,x2)\min(x_1, x_2) with baseline (0,0)(0, 0) and input (1,3)(1, 3), Integrated Gradients assigns the entire change to x1x_1, while the Shapley-Shubik method assigns 1/21/2 to each.

Applications in the paper

The paper shows examples of applying Integrated Gradients to five models covering images, text, and molecules. These are not numerical experiments competing on accuracy, but examples showing that the method is useful for understanding models and finding bugs.

TaskModelBaseline inputFindings
Object recognitionGoogLeNet trained on ImageNetBlack imageHighlights the distinctive parts of the image better than gradient at the input × image
Diabetic retinopathy severityDeep network on retinal fundus imagesBlack imagePositive contributions around lesions and negative ones inside them, showing that the model looks at lesion boundaries
Question type classificationKim's (2014) text classification modelAll-zero embeddingsAgrees with known rules, such as "how many" being a cue for questions about numbers. It also revealed a new rule, "total number", and an undesirable correlation in which "charles" is a cue for yes/no questions
Machine translationLSTM-based translation systemEmbeddings set to 0 except for the start and end symbolsAligns output words with input words ("und" with "and", "morgen" with "morning")
Molecular activity predictionGraph convolutions over moleculesAtom and atom-pair features set to 0Bonded atom pairs account for 46% of the prediction and other pairs for −3%. For another structure, it revealed a bug in which atoms with different neighbors received the same contribution

In the paper's experience, the number of points mm needed for the approximation is 20 to 300, which keeps the sum of the contributions within 5% of F(x)−F(x′)F(x) - F(x'). For the highly nonlinear translation model, 100 to 1000 were used.

Caveats in practice

Integrated Gradients contributions change with the choice of baseline input. The paper recommends choosing a baseline for which the prediction score is nearly 0 and which represents a state with "no signal at all". For example, if the baseline is an image made by adding a small perturbation to an image to bring the "elephant" score to 0, as in crafting adversarial examples, traces of that perturbation get mixed into the contributions.

Keep the following points in mind as well.

  • Check the approximation with completeness: compare the sum of the contributions with F(x)−F(x′)F(x) - F(x'), and increase the number of points mm if they differ.
  • The computation is expensive: the gradient computation is repeated mm times (about 20 to 300). Putting the intermediate inputs together into a single batch speeds it up.
  • A black baseline gives zero contribution to dark pixels: the contributions are multiplied by xi−xi′x_i - x'_i, so pixels that are already black receive zero contribution no matter how important they are.
  • It differs from attention weights: the paper points out that using attention weights in place of contributions overlooks influence that passes through memory cells and recurrent states.

Comparison with other attribution methods

The table compares Integrated Gradients with attribution methods it is often compared with, from the same viewpoints.

MethodWhat it usesBaseline inputContributions sum to the score differenceImplementation invariantAmount of computation
Gradient saliency mapGradient at the inputNot usedNoYes1 backward pass
SmoothGradAverage of gradients at noise-perturbed inputsNot usedNoYesTens of backward passes
DeepLIFTDifferences from the baseline backpropagated layer by layerUsedYesNo1 backward pass
Integrated GradientsIntegral of gradients from the baseline to the inputUsedYesYes20 to 300 backward passes

Rough guidelines for choosing:

  • To allocate contributions numerically (what fraction of the score is due to this feature): use Integrated Gradients. It satisfies completeness and is implementation invariant.
  • To compute quickly with a single backward pass: use DeepLIFT. However, the contributions can change for the same function depending on its implementation.
  • To get a quick look at which parts of an image the model is looking at: use Grad-CAM or the gradient saliency map.

PyTorch example

Show code
python
import torch
from torchvision import models

'''
Compute Integrated Gradients for a single image with a pretrained ResNet-18
(Eq. 3 of Sundararajan et al. 2017: (x - x') × average of the gradients at m points on the path)
'''

device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT).to(device)
model.eval()  # put BatchNorm in inference mode (gradients can still be computed)


def integrated_gradients(model, x, target_class, baseline=None, steps=50, batch_size=25):
  # x: [1, 3, H, W] (normalized). If baseline is omitted, it is 0 (0 after normalization; see the note below)
  if baseline is None:
    baseline = torch.zeros_like(x)
  alphas = torch.arange(1, steps + 1, device=x.device) / steps   # k/m (k = 1, ..., m)
  total_grad = torch.zeros_like(x)
  for chunk in alphas.split(batch_size):
    # step 2: put the points x' + (k/m)(x - x') on the path together into one batch
    path = baseline + chunk.view(-1, 1, 1, 1) * (x - baseline)
    path.requires_grad_(True)
    scores = model(path)[:, target_class]      # scores before the softmax
    # step 3: gradient at each point (the weights are not updated)
    grads = torch.autograd.grad(scores.sum(), path)[0]
    total_grad += grads.sum(dim=0, keepdim=True)
  # step 4 (Eq. 3): average of the gradients × (x - x')
  attributions = (x - baseline) * total_grad / steps
  # step 5: check completeness (sum of contributions ≈ F(x) - F(x'))
  with torch.no_grad():
    delta = model(x)[0, target_class] - model(baseline)[0, target_class]
  print(f'sum of contributions {attributions.sum().item():.4f}, F(x) - F(x\') {delta.item():.4f}')
  return attributions


# Example: a random image (in practice, use an image normalized with transforms)
x = torch.randn(1, 3, 224, 224, device=device)
target = model(x).argmax(dim=1).item()
attr = integrated_gradients(model, x, target)
heatmap = attr[0].sum(dim=0)   # sum over channels for display
print(heatmap.shape)           # torch.Size([224, 224])
# Note: if the image is normalized with a mean and standard deviation, 0 after normalization is the mean color, not black.
# To use a black image as the baseline, pass a black image (all zeros) normalized with the same transforms as baseline.

FAQ

Q. How many points $m$ should be used?
A.

In the paper's experience, 20 to 300, which keeps the sum of the contributions within 5% of F(x)−F(x′)F(x) - F(x'). To decide, compare the sum of the contributions with F(x)−F(x′)F(x) - F(x'), and increase mm if they differ. Highly nonlinear models may need even more (100 to 1000 for the paper's translation model).

Q. What should be used as the baseline input?
A.

Choose an input for which the prediction score is nearly 0 and which represents "no signal at all". The paper uses a black image for images and all-zero embeddings for text. Noise images have the same property, but the paper notes that a black image can show edge features more cleanly.

Q. How does it differ from gradient × input?
A.

Gradient × input uses only the gradient at the input xx. It corresponds to Eq. 3 with a zero baseline and m=1m = 1 point, that is, approximating the integral with only the gradient at the end of the path. If the model is saturated near the input, the gradient becomes 0, and so do the contributions of important features. Integrated Gradients uses all the gradients along the path, so this problem does not occur.

References

  1. M. Sundararajan, A. Taly, and Q. Yan, "Axiomatic Attribution for Deep Networks," Proceedings of the 34th International Conference on Machine Learning (ICML), PMLR 70, 2017(arXiv:1703.01365).
  2. A. Shrikumar, P. Greenside, and A. Kundaje, "Learning Important Features Through Propagating Activation Differences," ICML, PMLR 70, pp. 3145–3153, 2017(arXiv:1704.02685).
  3. K. Simonyan, A. Vedaldi, and A. Zisserman, "Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps," arXiv:1312.6034, 2013.