Trace tensor shapes and parameter counts through a LeNet-style CNN
Why it matters Mismatched flatten sizes are the most common error when people first write a CNN.
Before building a CNN you should be able to say the shape after every layer and how many weights it has.
Write trace_shapes(input_shape, layers). input_shape is (C, H, W). layers is a list of tuples: ("conv", out_c, k, s, p) with bias, ("pool", k, s) with no parameters, ("flatten",), and ("fc", out) with bias. Conv and pool output size is (H + 2p - k) // s + 1 (pool has p = 0). Flatten gives a 1-tuple (C * H * W,). Return a list with one (shape_tuple, n_params) per layer.
def trace_shapes(input_shape, layers)Example
trace_shapes((1, 32, 32), [("conv", 6, 5, 1, 0), ("pool", 2, 2), ("conv", 16, 5, 1, 0), ("pool", 2, 2), ("flatten",), ("fc", 120), ("fc", 84), ("fc", 10)]) is [((6, 28, 28), 156), ((6, 14, 14), 0), ((16, 10, 10), 2416), ((16, 5, 5), 0), ((400,), 0), ((120,), 48120), ((84,), 10164), ((10,), 850)].
Understand the idea
A CNN is a chain of shape changes. Convs change the channel count and usually shrink the image a bit; pools halve it; flatten unrolls it into a long vector; fully connected layers map vectors to vectors. If you track one shape through the chain, you can predict every layer's size and cost before writing any model code, like checking that each pipe in a plumbing job fits the next.
Tiny example: a 1 x 32 x 32 image, 6 filters of 5 x 5: (32 - 5) / 1 + 1 = 28, so 6 x 28 x 28, with 6 * (1 * 25 + 1) = 156 parameters. A 2 x 2 pool stride 2 gives 6 x 14 x 14 with 0 parameters.
Rules: size = (H + 2p - k) // s + 1; conv params = out_c (in_c k^2 + 1); fc params = out (in + 1).
The classic LeNet digit recogniser has about 61,700 parameters by this count.
Shapes and data flow
(1,32,32) -> (6,28,28) -> (6,14,14) -> (16,10,10) -> (16,5,5) -> (400,) -> 120 -> 84 -> 10