Deep learning and neural networksLoading progress…

Residual connections

Calculate a convolutional output and explain filters, stride, padding, pooling and residual connections.

Shortcuts that carry the input around the layers

A residual block computes y = x + F(x): it adds the layers' output F(x) to the unchanged input x. If a block has nothing useful to add it can learn F ≈ 0 and simply pass x on. For gradients, the addition gives each block a derivative of 1 + (slope of F) instead of just the slope, so the gradient through a very deep stack does not collapse to zero.

x = [1,-2,3] F(x) = [0.5,-1,0.5] (what the layers learned) x + F(x) = [1.5,-3,3.5] (the shortcut carries x through unchanged)
slope w of each layer0.4
stack of 20 layersgradient reaching the first layer
plain: w^201.10e-8
residual: (1 + w)^208.37e+2
Twenty layers with slope w. The plain stack's gradient is w^20; the residual stack's is (1 + w)^20.

Predict first. Can a shortcut add two tensors of incompatible shapes with no defined mapping between them?

F = np.maximum(x @ W1, 0) @ W2      # the learned part
y = F + x                           # the shortcut (or x @ proj when shapes change)
Chapter context

A convolutional layer reuses a local filter across positions. Weight sharing encodes a structural assumption about repeated local patterns while greatly reducing parameters compared with a fully connected map over all pixels.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

For one spatial dimension, output size is

nout=⌊n+2p−d(k−1)−1s⌋+1.n_{out}=\left\lfloor\frac{n+2p-d(k-1)-1}{s}\right\rfloor+1.

Here n is input size, k kernel size, p padding, d dilation and s stride. Cross-correlation is yt=∑iwixt+iy_t=\sum_iw_i x_{t+i}. A residual block has form hout=h+F(h)h_{out}=h+F(h) when shapes agree.

Worked example

For input [1,2,3,4] and kernel [1,−1], stride-one valid cross-correlation returns [−1,−1,−1]. Separately, n=7,k=3,p=1,s=2,d=1 gives floor((7+2−2−1)/2)+1=4 output positions.

Reference code

The following example uses the Python standard library and does not call a remote service.

x,w = [1,2,3,4],[1,-1]
y = [sum(x[t+i]*w[i] for i in range(len(w))) for t in range(len(x)-len(w)+1)]
assert y == [-1,-1,-1]
n,k,p,s,d = 7,3,1,2,1
assert (n+2*p-d*(k-1)-1)//s+1 == 4

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

Padding does not reveal missing real pixels. Kernel flipping conventions change calculations. A residual shortcut needs a defined shape-compatible path.