What Survives the Trip Back

BackpropagationMedium+20 XP+20

What Survives the Trip Back

Picture the thinnest deep network there is: one neuron per layer, stacked LLL layers deep. Starting from h0=xh_0 = xh0​=x, each layer computes

zl=wl hl−1+bl,hl=act(zl),l=1,…,Lz_l = w_l\,h_{l-1} + b_l, \qquad h_l = \text{act}(z_l), \qquad l = 1, \dots, Lzl​=wl​hl−1​+bl​,hl​=act(zl​),l=1,…,L

and the network's output is hLh_LhL​.

The backward pass starts at the output with ∂hL∂hL=1\dfrac{\partial h_L}{\partial h_L} = 1∂hL​∂hL​​=1. Every layer it crosses multiplies the signal by that layer's rate, which has two parts, the activation's slope and the weight:

∂hL∂hl−1=∂hL∂hl⋅act′(zl)⋅wl\frac{\partial h_L}{\partial h_{l-1}} = \frac{\partial h_L}{\partial h_l} \cdot \text{act}'(z_l) \cdot w_l∂hl−1​∂hL​​=∂hl​∂hL​​⋅act′(zl​)⋅wl​

The three activations and their slopes:

activationact(z)\text{act}(z)act(z)act′(z)\text{act}'(z)act′(z)
"sigmoid"σ(z)=11+e−z\sigma(z) = \dfrac{1}{1 + e^{-z}}σ(z)=1+e−z1​σ(z) (1−σ(z))\sigma(z)\,\big(1 - \sigma(z)\big)σ(z)(1−σ(z))
"tanh"tanh⁡(z)\tanh(z)tanh(z)1−tanh⁡(z)21 - \tanh(z)^21−tanh(z)2
"relu"max⁡(0,z)\max(0, z)max(0,z)111 if z>0z > 0z>0, otherwise 000 (including at exactly z=0z = 0z=0)

Task: write stack_gradients(activation, x, weights, biases). Layer lll uses weights[l-1] and biases[l-1], and every layer uses the same activation. Run the forward pass, then the backward pass, and return the list

[ ∂hL∂hL,  ∂hL∂hL−1,  …,  ∂hL∂h0 ]\left[\ \frac{\partial h_L}{\partial h_L},\ \ \frac{\partial h_L}{\partial h_{L-1}},\ \ \dots,\ \ \frac{\partial h_L}{\partial h_0}\ \right][ ∂hL​∂hL​​,  ∂hL−1​∂hL​​,  …,  ∂h0​∂hL​​ ]

That is L+1L + 1L+1 numbers: 1.0 at the output first, and the gradient that reaches the input xxx last. Round each one to 4 decimal places. Read left to right, the list shows how much of the signal is still alive after each layer it crosses on the way back.

0.25
0.25
0.25
multiplied together
0.01563
3 layers

Examples

activation = "sigmoid"
x = 0.0
weights = [1.0, 1.0, 1.0, 1.0, 1.0]
biases = [0.0, 0.0, 0.0, 0.0, 0.0]
returns [1.0, 0.2248, 0.0507, 0.0115, 0.0027, 0.0007]
activation = "relu"
x = 1.5
weights = [2.0, -1.0, 0.5]
biases = [0.0, 4.0, 1.0]
returns [1.0, 0.5, -0.5, -1.0]
activation = "tanh"
x = 0.8
weights = [1.5, -2.0, 1.2, 0.9]
biases = [0.1, 0.0, -0.3, 0.2]
returns [1.0, 0.6392, 0.1583, -0.0379, -0.0146]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run