Neural networks explainability with Keras
Explain a neural network as a transport problem: switching operators, relevance flows, entropic projection and Sinkhorn, with Keras exercises.
Learning goals: use the Filippov formalism (the companion course) to explain networks with switching nodes; compute relevance flows and prove their conservation; see LRP as an entropic projection; use Sinkhorn and region relevance; test explanation maps on a trained Keras network.
Context and objectives
Why explain a network with a transport problem?
Neural networks routinely beat humans on narrow tasks, yet their reasoning stays opaque, which raises problems of trust and accountability wherever they decide something that matters. Two families of attribution methods try to answer why a network produced an output. Gradient-based methods (Gradient×Input) tell how the output would respond to a small change of the input. Relevance propagation, of which Layer-wise Relevance Propagation (LRP) is the main example, tells how the output is shared among the inputs: the output score is sent backward through the layers, and what leaves a node equals what entered it (a conservation law). LRP is useful, but its rules were justified by local heuristics (conservation, deep Taylor expansions), not as the solution of a stated problem.
The article this course follows (O. Gibaru and E. Nyiri, Relevance Propagation as Entropic Optimal Transport on Filippov Neural Networks, arXiv:2611.05594) shows that relevance propagation is the solution of a variational problem: an entropic projection. Among all conservative relevance flows on the network’s active graph, LRP selects the one that is closest, in relative entropy, to a reference built from the forward pass, and the classical rules differ only by the choice of the reference. Taking the entropy edge by edge gives a new rule, Sinkhorn Relevance Propagation, an entropic optimal transport. Aggregated over a region of the input, the flow is a Schrödinger bridge that tells which hidden units carry the evidence of that region.
The second contribution is about architectures. Modern models use hard-routed Mixture-of-Experts blocks: a router picks one expert, and the output jumps when the choice changes. At the jump neither the gradient nor Clarke’s generalized gradient exists. The article represents networks as directed acyclic graphs of Filippov operators, which keep, at a switching point, the set of admissible values and derivatives. The Filippov part of the foundation is the course Filippov neural networks with Keras; here you rebuild the relevance part with small Keras and NumPy programs, from the smallest example to a trained network.
Objectives to carry out
- Compute LRP$_0$ and LRP$_{z^+}$ by a backward recursion, check conservation and the equality LRP$_0$ = Gradient×Input, and watch LRP$_0$ jump at a kink (Part 1).
- Recover the relevance flow as the minimizer of a relative entropy, with Keras optimizers, and compare references (Part 2).
- Implement Sinkhorn iterations, Sinkhorn Relevance Propagation and the relevance of a region (Part 3).
- Explain a trained ReLU network on handwritten digits and test the maps by deletion and by region (Part 4).
- Deliver a short report with numbers and a discussion of limits (Part 5).
Each part starts with a short course (definitions, statements, proofs when they are short) and proposes small exercises with a light Python starting code (TO DO lines). Each correction, folded just after, is commented line by line. Try the exercise before opening it.
How to work: environment
Install tensorflow==2.21.0 numpy matplotlib scikit-learn in an isolated environment (checked with Python 3.12 and TensorFlow CPU 2.21). No download is needed: the digits come with scikit-learn, and the running example is a network with 13 weights. Run the blocks in order in one notebook or session: the exercises reuse earlier functions. The reference numbers quoted in the corrections come from these programs.
import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersSEED = 0keras.utils.set_random_seed(SEED)np.set_printoptions(precision=4, suppress=True)# The running example of the article: inputs i1, i2, bias b1 -> hidden ReLU h1, h2 -> outputs o1, o2 (linear),# with a bias b2 on the outputs and a skip edge i1 -> o1. The bias nodes have the value +1.WEIGHTS = { ("i1", "h1"): 1.0, ("i2", "h1"): 2.0, ("b1", "h1"): 0.0, ("i1", "h2"): -1.0, ("i2", "h2"): 1.0, ("b1", "h2"): 1.0, ("h1", "o1"): 1.0, ("h2", "o1"): 2.0, ("b2", "o1"): 0.0, ("i1", "o1"): 1.0, ("h1", "o2"): -1.0, ("h2", "o2"): 2.0, ("b2", "o2"): -1.0,}INPUTS, HIDDEN, OUTPUTS = ["i1", "i2", "b1", "b2"], ["h1", "h2"], ["o1", "o2"]ORDER = ["i1", "i2", "b1", "b2", "h1", "h2", "o1", "o2"] # a topological order of the graph
The running example, provided
The graph of the article has two inputs, a bias on the hidden layer, two ReLU nodes, two linear outputs, a bias on the outputs and a skip edge $i_1\to o_1$; its construction and its Filippov analysis are the subject of the course Filippov neural networks with Keras. Here we only use it: the Keras model and the forward pass on the graph are given. Contributions are $z_{u,v}=w_{u,v}x_u$, the active graph keeps the nodes with a nonzero value and the edges of nonzero weight between them, and at $x=(-2,1)$ the hidden node $h_1$ is at a kink, hence inactive.
# Functional API: the skip edge i1 -> o1 and the direct inputs of the outputs are obtained by concatenating the hidden layer with the inputs.def build_network(): x = keras.Input(shape=(2,), name="inputs") # i1, i2 hidden = layers.Dense(2, activation="relu", name="hidden")(x) # two ReLU nodes h1, h2 with the weights of the article # Concatenation (h1, h2, i1, i2): the output layer then has four inputs, so a weight matrix of shape (4, 2). both = layers.Concatenate()([hidden, x]) # h1, h2, i1, i2 feed the outputs out = layers.Dense(2, name="outputs")(both) # two linear outputs o1, o2 (with the skip edge i1 -> o1) return keras.Model(x, out)model = build_network()# weights of the article: rows i1, i2 and columns h1, h2; bias b1 -> (h1, h2)# Keras kernels have shape (inputs, units): row = source node, column = target node. The bias vector is the weight of the bias node.model.get_layer("hidden").set_weights([np.array([[1.0, -1.0], [2.0, 1.0]]), np.array([0.0, 1.0])])# rows h1, h2, i1, i2 and columns o1, o2; bias b2 -> (o1, o2)model.get_layer("outputs").set_weights([np.array([[1.0, -1.0], [2.0, 2.0], [1.0, 0.0], [0.0, 0.0]]), np.array([0.0, -1.0])])for x in [(-2.0, 1.0), (1.0, 1.0)]: print(x, "->", model(np.array([x], dtype="float32")).numpy().ravel())print("expected: (-2, 1) -> (6, 7) and (1, 1) -> (6, -2)")
# The biases b1 and b2 are nodes of value 1, so that a bias is a weight like the others (a DAG with bias nodes).def forward(x): """Node values of the running example: dictionary node -> value (the biases have the value 1).""" v = {"i1": x[0], "i2": x[1], "b1": 1.0, "b2": 1.0} for h in HIDDEN: total = sum(WEIGHTS[(u, h)] * v[u] for u in ["i1", "i2", "b1"]) # sum of the incoming contributions # ReLU: the value of a hidden node is max(sum of incoming contributions, 0). v[h] = max(total, 0.0) # ReLU for o in OUTPUTS: v[o] = sum(w * v[u] for (u, t), w in WEIGHTS.items() if t == o) # linear output: sum of the contributions return v# The contribution z_{u,v} = w_{u,v} x_u is what node u sends to node v along the edge (u, v).def contributions(x): v = forward(x) return {(u, t): w * v[u] for (u, t), w in WEIGHTS.items()} # z_{u,v} = w_{u,v} x_udef active_graph(x): v = forward(x) # A node is active when its value is nonzero: a ReLU at 0 (a kink) is inactive, and so are the edges leaving it. nodes = [n for n in ORDER if v[n] != 0.0] # active nodes: nonzero value edges = [(u, t) for (u, t), w in WEIGHTS.items() if w != 0.0 and u in nodes and t in nodes] # edges with a nonzero weight between active nodes return nodes, edgesfor x in [(-2.0, 1.0), (1.0, 1.0)]: nodes, edges = active_graph(x) print("x =", x, "values", {n: v for n, v in forward(x).items() if n in HIDDEN + OUTPUTS}) print(" inactive nodes:", [n for n in ORDER if n not in nodes], "| active edges:", len(edges), "of", len(WEIGHTS))
Part 1 · Relevance flows and the classical rules
Relevance flows and conservation
Fix an input $x$ and an active output $o$. A relevance flow is a number $\pi_{u,v}$ on each active edge. It is admissible if the relevance entering a hidden node leaves it, $\operatorname{div}\pi(v)=\sum_{u\to v}\pi_{u,v}-\sum_{v\to w}\pi_{v,w}=0$ (a Kirchhoff law), if the flow entering $o$ is the explained value $x_o$ and if nothing enters the other outputs. The relevance of a node is the flow leaving it, $\mu_u=\sum_{u\to w}\pi_{u,w}$, and $\mu_o=x_o$.
For every admissible flow, $\displaystyle\sum_{u\in\mathcal I(x)}\mu_u=x_o$: the relevance of the inputs, bias nodes included, adds up to the explained output.
Proof
Add the flows of all active edges in two ways. Grouped by tail, the sum is $\sum_{u\in\mathcal I}\mu_u+\sum_{v\in\mathcal H}\text{out}(v)$ (the outputs have no outgoing edge). Grouped by head, it is $\sum_{v\in\mathcal H}\text{in}(v)+\sum_{o'\in\mathcal O}\text{in}(o')$. At a hidden node $\text{in}(v)=\text{out}(v)$, and $\text{in}(o)=x_o$, $\text{in}(o')=0$ otherwise. Equating the two expressions gives $\sum_{u\in\mathcal I}\mu_u=x_o$. $\square$
Many flows are admissible. A rule selects one by sending, at each node $v$, the relevance $\mu_v$ to its predecessors in proportion to a reference $\rho_{u,v}$ read off the forward pass:
\[K_{u,v}=\frac{\rho_{u,v}}{\tilde\rho_v},\quad \tilde\rho_v=\sum_{u\to v}\rho_{u,v},\qquad \pi_{u,v}=K_{u,v}\,\mu_v,\qquad \mu_u=\sum_{u\to v}K_{u,v}\,\mu_v,\quad\mu_o=x_o.\]The two basic rules are LRP$_0$ ($\rho=z$, the signed contributions) and LRP$_{z^+}$ ($\rho=z^+$, their positive part). Part 2 proves that this recursion is the solution of an optimization problem.
Exercise 1.1 · the backward recursion
- Write the recursion on the active graph for a given reference: from the output back to the inputs, with $\pi_{u,v}=\rho_{u,v}\mu_v/\tilde\rho_v$.
- Apply it with $\rho=z$ and $\rho=z^+$ at $x=(-2,1)$ and $x=(1,1)$, for the output $o_1$.
- Read the relevance of $(i_1,i_2,b_1,b_2)$ and compare with the figure of the article: $(2,3,1)$ for LRP$_{z^+}$ at $x=(1,1)$.
def lrp(x, output, reference): """Backward recursion mu_u = sum_v K_{u,v} mu_v, with K = rho / (sum of rho entering v). Returns (flows, relevances).""" v = forward(x) z = contributions(x) nodes, edges = active_graph(x) rho = {e: reference(e, z, edges) for e in edges} # reference on the active edges mu = {n: 0.0 for n in nodes} mu[output] = v[output] # all the relevance starts at the explained output flows = {} for t in reversed([n for n in ORDER if n in nodes]): # from the output back to the inputs incoming = [(u, s) for (u, s) in edges if s == t] if t in OUTPUTS and t != output: continue # the other outputs receive no relevance den = ... # TO DO: the sum of the reference entering the node for (u, s) in incoming: ... # TO DO: pi_{u,v} = K_{u,v} mu_v mu[u] += flows[(u, s)] return flows, mulrp0 = lambda e, z, edges: z[e] # LRP_0: the reference is the signed contribution zlrp_zplus = lambda e, z, edges: max(z[e], 0.0) # LRP_z+: the positive part of zfor x in [(-2.0, 1.0), (1.0, 1.0)]: for name, ref in [("LRP_0", lrp0), ("LRP_z+", lrp_zplus)]: flows, mu = lrp(x, "o1", ref) print(f"x = {x}, {name:7s}: relevance of (i1, i2, b1, b2) =", [round(mu.get(n, 0.0), 4) for n in ["i1", "i2", "b1", "b2"]])
Show the correction
# The recursion of the theorem: mu_u = sum over the edges (u, v) of K_{u,v} mu_v, where K_{u,v} = rho_{u,v} / sum of rho entering v.def lrp(x, output, reference): """Backward recursion mu_u = sum_v K_{u,v} mu_v, with K = rho / (sum of rho entering v). Returns (flows, relevances).""" v = forward(x) z = contributions(x) nodes, edges = active_graph(x) rho = {e: reference(e, z, edges) for e in edges} # reference on the active edges mu = {n: 0.0 for n in nodes} # The relevance to be distributed is the output value itself. mu[output] = v[output] # all the relevance starts at the explained output flows = {} # Reverse topological order: a node is processed after all the nodes it feeds, so its relevance is complete. for t in reversed([n for n in ORDER if n in nodes]): # from the output back to the inputs incoming = [(u, s) for (u, s) in edges if s == t] if t in OUTPUTS and t != output: continue # the other outputs receive no relevance # If the denominator is 0 the node receives nothing: the kernel is defined as 0 there (see the theorem). den = sum(rho[e] for e in incoming) # the sum of the reference entering the node for (u, s) in incoming: flows[(u, s)] = rho[(u, s)] / den * mu[t] if den != 0 else 0.0 # pi_{u,v} = K_{u,v} mu_v mu[u] += flows[(u, s)] return flows, mu# Two references of the article: the signed contributions (LRP_0) and their positive part (LRP_z+).lrp0 = lambda e, z, edges: z[e] # LRP_0: the reference is the signed contribution zlrp_zplus = lambda e, z, edges: max(z[e], 0.0) # LRP_z+: the positive part of zfor x in [(-2.0, 1.0), (1.0, 1.0)]: for name, ref in [("LRP_0", lrp0), ("LRP_z+", lrp_zplus)]: flows, mu = lrp(x, "o1", ref) print(f"x = {x}, {name:7s}: relevance of (i1, i2, b1, b2) =", [round(mu.get(n, 0.0), 4) for n in ["i1", "i2", "b1", "b2"]])
At $x=(1,1)$, LRP$_{z^+}$ gives $(2,3,1,0)$ and LRP$_0$ gives $(0,4,2,0)$. At $x=(-2,1)$, LRP$_0$ gives $(2,2,2,0)$ and LRP$_{z^+}$ gives $(3,1.5,1.5,0)$. Both sum to $x_{o_1}=6$ (the bias $b_2$ has no active edge towards $o_1$). Figure: the flows of LRP$_{z^+}$ at $x=(1,1)$.
Exercise 1.2 · check the Kirchhoff law and conservation
- Write the divergence of a flow at a node (inflow minus outflow).
- For LRP$_0$ and LRP$_{z^+}$ at $x=(1,1)$, check that it vanishes at the hidden nodes.
- Check that the relevance of the inputs adds up to the output $6$.
def divergence(flows, node): """inflow - outflow of a node: sum of the flows entering it minus the sum of the flows leaving it.""" inflow = ... # TO DO: flows entering the node outflow = ... # TO DO: flows leaving the node return inflow - outflowx = (1.0, 1.0)for name, ref in [("LRP_0", lrp0), ("LRP_z+", lrp_zplus)]: flows, mu = lrp(x, "o1", ref) div = {h: divergence(flows, h) for h in HIDDEN} # must vanish at every hidden node total = ... # TO DO: the total relevance of the inputs (biases included) print(f"{name:7s}: divergence at the hidden nodes {div}, total input relevance {total:.4f}, output value {forward(x)['o1']}")
Show the correction
# The divergence of a flow at a node is inflow minus outflow: Kirchhoff current law, zero at every hidden node for an admissible flow.def divergence(flows, node): """inflow - outflow of a node: sum of the flows entering it minus the sum of the flows leaving it.""" inflow = sum(f for (u, t), f in flows.items() if t == node) # flows entering the node outflow = sum(f for (u, t), f in flows.items() if u == node) # flows leaving the node return inflow - outflowx = (1.0, 1.0)for name, ref in [("LRP_0", lrp0), ("LRP_z+", lrp_zplus)]: flows, mu = lrp(x, "o1", ref) div = {h: divergence(flows, h) for h in HIDDEN} # must vanish at every hidden node # Conservation (Proposition): the relevance of the inputs, biases included, adds up to the output value. total = sum(mu[n] for n in ["i1", "i2", "b1", "b2"]) # the total relevance of the inputs (biases included) print(f"{name:7s}: divergence at the hidden nodes {div}, total input relevance {total:.4f}, output value {forward(x)['o1']}")
The divergences are zero and the total input relevance is $6$ for both rules, as the proposition predicts. Conservation is not an assumption of the method: it holds for every admissible flow, whatever the reference.
LRP$_0$ is Gradient×Input, and it can jump at a kink
On a network of ReLU and max-pooling nodes (bias nodes included in the graph), at an input away from every switching point, the relevance of an input node for the rule LRP$_0$ equals Gradient×Input: $\mu_i=x_i\,\dfrac{\partial x_o}{\partial x_i}$. At a switching point it depends on the selection $\kappa$, so that the LRP$_0$ relevance is a set, the convex hull over $\kappa$; the relevance can jump across the kink, while LRP$_{z^+}$ stays continuous in the situation of the example below.
Proof
Away from a switching point the active graph is fixed: an active ReLU node $v$ has the value $x_v=\sum_{u\to v}w_{u,v}x_u$ (bias nodes included, with the value $1$), an inactive one sends nothing, and a max-pooling node transmits its winner. Let $g_v=\partial x_o/\partial x_v$. By the chain rule, $g_o=1$ and $g_u=\sum_{u\to v}w_{u,v}\,g_v$ over the active edges. For LRP$_0$ the reference is $\rho_{u,v}=z_{u,v}=w_{u,v}x_u$, whose sum entering $v$ is $x_v$, so $K_{u,v}=w_{u,v}x_u/x_v$ (for an active node $x_v\neq0$). We prove $\mu_v=x_v\,g_v$ by going backward. At the output, $\mu_o=x_o=x_o\,g_o$. If it holds for the successors of $u$, then
\[\mu_u=\sum_{u\to v}K_{u,v}\,\mu_v=\sum_{u\to v}\frac{w_{u,v}x_u}{x_v}\,x_vg_v=x_u\sum_{u\to v}w_{u,v}g_v=x_u\,g_u.\]For the inputs this is $\mu_i=x_i\,\partial x_o/\partial x_i$. $\square$ At a switching point, $g$ depends on the selection $\kappa$ of the branch, hence the set of relevances and the possible jump.
This is Corollary 3.5 of the article, which also treats the change of winner of max-pooling nodes in detail. The next exercise checks the statement numerically on the running example and on a trained network.
Exercise 1.3 · Gradient×Input and the jump
- Compute Gradient×Input for the Keras model of the running example (provided code) at $x=(1,1)$ and compare it with the LRP$_0$ relevance of $(i_1,i_2)$.
- Along $x=(-2,1+\delta)$, compute the relevance of $i_2$ under LRP$_0$ and LRP$_{z^+}$ for $\delta=\mp0.001$, $\mp0.05$, $\mp0.2$.
- Describe what happens at $\delta=0$.
def gradient_times_input(x, output): xt = tf.Variable(np.array(x, dtype="float32")[None]) with tf.GradientTape() as tape: y = model(xt)[0, output] return ... # TO DO: gradient times input, for the two inputsx = (1.0, 1.0)_, mu0 = lrp(x, "o1", lrp0)print("LRP_0 (i1, i2):", [round(mu0[n], 4) for n in ["i1", "i2"]], "| Gradient x Input:", np.round(gradient_times_input(x, 0), 4))print("Along x = (-2, 1 + delta): relevance of i2 under LRP_0 and LRP_z+")for delta in [-0.2, -0.05, -0.001, 0.001, 0.05, 0.2]: xd = (-2.0, 1.0 + delta) r0 = lrp(xd, "o1", lrp0)[1]["i2"] rz = lrp(xd, "o1", lrp_zplus)[1]["i2"] print(f" delta = {delta:+.3f}: LRP_0 {r0:7.3f} LRP_z+ {rz:7.3f}")
Show the correction
# tf.GradientTape differentiates the logit with respect to the input.def gradient_times_input(x, output): xt = tf.Variable(np.array(x, dtype="float32")[None]) with tf.GradientTape() as tape: y = model(xt)[0, output] return (tape.gradient(y, xt).numpy()[0] * np.array(x)).tolist() # gradient times input, for the two inputsx = (1.0, 1.0)_, mu0 = lrp(x, "o1", lrp0)print("LRP_0 (i1, i2):", [round(mu0[n], 4) for n in ["i1", "i2"]], "| Gradient x Input:", np.round(gradient_times_input(x, 0), 4))# Near the kink the two selections give different gradients, hence different LRP_0: the relevance jumps. LRP_z+ stays continuous here.print("Along x = (-2, 1 + delta): relevance of i2 under LRP_0 and LRP_z+")for delta in [-0.2, -0.05, -0.001, 0.001, 0.05, 0.2]: xd = (-2.0, 1.0 + delta) r0 = lrp(xd, "o1", lrp0)[1]["i2"] rz = lrp(xd, "o1", lrp_zplus)[1]["i2"] print(f" delta = {delta:+.3f}: LRP_0 {r0:7.3f} LRP_z+ {rz:7.3f}")
At $x=(1,1)$ the two maps are both $(0,4)$. Across the kink the relevance of $i_2$ under LRP$_0$ jumps from $1.998$ to $4.004$ (the two selections of $h_1$ give $2$ and $4$), while under LRP$_{z^+}$ it goes from $1.498$ to $1.503$, continuously. This is the behaviour described in the article: a rule built on the signed contributions follows the selection, a rule built on the positive contributions does not here.
Part 2 · Relevance as an entropic projection
The entropic projection
The recursion of Part 1 looks like a convention. The main result of the article is that it is not: it is the solution of an optimization problem. For a flow $\pi\ge0$ and a reference kernel $K$ write $n_v=\sum_{u\to v}\pi_{u,v}$ for the inflow of $v$. The conditional relative entropy of $\pi$ with respect to $K$ is
\[\mathcal H(\pi\,\|\,K)=\sum_{v}n_v\,\mathrm{KL}\Big(\frac{\pi_{\cdot,v}}{n_v}\,\Big\|\,K_{\cdot,v}\Big),\qquad \mathrm{KL}(p\|q)=\sum_ip_i\log\frac{p_i}{q_i}.\]At each node it compares the way the flow splits the incoming relevance among the predecessors, with the way the reference splits it. Equivalently, it is the entropy between two Markov chains on the backward paths of the network.
Let $x_o>0$ and let $\rho\ge0$ be a reference on the active graph with $\tilde\rho_v>0$ at every hidden node and at $o$, and $K=\rho/\tilde\rho$. Among the admissible flows $\pi\ge0$, the problem $\min\mathcal H(\pi\,\|\,K)$ has a unique minimizer, its minimal value is $0$, and it is
\[\pi^{*}_{u,v}=K_{u,v}\,\mu_v,\qquad \mu_o=x_o,\quad\mu_u=\sum_{u\to v}K_{u,v}\mu_v.\]Proof
Each term of $\mathcal H$ is a KL divergence, hence $\ge0$ (Gibbs inequality), with equality if and only if the split $\pi_{\cdot,v}/n_v$ equals $K_{\cdot,v}$. So $\mathcal H\ge0$, and $\mathcal H=0$ exactly when $\pi_{u,v}=K_{u,v}\,n_v$ at every node. For an admissible flow the inflow of a hidden node equals its relevance (Kirchhoff), $n_v=\mu_v$, and $n_o=x_o$. The condition $\pi_{u,v}=K_{u,v}\mu_v$ with $\mu_u=\sum_{u\to v}\pi_{u,v}$ is then the backward recursion, which defines $\mu$ and $\pi$ uniquely, from the output to the inputs. The resulting flow is admissible, since by construction the flow entering a node is $\mu_v$ and the flow leaving it is $\mu_v$. Hence it attains the minimum $0$, and any other minimizer must have $\mathcal H=0$, thus coincides with it. $\square$
The article proves the same statement for signed references, with a sign-coherence condition, and obtains the classical rules by choosing the reference:
- LRP$_0$: $\rho=z$ (signed);
- LRP$_{z^+}$: $\rho=z^+$;
- LRP$_{\alpha,\beta}$, $\alpha+\beta=1$: $\rho_{u,v}=\alpha\,z^+_{u,v}/\tilde z^+_v+\beta\,z^-_{u,v}/\tilde z^-_v$ (the positive and negative channels weighted by $\alpha,\beta$);
- LRPN$_{\alpha,\beta}$: the same with weights $\alpha_v,\beta_v$ that may vary from node to node, for instance with the activity of the node, in the spirit of Hebb’s principle.
The rule is therefore the choice of a reference; conservation is a constraint of the problem, not a heuristic.
Exercise 2.1 · minimize the entropy at one node
- A node has three predecessors, a reference kernel $K=(3,2,1)/6$ and a relevance $\mu_v=6$ to distribute. Parametrize the flow as $\pi=\mu_v\,\mathrm{softmax}(\theta)$.
- Write the conditional entropy $n\,\mathrm{KL}(\pi/n\,\|\,K)$ and minimize it with Adam over $\theta$.
- Compare the minimizer with $K\mu_v$.
# One node v: three predecessors, reference kernel K and relevance mu_v to distributeK = tf.constant([3.0, 2.0, 1.0]) / 6.0 # the transition law read off the forward passmu_v = 6.0theta = tf.Variable(tf.zeros(3)) # free logits: the flow is pi = mu_v softmax(theta), so sum(pi) = mu_vopt = keras.optimizers.Adam(0.1)def conditional_entropy(pi, K): n = tf.reduce_sum(pi) return ... # TO DO: n_v KL(pi / n_v || K)for step in range(600): with tf.GradientTape() as tape: pi = mu_v * tf.nn.softmax(theta) loss = conditional_entropy(pi, K) ... # TO DO: one Adam step on the logitsprint("minimizer found by Adam:", pi.numpy(), "| K mu_v =", (K * mu_v).numpy(), "| minimal value:", float(loss))
Show the correction
# One node v: three predecessors, reference kernel K and relevance mu_v to distributeK = tf.constant([3.0, 2.0, 1.0]) / 6.0 # the transition law read off the forward passmu_v = 6.0# The flow is parametrized through a softmax so that the constraint sum(pi) = mu_v holds by construction.theta = tf.Variable(tf.zeros(3)) # free logits: the flow is pi = mu_v softmax(theta), so sum(pi) = mu_vopt = keras.optimizers.Adam(0.1)# n_v KL(pi / n_v || K): the weighted relative entropy between the split of the flow and the reference kernel at node v.def conditional_entropy(pi, K): n = tf.reduce_sum(pi) return n * tf.reduce_sum((pi / n) * tf.math.log((pi / n) / K)) # n_v KL(pi / n_v || K)for step in range(600): with tf.GradientTape() as tape: pi = mu_v * tf.nn.softmax(theta) loss = conditional_entropy(pi, K) # Adam updates the logits; the loss decreases to 0, reached only at pi = K mu_v. opt.apply_gradients([(tape.gradient(loss, theta), theta)]) # one Adam step on the logitsprint("minimizer found by Adam:", pi.numpy(), "| K mu_v =", (K * mu_v).numpy(), "| minimal value:", float(loss))
Adam drives the logits to the point where the softmax equals $K$: the flow is $(3,2,1)=K\mu_v$ and the entropy is $0$ (it cannot be lower, by Gibbs). The softmax parametrization encodes the constraint $\sum\pi=\mu_v$.
Exercise 2.2 · the whole network
- At $x=(1,1)$ for $o_1$ and $\rho=z^+$, list the positive edges entering $o_1$, $h_1$, $h_2$, and the kernel $K$ of each node.
- Give each node a free split (softmax of logits), build the flow by the backward recursion and sum the conditional entropies of the nodes.
- Minimize the total entropy with Adam and compare the input relevances with LRP$_{z^+}$, $(2,3,1)$.
x = (1.0, 1.0)v = forward(x); z = contributions(x)nodes, edges = active_graph(x)pos = [e for e in edges if z[e] > 0] # the support of the reference rho = z^+preds = {n: [u for (u, t) in pos if t == n] for n in ["o1", "h1", "h2"]}print("positive edges entering each node:", preds)Kref = {n: np.array([z[(u, n)] for u in preds[n]]) / sum(z[(u, n)] for u in preds[n]) for n in preds} # kernel of LRP_z+logits = {n: tf.Variable(tf.zeros(len(preds[n]))) for n in preds} # one free split per nodeopt = keras.optimizers.Adam(0.05)def flows_and_entropy(): mu = {"o1": v["o1"], "h1": 0.0, "h2": 0.0, "i1": 0.0, "i2": 0.0, "b1": 0.0} total, flows = 0.0, {} for n in ["o1", "h1", "h2"]: # from the output back to the inputs split = tf.nn.softmax(logits[n]) pi = ... # TO DO: the flow entering n is the relevance of n split among its predecessors total += mu[n] * tf.reduce_sum(split * tf.math.log(split / Kref[n])) # n_v KL(split || K_v) for u, f in zip(preds[n], pi): flows[(u, n)] = f mu[u] = mu[u] + f # relevance of u = sum of the flows leaving u return flows, mu, totalfor step in range(800): with tf.GradientTape() as tape: flows, mu, loss = flows_and_entropy() grads = tape.gradient(loss, list(logits.values())) ... # TO DO: gradient step on all the splits at onceprint("minimal conditional entropy:", float(loss))print("input relevances found by Adam (i1, i2, b1):", [round(float(mu[n]), 3) for n in ["i1", "i2", "b1"]], "| LRP_z+: (2, 3, 1)")
Show the correction
x = (1.0, 1.0)v = forward(x); z = contributions(x)nodes, edges = active_graph(x)# The support of the reference rho = z^+: the edges with a positive contribution.pos = [e for e in edges if z[e] > 0] # the support of the reference rho = z^+preds = {n: [u for (u, t) in pos if t == n] for n in ["o1", "h1", "h2"]}print("positive edges entering each node:", preds)Kref = {n: np.array([z[(u, n)] for u in preds[n]]) / sum(z[(u, n)] for u in preds[n]) for n in preds} # kernel of LRP_z+# One free simplex split per node: the constraint of conservation is then automatic, because the flow entering a node is its relevance.logits = {n: tf.Variable(tf.zeros(len(preds[n]))) for n in preds} # one free split per nodeopt = keras.optimizers.Adam(0.05)def flows_and_entropy(): mu = {"o1": v["o1"], "h1": 0.0, "h2": 0.0, "i1": 0.0, "i2": 0.0, "b1": 0.0} total, flows = 0.0, {} for n in ["o1", "h1", "h2"]: # from the output back to the inputs split = tf.nn.softmax(logits[n]) # mu[n] is already complete when node n is processed (the nodes are visited from the output to the inputs). pi = mu[n] * split # the flow entering n is the relevance of n split among its predecessors total += mu[n] * tf.reduce_sum(split * tf.math.log(split / Kref[n])) # n_v KL(split || K_v) for u, f in zip(preds[n], pi): flows[(u, n)] = f mu[u] = mu[u] + f # relevance of u = sum of the flows leaving u return flows, mu, totalfor step in range(800): with tf.GradientTape() as tape: flows, mu, loss = flows_and_entropy() grads = tape.gradient(loss, list(logits.values())) # Joint minimization of the total conditional entropy over all the splits: the minimum is 0, reached by the LRP_z+ flow. opt.apply_gradients(zip(grads, list(logits.values()))) # gradient step on all the splits at onceprint("minimal conditional entropy:", float(loss))print("input relevances found by Adam (i1, i2, b1):", [round(float(mu[n]), 3) for n in ["i1", "i2", "b1"]], "| LRP_z+: (2, 3, 1)")
The minimum is $0$ and the input relevances found by gradient descent are $(2,3,1)$, the numbers of LRP$_{z^+}$. The relevance is thus learned as the solution of an optimization problem, instead of being propagated by a formula: the two agree, which is the content of the theorem.
Exercise 2.3 · another reference: LRP$_{\alpha,\beta}$
- Write the reference $\alpha z^+/\tilde z^++\beta z^-/\tilde z^-$ at the nodes where both channels are present, and the single channel otherwise.
- Apply LRP$_0$, LRP$_{z^+}$ and LRP$_{2,-1}$ to $o_1$ at $x=(-1,1)$ and $x=(-3,1)$.
- Check that all the rules conserve the output, and compare the maps.
def lrp_alpha_beta(alpha, beta): """Reference alpha z^+ / z~^+ + beta z^- / z~^- at nodes with both signs; the single channel otherwise.""" def reference(e, z, edges): u, t = e into = [z[(a, b)] for (a, b) in edges if b == t] zp, zm = ... # TO DO: positive and negative parts of the contributions entering the node if zp > 0 and zm > 0: return alpha * max(z[e], 0) / zp + beta * max(-z[e], 0) / zm # both channels: weighted combination return max(z[e], 0) / zp if zm == 0 else max(-z[e], 0) / zm # one channel: that channel, normalized return referencefor x in [(-1.0, 1.0), (-3.0, 1.0)]: print("x =", x, "output o1 =", forward(x)["o1"]) for name, ref in [("LRP_0", lrp0), ("LRP_z+", lrp_zplus), ("LRP_{2,-1}", lrp_alpha_beta(2.0, -1.0))]: flows, mu = lrp(x, "o1", ref) r = [mu.get(n, 0.0) for n in ["i1", "i2", "b1"]] print(f" {name:11s}: (i1, i2, b1) = {np.round(r, 3).tolist()}, sum = {sum(r):.3f}")
Show the correction
# A signed reference with weights alpha + beta = 1 on the positive and negative channels of each node.def lrp_alpha_beta(alpha, beta): """Reference alpha z^+ / z~^+ + beta z^- / z~^- at nodes with both signs; the single channel otherwise.""" def reference(e, z, edges): u, t = e into = [z[(a, b)] for (a, b) in edges if b == t] # Z+ and Z- are the sums of the positive and of the negative contributions entering the node. zp, zm = sum(max(c, 0) for c in into), sum(max(-c, 0) for c in into) # positive and negative parts of the contributions entering the node if zp > 0 and zm > 0: return alpha * max(z[e], 0) / zp + beta * max(-z[e], 0) / zm # both channels: weighted combination return max(z[e], 0) / zp if zm == 0 else max(-z[e], 0) / zm # one channel: that channel, normalized return referencefor x in [(-1.0, 1.0), (-3.0, 1.0)]: print("x =", x, "output o1 =", forward(x)["o1"]) for name, ref in [("LRP_0", lrp0), ("LRP_z+", lrp_zplus), ("LRP_{2,-1}", lrp_alpha_beta(2.0, -1.0))]: flows, mu = lrp(x, "o1", ref) r = [mu.get(n, 0.0) for n in ["i1", "i2", "b1"]] print(f" {name:11s}: (i1, i2, b1) = {np.round(r, 3).tolist()}, sum = {sum(r):.3f}")
At $x=(-3,1)$ the maps are $(3,2,2)$ for LRP$_0$, $(4.2,1.4,1.4)$ for LRP$_{z^+}$ and $(1.4,2.8,2.8)$ for LRP$_{2,-1}$: three different explanations of the same output $7$. At $x=(-1,1)$ LRP$_{2,-1}$ even gives a negative relevance $-4.29$ to $i_1$ (an input that works against the output). All of them sum to the output: conservation does not tell which rule is faithful, it is the choice of the reference that does.
Part 3 · Sinkhorn propagation and relevance by region
Entropic optimal transport and Sinkhorn
In entropic optimal transport one looks for a plan $P_{ij}\ge0$ with prescribed row sums $r$ and column sums $c$ that is closest to a Gibbs kernel $K_{ij}=e^{-C_{ij}/\varepsilon}$ in relative entropy (a transport cost $C$ plus an entropy). The solution has a two-ended form $P_{ij}=a_i\,K_{ij}\,b_j$, and the factors $a,b$ are found by Sinkhorn iterations: rescale the rows to match $r$, then the columns to match $c$, and repeat.
Relevance propagation of Part 2 compares the transition laws node by node. If we compare instead the flow itself with the reference edge by edge, we obtain another rule, Sinkhorn Relevance Propagation (SRP):
Let $\rho\ge0$ be supported on edges that lie on a path from an input to $o$, and $y>0$. The problem $\min\mathrm{KL}(\pi\|\rho)$, with $\mathrm{KL}(\pi\|\rho)=\sum_e\pi_e\log\frac{\pi_e}{\rho_e}-\pi_e+\rho_e$, over the admissible flows of value $y$ at the output, has a unique solution, of the form
\[\pi^{S}_{u,v}=\rho_{u,v}\,\frac{\varphi_v}{\varphi_u},\qquad \varphi_i=1\ \text{at the inputs},\]where the potentials $\varphi_v>0$ solve $\varphi_v^2\sum_u\rho_{u,v}/\varphi_u=\sum_w\rho_{v,w}\varphi_w$ at the hidden nodes and $\varphi_o\sum_u\rho_{u,o}/\varphi_u=y$ at the output. Updating the potentials one node at a time converges to them (Sinkhorn sweeps).
Proof
The functional is strictly convex on the positive flows and the constraints are linear, so the minimizer is unique. Introduce a multiplier $\lambda_v$ for the conservation constraint at each node. Stationarity at an edge $(u,v)$ gives $\log(\pi_{u,v}/\rho_{u,v})=\lambda_v-\lambda_u$, that is $\pi_{u,v}=\rho_{u,v}\,\varphi_v/\varphi_u$ with $\varphi=e^{\lambda}$ (the inputs, which are free, have $\lambda=0$ at the optimum). Writing the conservation at a hidden node, $\sum_u\rho_{u,v}\varphi_v/\varphi_u=\sum_w\rho_{v,w}\varphi_w/\varphi_v$, gives the fixed-point equation; at the output the flow entering $o$ is $y$. Each update maximizes the dual function in one coordinate, which gives the convergence of the sweeps. $\square$
One sweep costs as much as a pass of LRP. If $\rho$ is already admissible, then $\pi^S=\rho$ and all the potentials equal $1$ (it is the minimizer with zero value). At $x=(1,1)$ the reference $z^+$ has this property for $o_1$; at $x=(0,1)$ it does not, and SRP differs from LRP$_{z^+}$.
Exercise 3.1 · Sinkhorn iterations
- Build a $3\times3$ Gibbs kernel for the cost $|i-j|$ with $\varepsilon=0.5$, and marginals $r=(0.5,0.3,0.2)$, $c=(0.4,0.4,0.2)$.
- Alternate the two rescalings 200 times.
- Check the marginals of the plan $a_iK_{ij}b_j$ and print its transport cost.
rng = np.random.default_rng(1)r = np.array([0.5, 0.3, 0.2]) # first marginalc = np.array([0.4, 0.4, 0.2]) # second marginalC = np.abs(np.arange(3)[:, None] - np.arange(3)[None, :]).astype(float) # cost |i - j|eps = 0.5Kmat = ... # TO DO: the Gibbs kernel exp(-C / eps), the "reference"a, b = np.ones(3), np.ones(3)for it in range(200): a = ... # TO DO: rescale the rows so that the first marginal is r b = ... # TO DO: rescale the columns so that the second marginal is cP = a[:, None] * Kmat * b[None, :] # the plan: one factor per row and one per columnprint("plan:\n", P)print("row sums:", P.sum(axis=1), "| column sums:", P.sum(axis=0))print("entropic cost <C, P> =", (C * P).sum())
Show the correction
rng = np.random.default_rng(1)r = np.array([0.5, 0.3, 0.2]) # first marginalc = np.array([0.4, 0.4, 0.2]) # second marginalC = np.abs(np.arange(3)[:, None] - np.arange(3)[None, :]).astype(float) # cost |i - j|eps = 0.5# K = exp(-C / eps): the reference measure of entropic optimal transport. The smaller eps, the closer to the unregularized plan.Kmat = np.exp(-C / eps) # the Gibbs kernel exp(-C / eps), the "reference"a, b = np.ones(3), np.ones(3)for it in range(200): # Sinkhorn: alternately rescale the rows and the columns to match the marginals; each step is an exact projection (a KL projection). a = r / (Kmat @ b) # rescale the rows so that the first marginal is r b = c / (Kmat.T @ a) # rescale the columns so that the second marginal is c# The plan has the form a_i K_ij b_j: one factor per row and per column, the same two-ended structure as SRP.P = a[:, None] * Kmat * b[None, :] # the plan: one factor per row and one per columnprint("plan:\n", P)print("row sums:", P.sum(axis=1), "| column sums:", P.sum(axis=0))print("entropic cost <C, P> =", (C * P).sum())
The row sums are $(0.5,0.3,0.2)$ and the column sums $(0.4,0.4,0.2)$ to machine precision. Each rescaling is an exact KL projection onto one family of constraints: alternating them converges to the intersection, the Sinkhorn plan.
Exercise 3.2 · SRP on the running example
- At $x=(0,1)$ for $o_1$ with $\rho=z^+$ and $y=x_{o_1}=6$, write the sweeps on the potentials of $h_1,h_2$ and $o_1$ (inputs fixed at $1$).
- Compute the flows $\pi_{u,v}=\rho_{u,v}\varphi_v/\varphi_u$ and the relevances. Check conservation and the divergence at the hidden nodes.
- Compare the relevances with LRP$_{z^+}$, and the value of $\mathrm{KL}(\pi\|\rho)$ for the two flows.
def srp(x, output, y=None, sweeps=200): """Sinkhorn relevance propagation with the reference rho = z^+ on the active graph.""" v = forward(x); z = contributions(x) nodes, edges = active_graph(x) rho = {e: max(z[e], 0.0) for e in edges if z[e] > 0} # keep the edges that lie on a positive path from an input to the output keep, changed = {output}, True while changed: changed = False for (u, t) in rho: if t in keep and u not in keep: keep.add(u); changed = True rho = {e: r for e, r in rho.items() if e[0] in keep and e[1] in keep} y = v[output] if y is None else y hidden = [n for n in HIDDEN if n in keep] phi = {n: 1.0 for n in keep} for _ in range(sweeps): for h in hidden: out_sum = ... # TO DO: sum over the edges leaving h of rho phi_w in_sum = ... # TO DO: sum over the edges entering h of rho / phi_u phi[h] = ... # TO DO: the fixed-point equation of the node phi[output] = ... # TO DO: the output potential carries the total mass y flows = {(u, t): r * phi[t] / phi[u] for (u, t), r in rho.items()} # pi_{u,v} = rho_{u,v} phi_v / phi_u mu = {n: sum(f for (u, t), f in flows.items() if u == n) for n in keep if n != output} return flows, mu, rho, phix = (0.0, 1.0)flows, mu, rho, phi = srp(x, "o1")print("potentials:", {k: round(float(p), 4) for k, p in phi.items()})print("SRP relevances (i2, b1) (i1 = 0 is inactive):", [round(float(mu[n]), 4) for n in ["i2", "b1"]], "| sum =", round(float(sum(mu[n] for n in ["i2", "b1"])), 6))print("divergence at the hidden nodes:", {h: round(float(divergence(flows, h)), 10) for h in ["h1", "h2"]})def kl(pi, rho): return sum(pi[e] * np.log(pi[e] / rho[e]) - pi[e] + rho[e] for e in rho if pi[e] > 0)flows_lrp, _ = lrp(x, "o1", lrp_zplus)flows_lrp = {e: f for e, f in flows_lrp.items() if e in rho}print("LRP_z+ relevances (i2, b1):", [round(lrp(x, "o1", lrp_zplus)[1][n], 4) for n in ["i2", "b1"]])print("KL(pi || rho): SRP", round(float(kl(flows, rho)), 4), "| LRP_z+", round(float(kl(flows_lrp, rho)), 4), "(the SRP flow has the smaller value)")
Show the correction
# SRP solves min KL(pi || rho) over the conservative flows of mass y at the output; the solution is pi_{u,v} = rho_{u,v} phi_v / phi_u.def srp(x, output, y=None, sweeps=200): """Sinkhorn relevance propagation with the reference rho = z^+ on the active graph.""" v = forward(x); z = contributions(x) nodes, edges = active_graph(x) rho = {e: max(z[e], 0.0) for e in edges if z[e] > 0} # keep the edges that lie on a positive path from an input to the output # Keep only the edges lying on a positive path from an input to the output. keep, changed = {output}, True while changed: changed = False for (u, t) in rho: if t in keep and u not in keep: keep.add(u); changed = True rho = {e: r for e, r in rho.items() if e[0] in keep and e[1] in keep} y = v[output] if y is None else y hidden = [n for n in HIDDEN if n in keep] # Potentials: 1 at the inputs, one positive number per hidden node and for the output, found by sweeps. phi = {n: 1.0 for n in keep} for _ in range(sweeps): for h in hidden: # The fixed-point equation of a hidden node v is phi_v^2 sum_u rho_{u,v}/phi_u = sum_w rho_{v,w} phi_w. out_sum = sum(r * phi[t] for (u, t), r in rho.items() if u == h) # sum over the edges leaving h of rho phi_w in_sum = sum(r / phi[u] for (u, t), r in rho.items() if t == h) # sum over the edges entering h of rho / phi_u phi[h] = np.sqrt(out_sum / in_sum) # the fixed-point equation of the node # The output potential is set by the total mass y. phi[output] = y / sum(r / phi[u] for (u, t), r in rho.items() if t == output) # the output potential carries the total mass y # Each edge is rescaled at both ends: by the potential of its head and the inverse potential of its tail. flows = {(u, t): r * phi[t] / phi[u] for (u, t), r in rho.items()} # pi_{u,v} = rho_{u,v} phi_v / phi_u mu = {n: sum(f for (u, t), f in flows.items() if u == n) for n in keep if n != output} return flows, mu, rho, phix = (0.0, 1.0)flows, mu, rho, phi = srp(x, "o1")print("potentials:", {k: round(float(p), 4) for k, p in phi.items()})print("SRP relevances (i2, b1) (i1 = 0 is inactive):", [round(float(mu[n]), 4) for n in ["i2", "b1"]], "| sum =", round(float(sum(mu[n] for n in ["i2", "b1"])), 6))print("divergence at the hidden nodes:", {h: round(float(divergence(flows, h)), 10) for h in ["h1", "h2"]})# Generalized KL divergence KL(pi || rho) = sum pi log(pi/rho) - pi + rho of the article.def kl(pi, rho): return sum(pi[e] * np.log(pi[e] / rho[e]) - pi[e] + rho[e] for e in rho if pi[e] > 0)flows_lrp, _ = lrp(x, "o1", lrp_zplus)flows_lrp = {e: f for e, f in flows_lrp.items() if e in rho}print("LRP_z+ relevances (i2, b1):", [round(lrp(x, "o1", lrp_zplus)[1][n], 4) for n in ["i2", "b1"]])print("KL(pi || rho): SRP", round(float(kl(flows, rho)), 4), "| LRP_z+", round(float(kl(flows_lrp, rho)), 4), "(the SRP flow has the smaller value)")
The sweeps give the potentials $\varphi_{h_1}=1.2426$, $\varphi_{h_2}=1.7574$, $\varphi_{o_1}=1.5442$, the relevances $(i_2,b_1)=(4.2426,1.7574)$ (that is $3\sqrt2$ and $6-3\sqrt2$) against $(4,2)$ for LRP$_{z^+}$, and a divergence of $0$. Both flows are admissible, but $\mathrm{KL}(\pi\|\rho)=0.607$ for SRP and $0.773$ for LRP$_{z^+}$: SRP is the minimizer of this criterion, LRP$_{z^+}$ the minimizer of the other one (Part 2). Two principles, two explanations of the same output.
Relevance by region and Schrödinger bridges
A relevance map says which pixels support the output, not through which hidden units. For a non-negative reference, the relevance can be followed along the backward paths of the network: the backward Markov chain with kernel $K$, started at $o$ with mass $x_o$. For nodes $u,v$ let
\[R^{(v)}_u=\sum_{p\in\mathcal P(u,v)}\ \prod_{(a,b)\in p}K_{a,b}\]be the relevance of $u$ when the recursion is started from $v$ with unit mass, and, for a set $M$ of input nodes (a region), $R^{(v)}(M)=\sum_{i\in M}R^{(v)}_i$.
(i) The paths of the chain that pass through $v$ and end in an input $i$ carry the mass $\mu_v\,R^{(v)}_i$. (ii) The region relevance $\mu^M_v=\mu_v\,R^{(v)}(M)$ satisfies, for every cut $C$ (a set of nodes met exactly once by each path from an input to $o$), $\sum_{v\in C}\mu^M_v=\mu(M)=\sum_{i\in M}\mu_i$. (iii) The flow $\pi^M_{u,v}=\dfrac{x_o}{\mu(M)}\,\pi^{*}_{u,v}\,R^{(u)}(M)$ is the minimizer of $\mathcal H(\pi\|K)$ among the admissible flows whose input mass is carried by $M$ only, with the minimal value $x_o\log\big(x_o/\mu(M)\big)$: a Schrödinger bridge conditioned on the region.
Proof
(i) The mass of a backward path $o=v_0,v_1,\dots,v_m=i$ (the edges are $(v_{k+1},v_k)$) is $x_o\prod_kK_{v_{k+1},v_k}$. Summing over the paths that pass through $v$ and end at $i$ factorizes into the sum over the paths from $o$ to $v$, which is $\mu_v$ by the recursion, times the sum over the paths from $v$ to $i$, which is $R^{(v)}_i$. (ii) If every path meets $C$ exactly once, the mass of the paths ending in $M$ is the sum over $v\in C$ of the mass of those that go through $v$: $\sum_{v\in C}\mu^M_v=\sum_{i\in M}\mu_i$ by (i) applied with $v=i$. (iii) is the Schrödinger problem with both end marginals prescribed (the mass of $o$ and the mass on $M$); its solution rescales the paths ending in $M$ by $x_o/\mu(M)$, and the relative entropy of the rescaled measure is $x_o\log(x_o/\mu(M))$. $\square$
Exercise 3.3 · region relevance on the running example
- From the flows of LRP$_{z^+}$ at $x=(1,1)$, recover the kernel $K$.
- Compute $R^{(v)}_u$ by a backward sweep started at $v$ with unit mass, then the region relevance $\mu^M_v=\mu_vR^{(v)}(M)$ for $M=\{i_2\}$ at $h_1$, $h_2$, $o_1$.
- Check the cut $\{o_1\}$, and compute the flow of the conditioned bridge through $h_1$ and $h_2$.
x = (1.0, 1.0)flows_lrp, mu_lrp = lrp(x, "o1", lrp_zplus) # the relevance flows of LRP_z+ (the kernel K)nodes = ["i1", "i2", "b1", "h1", "h2", "o1"]into = {t: sum(f for (u, s), f in flows_lrp.items() if s == t) for t in nodes}K = {e: f / into[e[1]] for e, f in flows_lrp.items() if into[e[1]] > 0}def R(v): """R^{(v)}_u: relevance of u when the backward recursion is started from v with unit mass.""" rel = {n: 0.0 for n in nodes} rel[v] = 1.0 for u in reversed(["i1", "i2", "b1", "h1", "h2", "o1"]): # backward over the nodes if u == v: continue rel[u] = ... # TO DO: sum over the successors of K_{u,w} R_w return relM = ["i2"] # a region of the input: the single input i2mu_M = ... # TO DO: region relevance mu_v R^{(v)}(M)print("region relevance of M = {i2}:", {k: round(a, 4) for k, a in mu_M.items()}, "| mu(M) =", mu_lrp["i2"])print("cut {o1}: sum =", mu_M["o1"], "| the paths through h1 and h2 carry", mu_M["h1"], "and", mu_M["h2"], "(the sum is mu(M))")scale = forward(x)["o1"] / mu_lrp["i2"] # the bridge rescales the evidence of M to the full output massprint("Schroedinger bridge conditioned on M: through h1", scale * mu_M["h1"], ", through h2", scale * mu_M["h2"])
Show the correction
x = (1.0, 1.0)flows_lrp, mu_lrp = lrp(x, "o1", lrp_zplus) # the relevance flows of LRP_z+ (the kernel K)nodes = ["i1", "i2", "b1", "h1", "h2", "o1"]into = {t: sum(f for (u, s), f in flows_lrp.items() if s == t) for t in nodes}# The kernel of the LRP_z+ reference, recovered from its flows.K = {e: f / into[e[1]] for e, f in flows_lrp.items() if into[e[1]] > 0}# Start with unit mass at v and run the backward recursion: R^{(v)}_u is the share of u in the evidence of v.def R(v): """R^{(v)}_u: relevance of u when the backward recursion is started from v with unit mass.""" rel = {n: 0.0 for n in nodes} rel[v] = 1.0 for u in reversed(["i1", "i2", "b1", "h1", "h2", "o1"]): # backward over the nodes if u == v: continue rel[u] = sum(K[(u, t)] * rel[t] for (a, t) in K if a == u) # sum over the successors of K_{u,w} R_w return relM = ["i2"] # a region of the input: the single input i2# mu_v R^{(v)}(M): the part of the relevance of v whose paths end in the region M.mu_M = {v: mu_lrp[v] * sum(R(v)[i] for i in M) for v in ["h1", "h2", "o1"]} # region relevance mu_v R^{(v)}(M)print("region relevance of M = {i2}:", {k: round(a, 4) for k, a in mu_M.items()}, "| mu(M) =", mu_lrp["i2"])print("cut {o1}: sum =", mu_M["o1"], "| the paths through h1 and h2 carry", mu_M["h1"], "and", mu_M["h2"], "(the sum is mu(M))")# The Schroedinger bridge conditioned on M scales these flows by x_o / mu(M) so that the whole output mass comes from M.scale = forward(x)["o1"] / mu_lrp["i2"] # the bridge rescales the evidence of M to the full output massprint("Schroedinger bridge conditioned on M: through h1", scale * mu_M["h1"], ", through h2", scale * mu_M["h2"])
The evidence of $M=\{i_2\}$ goes for $2$ through $h_1$ and $1$ through $h_2$: $\mu^M_{h_1}+\mu^M_{h_2}=3=\mu_{i_2}$, and the cut $\{o_1\}$ gives $3$ as well. The bridge conditioned on $M$ rescales by $6/3=2$: $4$ through $h_1$ and $2$ through $h_2$, the numbers of the article. The head of the region, here a single input, is carried mostly by $h_1$.
Part 4 · Relevance in a trained Keras network
From the toy graph to a Keras network
A dense network is a layered DAG: layer $\ell$ has $a^{(\ell)}$ for values and a kernel $W^{(\ell)}$ and a bias $b^{(\ell)}$. With the bias as a node of value $1$, the contributions entering unit $j$ are $z_{i,j}=a_iW_{ij}$ and $z_{b,j}=b_j$, and the rule of Part 1 becomes, for a reference $\rho$ (here $z$ or $z^{+}$),
\[R_i=\sum_j\frac{\rho_{i,j}}{\sum_{i'}\rho_{i',j}+\rho_{b,j}}\,R_j,\]a matrix product per layer. The share $\rho_{b,j}/\tilde\rho_j$ of the relevance absorbed by the bias nodes is lost for the pixels: it is why the pixel relevances add up to a little less than the explained logit. We apply this to a small ReLU network on the $8\times8$ handwritten digits of scikit-learn, with the logit of the class as the explained output.
Exercise 4.1 · a ReLU network on digits
- Load the digits, scale them to $[0,1]$ and split them (stratified).
- Build a network $64\to32\to10$ with one ReLU hidden layer, and train it with Adam.
- Report the test accuracy.
from sklearn.datasets import load_digitsfrom sklearn.model_selection import train_test_splitdigits = load_digits()X = (digits.data / 16.0).astype("float32") # 1,797 images of 8 x 8 pixels with values in [0, 1]y = digits.targetx_tr, x_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=SEED)keras.utils.set_random_seed(SEED)hidden = ... # TO DO: one hidden layer of 32 ReLU unitshead = ... # TO DO: one logit per digitnet = keras.Sequential([keras.Input(shape=(64,)), hidden, head])net.compile(optimizer=keras.optimizers.Adam(1e-2), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])net.fit(x_tr, y_tr, epochs=40, batch_size=64, validation_split=0.15, verbose=0)print("test accuracy:", net.evaluate(x_te, y_te, verbose=0)[1])
Show the correction
from sklearn.datasets import load_digitsfrom sklearn.model_selection import train_test_splitdigits = load_digits()X = (digits.data / 16.0).astype("float32") # 1,797 images of 8 x 8 pixels with values in [0, 1]y = digits.target# Stratified split so that every digit appears in both sets.x_tr, x_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=SEED)keras.utils.set_random_seed(SEED)# A small ReLU network: 64 pixels -> 32 hidden units -> 10 logits. It is a feed-forward Filippov network with ReLU nodes only.hidden = layers.Dense(32, activation="relu") # one hidden layer of 32 ReLU unitshead = layers.Dense(10) # one logit per digitnet = keras.Sequential([keras.Input(shape=(64,)), hidden, head])net.compile(optimizer=keras.optimizers.Adam(1e-2), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=["accuracy"])net.fit(x_tr, y_tr, epochs=40, batch_size=64, validation_split=0.15, verbose=0)print("test accuracy:", net.evaluate(x_te, y_te, verbose=0)[1])
The test accuracy is $96.2\%$. The network contains only ReLU nodes, so it is a feed-forward Filippov network whose output values never branch.
Exercise 4.2 · LRP for a dense network
- Extract the kernels and biases of the two Dense layers.
- Write one backward step for a dense layer, for the references $z$ and $z^+$, with the bias as a node in the denominator.
- Explain the logit of the predicted class of a test image and look at the total relevance reaching the pixels.
W1, b1 = [w.numpy() for w in net.layers[0].weights]W2, b2 = [w.numpy() for w in net.layers[1].weights]def forward_mlp(x): a1 = np.maximum(x @ W1 + b1, 0.0) return a1, a1 @ W2 + b2def lrp_layer(a, W, b, R, rule): """Redistribute the relevance R of the nodes of a layer to the nodes a that feed it (the bias is a node of value 1).""" z = a[:, None] * W # contributions z_{i,j} = a_i W_ij zb = b # contribution of the bias node if rule == "zplus": z, zb = ... # TO DO: keep the positive parts only den = ... # TO DO: the sum of the reference entering each node safe = np.where(den == 0, 1.0, den) return ... # TO DO: R_i = sum_j K_{i,j} R_jdef lrp_mlp(x, c, rule): a1, logits = forward_mlp(x) R2 = np.zeros(10); R2[c] = logits[c] # all the relevance starts at the explained logit R1 = lrp_layer(a1, W2, b2, R2, rule) # hidden units R0 = lrp_layer(x, W1, b1, R1, rule) # pixels return R0, R1x = x_te[0]; c = int(np.argmax(forward_mlp(x)[1]))R0, R1 = lrp_mlp(x, c, "lrp0")print("explained logit:", forward_mlp(x)[1][c])print("relevance reaching the pixels: LRP_0", R0.sum(), "| LRP_z+", lrp_mlp(x, c, "zplus")[0].sum(), "(the rest is absorbed by the bias nodes)")
Show the correction
# The kernels and biases of the Keras layers are the weights of the graph; the bias of a unit is the weight of its bias node.W1, b1 = [w.numpy() for w in net.layers[0].weights]W2, b2 = [w.numpy() for w in net.layers[1].weights]def forward_mlp(x): a1 = np.maximum(x @ W1 + b1, 0.0) return a1, a1 @ W2 + b2# One backward step of the recursion for a dense layer: matrix form of R_i = sum_j K_{ij} R_j.def lrp_layer(a, W, b, R, rule): """Redistribute the relevance R of the nodes of a layer to the nodes a that feed it (the bias is a node of value 1).""" # z[i, j] is the contribution of the node i to the unit j. z = a[:, None] * W # contributions z_{i,j} = a_i W_ij zb = b # contribution of the bias node if rule == "zplus": z, zb = np.maximum(z, 0.0), np.maximum(b, 0.0) # keep the positive parts only # The bias node is part of the denominator: it keeps a share of the relevance, which is not seen on the pixels. den = z.sum(axis=0) + zb # the sum of the reference entering each node safe = np.where(den == 0, 1.0, den) return (z / safe[None, :]) @ R # R_i = sum_j K_{i,j} R_jdef lrp_mlp(x, c, rule): a1, logits = forward_mlp(x) # The explained logit is the only relevance injected into the network. R2 = np.zeros(10); R2[c] = logits[c] # all the relevance starts at the explained logit R1 = lrp_layer(a1, W2, b2, R2, rule) # hidden units R0 = lrp_layer(x, W1, b1, R1, rule) # pixels return R0, R1x = x_te[0]; c = int(np.argmax(forward_mlp(x)[1]))R0, R1 = lrp_mlp(x, c, "lrp0")print("explained logit:", forward_mlp(x)[1][c])print("relevance reaching the pixels: LRP_0", R0.sum(), "| LRP_z+", lrp_mlp(x, c, "zplus")[0].sum(), "(the rest is absorbed by the bias nodes)")
For the first test image the logit is $4.5006$; the pixels receive $4.478$ under LRP$_0$ and $4.319$ under LRP$_{z^+}$. The difference is what the bias nodes keep: the positive rule leaves a larger share to the biases, which is one of the properties that the article measures on VGG-16.
Exercise 4.3 · LRP$_0$ is Gradient×Input
- Compute Gradient×Input for the Keras network with
tf.GradientTape. - Compare it with the pixel relevances of LRP$_0$ on 50 test images and print the largest difference.
def gradient_x_input(x, c): xt = tf.Variable(x[None]) with tf.GradientTape() as tape: out = net(xt)[0, c] return ... # TO DO: gradient of the logit times the inputworst = 0.0for x in x_te[:50]: c = int(np.argmax(forward_mlp(x)[1])) worst = ... # TO DO: largest difference between the two mapsprint("largest difference between LRP_0 and Gradient x Input over 50 images:", worst)
Show the correction
# The classical attribution, computed by automatic differentiation.def gradient_x_input(x, c): xt = tf.Variable(x[None]) with tf.GradientTape() as tape: out = net(xt)[0, c] return tape.gradient(out, xt).numpy()[0] * x # gradient of the logit times the input# The two maps are the same up to float32 rounding errors: LRP_0 is Gradient x Input on ReLU networks.worst = 0.0for x in x_te[:50]: c = int(np.argmax(forward_mlp(x)[1])) worst = max(worst, np.abs(lrp_mlp(x, c, "lrp0")[0] - gradient_x_input(x, c)).max()) # largest difference between the two mapsprint("largest difference between LRP_0 and Gradient x Input over 50 images:", worst)
The largest difference over 50 images is $1.7\cdot10^{-5}$, the accuracy of float32 arithmetic: on ReLU networks the signed rule is the classical Gradient×Input, as the corollary of the article states.
Exercise 4.4 · a deletion test
- For 150 correctly classified test images, delete the pixels (set them to $0$) in decreasing order of relevance and record the logit of the class, for LRP$_0$, LRP$_{z^+}$ and a random order.
- Plot the mean curves, and print the area under each curve and the value after 20 deleted pixels.
- Which rule makes the logit fall fastest?
def deletion_curve(x, c, order, steps=33): """Logit of class c when the first k pixels of `order` are set to 0 (black), k = 0, 2, 4, ...""" values = [] for k in range(0, 64, 2)[:steps]: xx = x.copy(); xx[order[:k]] = 0.0 values.append(forward_mlp(xx)[1][c]) return np.array(values)rng = np.random.default_rng(0)idx = [i for i in range(len(x_te)) if np.argmax(forward_mlp(x_te[i])[1]) == y_te[i]][:150] # correctly classified test imagescurves = {name: [] for name in ["LRP_0 (= Gradient x Input)", "LRP_z+", "random"]}for i in idx: x, c = x_te[i], int(y_te[i]) r0 = lrp_mlp(x, c, "lrp0")[0]; rz = lrp_mlp(x, c, "zplus")[0] ... # TO DO: delete the pixels of largest relevance first curves["LRP_z+"].append(deletion_curve(x, c, np.argsort(-rz))) curves["random"].append(deletion_curve(x, c, rng.permutation(64)))for name, cs in curves.items(): m = np.mean(cs, axis=0) # mean logit curve over the images plt.plot(range(0, 64, 2), m, label=name) print(f"{name:28s}: area under the mean curve {m.mean():7.3f} logit after deleting 20 pixels {m[10]:7.3f}")plt.xlabel("number of deleted pixels"); plt.ylabel("logit of the class"); plt.legend(); plt.show()

Show the correction
# Faithfulness test: delete the pixels in a given order and watch the logit of the class.def deletion_curve(x, c, order, steps=33): """Logit of class c when the first k pixels of `order` are set to 0 (black), k = 0, 2, 4, ...""" values = [] for k in range(0, 64, 2)[:steps]: xx = x.copy(); xx[order[:k]] = 0.0 values.append(forward_mlp(xx)[1][c]) return np.array(values)rng = np.random.default_rng(0)# Only correctly classified images are used.idx = [i for i in range(len(x_te)) if np.argmax(forward_mlp(x_te[i])[1]) == y_te[i]][:150] # correctly classified test imagescurves = {name: [] for name in ["LRP_0 (= Gradient x Input)", "LRP_z+", "random"]}for i in idx: x, c = x_te[i], int(y_te[i]) # Relevance maps under the two rules for the true class. r0 = lrp_mlp(x, c, "lrp0")[0]; rz = lrp_mlp(x, c, "zplus")[0] curves["LRP_0 (= Gradient x Input)"].append(deletion_curve(x, c, np.argsort(-r0))) # delete the pixels of largest relevance first curves["LRP_z+"].append(deletion_curve(x, c, np.argsort(-rz))) curves["random"].append(deletion_curve(x, c, rng.permutation(64)))for name, cs in curves.items(): m = np.mean(cs, axis=0) # mean logit curve over the images plt.plot(range(0, 64, 2), m, label=name) print(f"{name:28s}: area under the mean curve {m.mean():7.3f} logit after deleting 20 pixels {m[10]:7.3f}")plt.xlabel("number of deleted pixels"); plt.ylabel("logit of the class"); plt.legend(); plt.show()
| order | area under the mean curve | logit after 20 pixels |
|---|---|---|
| LRP$_0$ (Gradient×Input) | $-6.98$ | $-8.98$ |
| LRP$_{z^+}$ | $-1.31$ | $-4.77$ |
| random | $3.39$ | $4.83$ |
Both rules are far better than a random order, and on this network the signed rule makes the logit fall faster. A faster fall under deletion is evidence of faithfulness for this test, but the test itself replaces pixels by an out-of-distribution black, and the article evaluates several tests (and several networks) because no single one is conclusive.
Exercise 4.5 · which hidden units carry the upper half?
- For the rule LRP$_{z^+}$, recompute the kernel $K_{i,j}$ of the first layer.
- For the region $M$ made of the four upper rows of the image, compute the region relevance $\mu_jR^{(j)}(M)$ of the hidden units.
- Check that the hidden layer is a cut (the sum equals the relevance of the region on the pixels) and list the units that carry the upper half and the lower half.
x = x_te[0]; c = int(np.argmax(forward_mlp(x)[1]))a1, _ = forward_mlp(x)R0, R1 = lrp_mlp(x, c, "zplus") # LRP_z+: hidden relevances R1 and pixel relevances R0z = np.maximum(x[:, None] * W1, 0.0); zb = np.maximum(b1, 0.0)K = z / (z.sum(axis=0) + zb)[None, :] # kernel K_{i,j} of the first layer: share of hidden unit j due to pixel itop = np.zeros(64, bool); top[:32] = True # region M: the 4 upper rows of the image (32 pixels)share_top = ... # TO DO: R^{(j)}(M): the share of each hidden unit that comes from the regionmu_M = ... # TO DO: region relevance mu_j R^{(j)}(M) of the hidden unitsmu_bottom = R1 * K[~top].sum(axis=0)print("class", c, "| relevance of the region (upper half) via the pixels:", R0[top].sum())print("sum over the hidden units of the region relevance:", mu_M.sum(), "(the same number: the hidden layer is a cut, up to the bias nodes)")print("hidden units carrying the upper half:", np.argsort(-mu_M)[:5], "| the lower half:", np.argsort(-mu_bottom)[:5])
Show the correction
x = x_te[0]; c = int(np.argmax(forward_mlp(x)[1]))a1, _ = forward_mlp(x)R0, R1 = lrp_mlp(x, c, "zplus") # LRP_z+: hidden relevances R1 and pixel relevances R0# Recompute the kernel K_{i,j} of the first layer for the rule LRP_z+.z = np.maximum(x[:, None] * W1, 0.0); zb = np.maximum(b1, 0.0)K = z / (z.sum(axis=0) + zb)[None, :] # kernel K_{i,j} of the first layer: share of hidden unit j due to pixel i# The region M is a set of input pixels: here the four upper rows.top = np.zeros(64, bool); top[:32] = True # region M: the 4 upper rows of the image (32 pixels)share_top = K[top].sum(axis=0) # R^{(j)}(M): the share of each hidden unit that comes from the region# Region relevance of the hidden units: which units carry the evidence that comes from M.mu_M = R1 * share_top # region relevance mu_j R^{(j)}(M) of the hidden unitsmu_bottom = R1 * K[~top].sum(axis=0)print("class", c, "| relevance of the region (upper half) via the pixels:", R0[top].sum())print("sum over the hidden units of the region relevance:", mu_M.sum(), "(the same number: the hidden layer is a cut, up to the bias nodes)")print("hidden units carrying the upper half:", np.argsort(-mu_M)[:5], "| the lower half:", np.argsort(-mu_bottom)[:5])
For the first test image (class 2) the upper half carries a relevance of $2.0569$, and the hidden units sum to the same value $2.0569$. The units $28, 8, 29, 14, 17$ carry the upper half and $28, 29, 14, 8, 24$ the lower half: several units are shared, as the article observes on VGG-16 for the head and the body of an animal.
Part 5 · Deliverables and limits
Build a defensible report
- Explain, with the example $E_1=z+1$, $E_2=2z-1$ of the course Filippov neural networks with Keras, why automatic differentiation hides information at a routing tie, and give the Filippov set.
- Prove the conservation proposition and check it numerically for three different references.
- State the entropic projection theorem and reproduce its proof for a non-negative reference.
- Compare LRP$_0$, LRP$_{z^+}$, LRP$_{2,-1}$ and SRP on the running example at an input of your choice: values, signs, shares left to the biases.
- Report the deletion test of Exercise 4.4 and the region relevance of Exercise 4.5 for another class and another region (left and right halves).
- Extension: implement SRP for the dense network of Part 4 by Sinkhorn sweeps layer by layer, and compare its deletion curve with the two other rules.
Deliver a rerunnable notebook, a table of results, the figures and a discussion of limits.
What these experiments do not show
The running example has 13 weights and the digits are $8\times8$ images: these programs explain the mechanics, not the behaviour of large models. The article evaluates the rules on VGG-16 and ConvNeXt-Tiny, with several measures (conservation, the share left to the bias nodes, faithfulness, localization, class dependence), and it states what remains open: the theorem characterizes the flow once the reference is fixed, it does not choose the reference nor guarantee faithfulness. Filippov sets are a tool for analysis at switching points; Keras models are trained with the usual single selection, and the explanation of a hard-routed network at a routing tie should report the set, not one arbitrary branch. The animation of the article on a car image is an illustration, not a benchmark.
References and related learning
The article and related work
- O. Gibaru, E. Nyiri, Relevance Propagation as Entropic Optimal Transport on Filippov Neural Networks: Sinkhorn Propagation and Region Relevance in Image Classifiers, arXiv:2611.05594, 2026.
- S. Bach et al., On pixel-wise explanations for non-linear classifier decisions by layer-wise relevance propagation, PLoS ONE 10(7), 2015.
- G. Montavon et al., Explaining nonlinear classification decisions with deep Taylor decomposition, Pattern Recognition 65, 2017.
- A. F. Filippov, Differential Equations with Discontinuous Righthand Sides, Kluwer, 1988; F. H. Clarke, Optimization and Nonsmooth Analysis, SIAM, 1990.
- M. Cuturi, Sinkhorn distances: lightspeed computation of optimal transport, NeurIPS 2013; G. Peyré, M. Cuturi, Computational optimal transport, 2019.
- N. Shazeer et al., Outrageously large neural networks: the sparsely-gated mixture-of-experts layer, ICLR 2017.
- On this site: Neural networks with Keras, Transformers with Keras, VLM Project, Optimization on Riemannian manifolds (the natural gradient and information geometry).