AI Logic

Explainability (XAI)

SmoothGrad

Updated:

Diagram of SmoothGrad. Left: the flow of repeating n times the process of backpropagating a CNN's score to the input for a noisy image, then averaging the gradients. Right: four noisy copies of an input of abstract shapes with their speckled gradients, the map from the absolute value of the average over 50 copies in which only the area over the circle remains, and a comparison with a single gradient computed without noise

What is SmoothGrad?

SmoothGrad is a method that reduces the speckle-like noise of gradient saliency maps by creating many copies of the input image with small noise added and averaging their gradient maps. It was proposed by Smilkov et al. in 2017. The paper's subtitle is "removing noise by adding noise."

A map of the gradient of the class score with respect to the input image points to the area around the object, but it also tends to light up pixels that look random to the human eye. SmoothGrad attributes this visual noise to "the gradient fluctuating sharply with tiny differences in the input," and smooths it out by averaging the gradient in the neighborhood of the input.

The computation simply repeats a gradient saliency map a few dozen times on noisy images and averages the results. No change to the model is needed, and it can be combined with other gradient-based methods such as Integrated Gradients and Guided Backpropagation.

A gradient measured at a single point is like the slope of a single step on a bumpy road. The slope changes sharply every time a pebble is stepped on, but measuring the slope at several nearby spots and averaging reveals the true direction of the hill. SmoothGrad extracts this "direction of the hill" by measuring and averaging gradients around the input.

How it is computed

This section follows the equations in Section 2 of Smilkov et al. (2017), who proposed the method. Let xx be the input image and ScS_c the score for class cc.

The underlying gradient map (called a sensitivity map in the paper) is the derivative of the score with respect to the input.

Mc(x)=∂Sc(x)∂xM_c(x) = \frac{\partial S_c(x)}{\partial x}

The steps of SmoothGrad are as follows.

  1. Choose the noise level σ\sigma and the number of samples nn.
  2. Create nn copies of the input image xx with Gaussian noise of mean 0 and standard deviation σ\sigma added.
  3. For each image, compute the gradient map McM_c by backpropagation.
  4. Average the nn maps (equation below).
  5. For display, take absolute values as needed, suppress outliers, and overlay the result on the image.
M^c(x)=1n∑1nMc(x+N(0,σ2))\hat{M}_c(x) = \frac{1}{n} \sum_{1}^{n} M_c\big(x + \mathcal{N}(0, \sigma^2)\big)

This amounts to a stochastic approximation of the gradient averaged around the input with Gaussian weights (smoothed with a Gaussian kernel). Since computing this average exactly in a high-dimensional input space is difficult, it is approximated with a small number of random images.

The right side of the diagram at the top shows an example of this computation. The gradient of each individual noisy image has speckles across the whole image, not only on the circle. Averaging 50 of them cancels out the fluctuations that differ from image to image, leaving only the gradient over the circle that appears consistently in every image.

Why adding noise makes the map cleaner

Why does the gradient fluctuate? The paper shows that the derivative of the score ScS_c fluctuates sharply at small scales. Moving gradually from an image xx to a nearby image x+ϵx + \epsilon that is indistinguishable to the human eye (ϵ\epsilon is one draw of Gaussian noise with standard deviation 0.01), all intermediate images are classified correctly, yet the partial derivatives with respect to the R, G and B values of a single pixel change substantially.

The score of a network using ReLU is not a smoothly differentiable function. Moreover, ordinary training gives no reason for the derivative to vary smoothly. A gradient measured at a single point is therefore thought to contain many meaningless local fluctuations, and these fluctuations appear as visual noise in the map.

The explanation that gradient fluctuation causes noise in the map is a hypothesis of the paper. The paper presents examples supporting it, while noting that other causes are possible (for example, noise affecting different image textures differently). A SmoothGrad map being easy to read does not prove that it correctly reflects the model's decision.

The paper also reports that regularization by adding noise to the inputs during training makes maps cleaner as well. The effects of training-time noise and SmoothGrad (inference-time noise) add up, and using both gave the most readable maps.

Experiments in the paper

The paper experimented with Inception v3 (an improved version of GoogLeNet) trained on ImageNet (ILSVRC-2013) and with a convolutional model on MNIST. Since there was no established way to measure map quality numerically, the evaluation was by visual comparison.

What was examinedResult
Noise level σ\sigma10–20% of the range of pixel values (xmax⁡−xmin⁡x_{\max} - x_{\min}) gave a good balance between map sharpness and the structure of the original image. However, the optimal value varies with the input
Number of samples nnMaps became smoother as more samples were used, but beyond 50 the appearance barely changed
Visual comparison with other methodsOn 200 randomly chosen images, SmoothGrad consistently produced maps more concentrated on the object than the plain gradient and Integrated Gradients. Guided Backpropagation produced the sharpest maps but tended to fail on images with uniform backgrounds. SmoothGrad was especially effective on images with uniform backgrounds
Discriminating classesFor images with objects of two classes, such as a cat and a dog, the difference between the two class maps distinguished the location of each class better than other methods
Combining with other methodsAdding SmoothGrad to Integrated Gradients and Guided Backpropagation made the maps of both more coherent

Display tips and caveats in practice

