AI Logic

Explainability (XAI)

LRP (Layer-wise Relevance Propagation)

Updated:

Diagram of LRP. The left side shows the flow: a forward pass records the values, the output score is passed down layer by layer as relevance, and it becomes per-pixel relevance. The right side shows a computation example on a small network with 2 hidden neurons that takes an image of a circle and a triangle as input: relevance is distributed from the output to the hidden layer and then to the pixels, and the sum equals the output of 0.36 at every layer

What is LRP?

LRP (Layer-wise Relevance Propagation) is a method that treats the network's output score as "relevance" and redistributes it from the output to the input one layer at a time to obtain per-pixel contributions. Bach, Binder, Montavon, Klauschen, MΓΌller, and Samek proposed it in 2015.

Each neuron splits the relevance it receives among the neurons of the layer below, according to how much each contributed to its value during the forward pass. Because the total relevance is kept the same at each layer (the conservation property), the pixel relevances obtained at the end sum to the output score. Positive relevance represents evidence that the class is present, and negative relevance represents evidence that it is absent.

The computation simply records the values of each layer during the forward pass and then traverses the network once in reverse from the output. Because it does not use gradients, it can also be applied to networks with non-differentiable activation functions.

It can be likened to injecting current at one end of an electrical circuit and measuring it at the other end (Montavon et al. 2018). At each node, the current flowing in equals the current flowing out (Kirchhoff's law), so overall the total current put in matches the total coming out. LRP relevance likewise flows to the input while being conserved at each neuron.

Background: splitting a prediction into a sum over pixels

An image classifier only answers "cat or not cat" and does not show which parts of the image it based its answer on. The LRP paper aimed for a pixel-wise decomposition that splits the prediction f(x)f(x) into a sum of per-pixel relevances RdR_d. VV is the number of pixels.

f(x)β‰ˆβˆ‘d=1VRd(1)f(x) \approx \sum_{d=1}^{V} R_d \qquad (1)

It then views the network as a stack of layers and requires the total relevance to be equal at every layer. This is the layer-wise conservation property. Rd(l)R^{(l)}_d is the relevance of the dd-th neuron in layer ll.

f(x)=β‹―=βˆ‘d∈l+1Rd(l+1)=βˆ‘d∈lRd(l)=β‹―=βˆ‘dRd(1)(2)f(x) = \cdots = \sum_{d \in l+1} R^{(l+1)}_d = \sum_{d \in l} R^{(l)}_d = \cdots = \sum_{d} R^{(1)}_d \qquad (2)

However, satisfying the conservation property alone does not guarantee a meaningful decomposition. As a counterexample, the paper gives a scheme that distributes f(x)f(x) in proportion to ∣adΟ•d(xd)∣|a_d \phi_d(x_d)| for each input. With this scheme, every pixel's relevance has the same sign as the prediction, and the information that "this pixel is evidence against the class" is lost. A rule is therefore needed that distributes relevance according to the direction in which each input actually contributed.

Computation steps

The explanation follows the section on neural networks in Bach et al. (2015), who proposed the method. The computation from a neuron xix_i in one layer to a neuron xjx_j in the next layer is written as follows, where wijw_{ij} is the weight, bjb_j the bias, and gg the activation function (Eqs. 50–52).

zij=xiwij,zj=βˆ‘izij+bj,xj=g(zj)z_{ij} = x_i w_{ij}, \qquad z_j = \sum_i z_{ij} + b_j, \qquad x_j = g(z_j)
  1. Run the input through the forward pass and record zijz_{ij} and zjz_j for each layer.
  2. Set the relevance of the output neuron to the score of the class to be explained (R(L)=f(x)R^{(L)} = f(x)). In the paper's MNIST experiments, the output of the last linear layer before the softmax is used.
  3. Split the relevance RjR_j of neuron jj in the upper layer into messages Ri←jR_{i \leftarrow j} to the neurons ii in the lower layer (using one of the rules in Eqs. 56, 58, or 60).
  4. Set the relevance of each neuron in the lower layer to the sum of the messages it receives (Eq. 62).
  5. Repeat steps 3 and 4 down to the input pixels. The resulting Rd(1)R^{(1)}_d are the per-pixel relevances.
Ri(l)=βˆ‘jRi←j(l,l+1)(62)R_i^{(l)} = \sum_j R_{i \leftarrow j}^{(l, l+1)} \qquad (62)

The basic rule splits RjR_j in proportion to each input's contribution zijz_{ij}.

Ri←j(l,l+1)=zijzjβ‹…Rj(l+1)(56)R_{i \leftarrow j}^{(l, l+1)} = \frac{z_{ij}}{z_j} \cdot R_j^{(l+1)} \qquad (56)

Under this rule, the messages sum to Rj(1βˆ’bj/zj)R_j (1 - b_j / z_j), so relevance corresponding to the bias is absorbed (if the bias is 0, relevance is conserved exactly). The right side of the top figure is an example on a small network with zero biases. The output 0.36 splits into +1.00+1.00 and βˆ’0.64-0.64 in the hidden layer, and at the pixels, +1.16+1.16 goes to the circle and βˆ’0.80-0.80 to the triangle. Because h2h_2 receives input from the circle pixels with a negative weight, the negative relevance of h2h_2 is distributed as positive to the circle pixels and negative to the triangle pixels. The sum is 0.36 at every layer.

Eq. 56 becomes too large when zjz_j is close to 0. The paper presents two rules that suppress this.

The Ξ΅ rule. Add a small positive number Ξ΅\varepsilon to the denominator, matched to the sign of zjz_j.

Ri←j(l,l+1)=zijzj+Ρ sign(zj)β‹…Rj(l+1)(58)R_{i \leftarrow j}^{(l, l+1)} = \frac{z_{ij}}{z_j + \varepsilon\, \mathrm{sign}(z_j)} \cdot R_j^{(l+1)} \qquad (58)

The Ξ±-Ξ² rule. Distribute the positive part zij+z^+_{ij} and the negative part zijβˆ’z^-_{ij} of zijz_{ij} separately, where zj+=βˆ‘izij++bj+z^+_j = \sum_i z^+_{ij} + b^+_j and zjβˆ’=βˆ‘izijβˆ’+bjβˆ’z^-_j = \sum_i z^-_{ij} + b^-_j.

Ri←j(l,l+1)=Rj(l+1)β‹…(Ξ±β‹…zij+zj++Ξ²β‹…zijβˆ’zjβˆ’),Ξ±+Ξ²=1(60)R_{i \leftarrow j}^{(l, l+1)} = R_j^{(l+1)} \cdot \left(\alpha \cdot \frac{z^+_{ij}}{z^+_j} + \beta \cdot \frac{z^-_{ij}}{z^-_j}\right), \qquad \alpha + \beta = 1 \qquad (60)

Papers differ in how they define Ξ±\alpha and Ξ²\beta in the Ξ±-Ξ² rule. The original paper (Eq. 60) sets Ξ±+Ξ²=1\alpha + \beta = 1, and Samek et al. (2017) use Ξ±=2\alpha = 2, Ξ²=βˆ’1\beta = -1 under this convention. The later tutorial by Montavon et al. (2018) puts a minus sign on the negative-part term, sets Ξ±βˆ’Ξ²=1\alpha - \beta = 1 with Ξ²β‰₯0\beta \geq 0, and calls the rule with Ξ±=2\alpha = 2, Ξ²=1\beta = 1 LRP-Ξ±2Ξ²1. These two are the same rule. When comparing with other sources, check which convention is used.

The paper also presents a method that approximates each layer with a Taylor expansion (Taylor-type decomposition), but unlike Taylor expansion, LRP does not need to search for another point in the input space (the root point of the expansion).

Choosing a rule

The choice of rule changes the appearance of the heatmap. The original paper and the later tutorial (Montavon et al. 2018) describe the rules as follows.

RuleHeatmap characteristicsExample of use
Eq. 56 (Ξ΅=0\varepsilon = 0)No relevance absorbed by Ξ΅, but unstable when zjz_j is close to 0MNIST experiments in the original paper
Ξ΅ rule (small Ξ΅\varepsilon)Finest detail, with much negative evidenceImageNet examples in the original paper
Ξ΅ rule (large Ξ΅\varepsilon)Coarser, with less negative evidence; part of the relevance is absorbedSame as above
LRP-Ξ±1Ξ²0 (distributes only the positive part)Only positive relevance; stableReported as stable on GoogLeNet
LRP-Ξ±2Ξ²1Includes negative relevance; sparserReported as good on CaffeNet

Montavon et al. (2018) recommend first trying rules based on deep Taylor decomposition (such as LRP-Ξ±1Ξ²0 in hidden layers and a rule using the range of pixel values in the input layer), and switching to LRP-Ξ±2Ξ²1 in hidden layers when negative relevance is needed or the heatmap is blurry. For text classification, the Ξ΅ rule has been used successfully. If none is satisfactory, choose a rule with the pixel-removal evaluation described below.

Experimental results

The experiments in the original paper mainly verify the method by inspecting heatmaps.

  • Handwritten digits (MNIST): when a network with 784 inputs, hidden layers of 400 and 400 units (tanh), and 10 outputs (test accuracy 98.25%) was explained with Eq. 56, positive relevance appeared, even when explaining a wrong class, on pixels that frequently appear in that class's training digits. In another network with three stacked hidden layers of 1296 units (accuracy 99.2%), the horizontal stroke in the middle of a digit 3 and the absence of a vertical line on its left were evidence for "3", and when a 4 was explained as "9", its open top was negative evidence.
  • Pixel-flipping experiment: flipping "non-digit pixels" with large positive relevance made the score of the correct class drop quickly. This shows that pixels outside the digit also serve as evidence for determining the class.
  • Pretrained ImageNet models: with a pretrained Caffe network, high relevance appeared on the comb and feathers for a rooster, and on the rim and handle for an espresso cup. In a cat example, relevance also appeared on a road surface resembling fur, showing that the classifier also uses cues outside the object.

Samek et al. (2017) replaced 9 Γ— 9 regions of an image with random values in order of decreasing relevance and compared LRP, gradients (sensitivity), and DeconvNet by how quickly the score dropped (AOPC). On all three datasets, SUN397, ILSVRC2012, and MIT Places (5040 images each), the score dropped fastest with LRP, meaning it captured the evidence best. The results of comparing heatmap complexity by PNG file size are as follows; LRP had the smallest files (the least noise).

DatasetGradient (sensitivity)DeconvNetLRP
SUN397183 KB166 KB154 KB
ILSVRC2012177 KB164 KB154 KB
MIT Places183 KB167 KB155 KB

Caveats in practice

LRP heatmaps change greatly depending on which rule is used, with which parameters, and in which layers. Increasing Ξ΅ reduces detail and negative relevance, and part of the relevance is absorbed, breaking the conservation property. When comparing different rules, check them with an evaluation that removes pixels and observes how the score drops (such as AOPC).

Keep the following points in mind as well.

  • Biases absorb relevance: the messages of Eq. 56 sum to Rj(1βˆ’bj/zj)R_j (1 - b_j / z_j), so the sum deviates from the output by the bias's share. The paper notes that this share can be redistributed to each neuron if needed.
  • For ReLU networks, it is the same as gradient Γ— input: according to the DeepLIFT paper, LRP rules without numerical-stability tricks are equivalent to a constant multiple of gradient Γ— input for ReLU networks. Therefore, like gradient Γ— input, LRP also suffers from the saturation problem.
  • It depends on the implementation: the Integrated Gradients paper points out that LRP does not satisfy the property "the same function gives the same contributions" (implementation invariance).
  • Each layer type needs its own rule: fully connected and convolutional layers can use Eqs. 56–60 as is. Strongly nonlinear layers, such as local normalization, require approximation by Taylor expansion.

Comparison with other attribution methods

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

MethodWhat it usesBaseline inputContributions sum to the outputNeeds gradientsAmount of computation
Gradient saliency mapGradient at the inputNot usedNoYes1 backward pass
LRPDistributes relevance in proportion to contributions zijz_{ij}Not used (0 can be regarded as the baseline)Yes (except for the shares of Ξ΅ and biases)No1 backward pass
DeepLIFTBackpropagates differences from the reference with per-layer rulesUsedYes (matches the output difference)No1 backward pass
Integrated GradientsIntegral of gradients from the baseline to the inputUsedYes (matches the output difference)Yes20 to 300 backward passes
SHAPShapley valuesBackground dataYes (matches the difference from the base value)Depends on the methodThousands of predictions (Kernel SHAP)

The SHAP paper regards LRP as equivalent to "DeepLIFT with the reference of every neuron set to 0" and includes LRP among the additive feature attribution methods.

Rough guidelines for choosing:

  • A heatmap that separates positive and negative evidence from a single backward pass: use LRP.
  • Contributions computed as differences from a chosen baseline input: use DeepLIFT or Integrated Gradients.
  • A quick, rough look at which parts of an image the model is looking at: use Grad-CAM.

PyTorch example

Show code
python
import torch
import torch.nn as nn

'''
Compute the LRP Ξ΅ rule (Eq. 58 of Bach et al. 2015) on a network of only Linear and ReLU layers.
R_{i←j} = z_ij / (z_j + Ξ΅ sign(z_j)) Β· R_j, R_i = Ξ£_j R_{i←j} (Eq. 62)
'''


def lrp_epsilon(layers, x, target, eps=1e-6):
  # x: [1, input dim]. layers is an nn.Sequential of nn.Linear and nn.ReLU
  layers.eval()
  # step 1: run the forward pass and record the input (x_i) to each Linear layer
  acts = []
  h = x
  with torch.no_grad():
    for layer in layers:
      if isinstance(layer, nn.Linear):
        acts.append(h)
      h = layer(h)
  # step 2: the output relevance is the score of the class to explain (before the softmax)
  R = torch.zeros_like(h)
  R[0, target] = h[0, target]
  # steps 3-5: traverse the Linear layers from the top (ReLU passes relevance through unchanged)
  linears = [l for l in layers if isinstance(l, nn.Linear)]
  for layer, a in zip(reversed(linears), reversed(acts)):
    z = a @ layer.weight.T + layer.bias                     # z_j (Eq. 51)
    z = z + eps * torch.where(z >= 0, torch.ones_like(z), -torch.ones_like(z))  # Ξ΅ rule (Eq. 58)
    s = R / z                                               # R_j / z_j
    R = a * (s @ layer.weight)                              # R_i = x_i Ξ£_j w_ij R_j / z_j (Eqs. 58, 62)
  return R                                                  # relevance per input dimension


torch.manual_seed(0)
layers = nn.Sequential(nn.Linear(784, 400), nn.ReLU(), nn.Linear(400, 400), nn.ReLU(), nn.Linear(400, 10))
x = torch.rand(1, 784)                  # example: an MNIST image flattened into a row
with torch.no_grad():
  target = layers(x).argmax(dim=1).item()
  score = layers(x)[0, target].item()
R = lrp_epsilon(layers, x, target)
# the sum of relevances deviates from the score by the shares of the biases and Ξ΅ (Eqs. 57, 59)
print(f'sum of relevances {R.sum().item():.4f}, score {score:.4f}')

FAQ

Q. How do LRP and gradient Γ— input differ?
A.

The basic rule without numerical stabilization (Eq. 56) is equivalent to a constant multiple of gradient Γ— input for ReLU networks (according to the DeepLIFT paper). Differences arise when the Ξ΅ rule or the Ξ±-Ξ² rule is used. These change how positive and negative contributions are handled, so they produce heatmaps different from gradient Γ— input. Also, because LRP does not use gradients, it can be defined even for non-differentiable activation functions.

Q. What value should Ξ΅ have?
A.

There is no fixed value. Samek et al. (2017) use Ξ΅=0.01\varepsilon = 0.01 and Ξ΅=100\varepsilon = 100. According to the original paper, a small value gives a fine heatmap with much negative evidence, and a large value gives a coarse heatmap with little negative evidence. Compare and choose with an evaluation that removes pixels and observes how the score drops.

Q. What does negative relevance mean?
A.

It means the pixel is evidence against the class being explained. In the MNIST example in the original paper, when a digit 4 was explained as 9, the open top of the 4 was shown as evidence against 9 (negative relevance), because a 9 should have a horizontal stroke at the top.

References

  1. S. Bach, A. Binder, G. Montavon, F. Klauschen, K.-R. MΓΌller, and W. Samek, "On Pixel-Wise Explanations for Non-Linear Classifier Decisions by Layer-Wise Relevance Propagation," PLoS ONE, vol. 10, no. 7, e0130140, 2015.
  2. W. Samek, A. Binder, G. Montavon, S. Bach, and K.-R. MΓΌller, "Evaluating the visualization of what a Deep Neural Network has learned," arXiv:1509.06321.
  3. G. Montavon, W. Samek, and K.-R. MΓΌller, "Methods for Interpreting and Understanding Deep Neural Networks," Digital Signal Processing, doi:10.1016/j.dsp.2017.10.011(arXiv:1706.07979).
  4. A. Shrikumar, P. Greenside, and A. Kundaje, "Learning Important Features Through Propagating Activation Differences," Proceedings of the 34th International Conference on Machine Learning (ICML), PMLR 70, pp. 3145–3153, 2017(arXiv:1704.02685).