How a map is displayed greatly changes how it looks. The paper lists the following techniques.

  • Whether to take absolute values: When objects always have the same color, as in MNIST, positive gradients directly represent cues for the class. On ImageNet, taking absolute values gave more readable maps, because the sign of the gradient is reversed between a white ball on a dark background and a black ball on a light background.
  • Suppressing outliers: A small number of pixels can have very large gradients, and coloring them as is makes most of the map black. Capping values above the top 1% (the 99th percentile) at that value yields a coherent map. This property has also been used to create adversarial examples.
  • Whether to multiply by the input image: Multiplying the gradient by the pixel values tends to give cleaner maps, but pixels with value 0 never appear in the map no matter how important they are. For example, if black is represented as 0, a black ball on a white background does not show up in the map.

Keep the following points in mind when using SmoothGrad.

  • Computation grows nn-fold: The gradient computation is repeated nn times (around 50). Grouping the noisy images into a single batch makes it faster.
  • The optimal σ\sigma depends on the input: Start from the paper's guideline (10–20% of the value range) and adjust while looking at the map.
  • Evaluation is visual: The paper's comparisons are visual assessments. A map being easy to read is a separate question from whether it correctly reflects the model's decision.

Comparison with other visualization methods

The table below compares SmoothGrad with pixel-level visualization methods it is often compared against, from the same perspectives.

MethodWhat it usesMap appearanceComputationMain weakness
Gradient saliency mapGradient at the inputMany speckles1 backward passLocal gradient fluctuations show up directly
SmoothGradAverage of gradients at noisy inputsTends to concentrate on the objectnn backward passes (around 50)σ\sigma and nn must be chosen
Guided BackpropagationGradient with negative values discarded during backpropagationSharpest1 backward passTends to fail on images with uniform backgrounds; weak at discriminating classes
Integrated GradientsIntegral of gradients from a baseline input to the inputIn the paper's comparison, often less coherent than SmoothGrad20 to 300 backward passesResults depend on the choice of baseline

Rather than competing with other methods, SmoothGrad is layered on top of gradient-based methods. Combinations such as averaging Integrated Gradients attributions over noisy images are also possible.

Rough guidelines for choosing:

  • To make a gradient map easier to read: Apply SmoothGrad to the gradient saliency map.
  • To get values whose sum of contributions matches the score difference: Use Integrated Gradients, and layer SmoothGrad on top when a cleaner appearance is wanted.
  • To quickly see the rough location of objects: Use Grad-CAM.

PyTorch example

Show code
python
import torch
from torchvision import models

'''
Compute SmoothGrad for one image with a pretrained ResNet-18
(Smilkov et al. 2017: M̂_c(x) = (1/n) Σ M_c(x + N(0, σ²)), M_c = ∂S_c/∂x)
'''

device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT).to(device)
model.eval()  # Put Dropout and BatchNorm in inference mode (noise is added only to the input)


def smoothgrad(model, x, target_class, n=50, noise_level=0.15, batch_size=25):
  # x: [1, 3, H, W] (normalized). noise_level is σ as a fraction of the value range (x_max - x_min)
  sigma = noise_level * (x.max() - x.min())
  total = torch.zeros_like(x)
  done = 0
  while done < n:
    b = min(batch_size, n - done)
    # Step 2: create a batch of images with Gaussian noise added
    noisy = x.repeat(b, 1, 1, 1) + sigma * torch.randn(b, *x.shape[1:], device=x.device)
    noisy.requires_grad_(True)
    scores = model(noisy)[:, target_class]          # Scores S_c before the softmax
    # Step 3: gradient M_c for each image (weights are not updated)
    grads = torch.autograd.grad(scores.sum(), noisy)[0]
    total += grads.sum(dim=0, keepdim=True)
    done += b
  return total / n                                  # Step 4: average


def to_heatmap(grad, q=0.99):
  # Step 5: take absolute values, max across channels, cap the top 1%, and scale to 0-1
  m = grad[0].abs().amax(dim=0)
  cap = torch.quantile(m.flatten(), q)
  return (m.clamp(max=cap) / (cap + 1e-8)).detach()


# 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()
heatmap = to_heatmap(smoothgrad(model, x, target))
print(heatmap.shape)  # torch.Size([224, 224])

FAQ

Q. How should the noise level $\sigma$ and the number of samples $n$ be chosen?
A.

The paper's guideline is σ\sigma at 10–20% of the range of pixel values (xmax⁡−xmin⁡x_{\max} - x_{\min}) and nn around 50. The paper reports that the appearance barely changed for nn beyond 50. Since the optimal σ\sigma depends on the input, start from the guideline and adjust while looking at the map.

Q. How does it differ from data augmentation that adds noise during training?
A.

SmoothGrad adds noise to the input when creating an explanation, without changing the trained model. Adding noise during training is regularization that changes the model's weights themselves. In the paper, training-time noise also made maps cleaner, and using both gave the most readable maps.

Q. Can it be used for models other than image models?
A.

The computation itself is possible for any model that is differentiable with respect to its input. However, the paper's experiments cover only image classification (ImageNet and MNIST), and whether the same effect holds for other kinds of models and tasks is left as future work.

References

  1. D. Smilkov, N. Thorat, B. Kim, F. Viégas, and M. Wattenberg, "SmoothGrad: removing noise by adding noise," arXiv:1706.03825, 2017.
  2. K. Simonyan, A. Vedaldi, and A. Zisserman, "Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps," arXiv:1312.6034, 2013.
  3. 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).
  4. J. T. Springenberg, A. Dosovitskiy, T. Brox, and M. Riedmiller, "Striving for Simplicity: The All Convolutional Net," arXiv:1412.6806, 2014.