Lesson 3.2 — Convolutional Neural Networks
Pixel, channel & tensor
An image is a sampled 2D spatial signal rather than an unstructured flat vector. PyTorch
Conv2d expects NCHW layout: Batch, Channel, Height, Width. Converting
an HWC image to NCHW requires permute, never
reshape.
01 · RGB Image Tensor Inspector (1 × 3 × 4 × 6)
permute(2, 0, 1).unsqueeze(0), never reshape.HWC to NCHW layout conversion
import torch
image = torch.rand(32, 64, 3) # HWC
x = image.permute(2, 0, 1).unsqueeze(0) # (1, 3, 32, 64)
Sliding window & cross-correlation
An inspection camera sees a vertical boundary between a dark surface and a bright one. To locate the boundary, compare the brightness on the two sides of a small patch. Slide that same comparison over the image. Where it responds tells you where the local pattern occurs.

Read the highlighted patch from left to right. The filter subtracts a weighted sum of its left column from the same weighted sum of its right column. The center column has zero weight. A constant patch therefore cancels, even if it is bright. A patch that crosses the boundary produces a positive response because its right side is brighter. Reversing the brightness order reverses the sign.
The output has two responding columns even though there is only one boundary. A three-column patch can straddle this boundary from two different starting positions. Each colored output cell describes a patch, and adjacent patches overlap.
Here locates the top-left corner of the patch, and indexes an offset inside it. The figure uses one input channel, stride one, no padding and zero bias. Each output is the dot product from Lesson 1.4; the weights stay fixed as the patch moves. This indexing is cross-correlation, the convention used by a CNN convolutional layer. Training can learn other comparisons from data.
Inspect the filter taps or change the edge orientation
02 · Kernel Convolution Player
03 · Edge & Texture Filter Playground (Same-Pad)
Spatial shape · exact output size derivation
If the effective kernel exceeds the padded input, no valid window exists and PyTorch raises an
error. When stride = 1 and K_eff is odd, symmetric padding
P = (K_eff − 1) / 2 preserves spatial size.
With symmetric padding width P, there are H + 2P available positions. The last sampled tap is D(K−1) positions from the first. For an output index j, the tap positions in original input coordinates are jS−P+kD. Read indices outside the original input as zero. Check how increasing stride moves the entire window, while increasing dilation spreads its taps.
04 · Padding / Stride / Dilation (H = 7)
Multi-channel feature maps
For an ungrouped convolution with a trainable bias per output channel, the parameter count includes those biases. The MAC count below covers kernel products and their accumulation for one sample, excluding bias addition.
Parameter count in standard convolution (groups = 1) is independent of input image
size, while compute scales with output spatial resolution.
05 · Multi-channel Feature Map (C_in=2 → C_out=2)
Pooling · spatial downsampling
Global Average Pooling (GAP) averages each feature map into a single scalar, shrinking the classification head parameter count and reducing sensitivity to object position—though boundary effects, stride, and padding still prevent exact translation invariance.
06 · Pooling Operator Explorer (6×6 Input)
Receptive field & hierarchical features
The theoretical receptive field bounds which input pixels can possibly affect an output, whereas the effective receptive field measures which pixels have significant gradient influence.
07 · Receptive Field Tracker (3×3 Conv Layers)
Shape, parameters & gradient flow
| Layer | Output Shape (F=4) | Parameters |
|---|---|---|
| Conv2d(1, 4, 3) | (B, 4, 6, 6) | 40 |
| ReLU / GAP | (B, 4) | 0 |
| Linear(4, 3) | (B, 3) | 15 |
Engineering Lab · Industrial Visual Inspection
Default PyTorch result over 100 Adam updates (F=4, lr=0.03,
noise=0.12): validation CE drops 1.092172 → 0.026326 with
24/24 validation accuracy. Real industrial vision requires splitting by part/batch
and testing under realistic illumination and defect variations.
The browser trains the same small architecture with full-batch Adam on the synthetic split. It keeps 11 checkpoints so you can inspect the same validation image and feature channel across training. Each feature map uses its own brightness scale. Compare the spatial pattern in the map and the probability bars for the output.
08 · Train and Inspect a Tiny CNN
Complete implementation · NumPy + PyTorch (industrial_cnn.py)
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
torch.set_num_threads(1)
torch.set_default_dtype(torch.float64)
def rng(seed):
x = seed
def next_value():
nonlocal x
x = (1664525 * x + 1013904223) % 2**32
return x / 2**32
return next_value
def dataset(n, seed, noise):
r = rng(seed)
X, Y = [], []
for i in range(n):
c = i % 3
p = 1 + int(6 * r())
a = []
for y in range(8):
for x in range(8):
defect = (c == 1 and x == p) or (c == 2 and y == p)
a.append(0.2 + 0.7 * defect + noise * (2 * r() - 1))
X.append(a)
Y.append(c)
return torch.tensor(X).reshape(n, 1, 8, 8), torch.tensor(Y, dtype=torch.long)
def xcorr_numpy(x, w, b, stride=1, padding=0, dilation=1):
x = np.pad(x, ((0, 0), (padding, padding), (padding, padding)))
co, ci, kh, kw = w.shape
oh = (x.shape[1] - dilation * (kh - 1) - 1) // stride + 1
ow = (x.shape[2] - dilation * (kw - 1) - 1) // stride + 1
if min(oh, ow) < 1:
raise ValueError("invalid spatial shape")
y = np.zeros((co, oh, ow))
for o in range(co):
for i in range(oh):
for j in range(ow):
patch = x[:, i * stride:i * stride + dilation * (kh - 1) + 1:dilation, j * stride:j * stride + dilation * (kw - 1) + 1:dilation]
y[o, i, j] = (patch * w[o]).sum() + b[o]
return y
class TinyCNN(nn.Module):
def __init__(self, filters, seed):
super().__init__()
self.conv = nn.Conv2d(1, filters, 3)
self.head = nn.Linear(filters, 3)
r = rng(seed + 2000)
with torch.no_grad():
for p in [self.conv.weight, self.head.weight]:
p.copy_(torch.tensor([0.8 * (r() - 0.5) for _ in range(p.numel())]).reshape(p.shape))
self.conv.bias.zero_()
self.head.bias.zero_()
def forward(self, x):
return self.head(F.relu(self.conv(x)).mean(dim=(2, 3)))
def run(seed=3, filters=4, noise=0.12, lr=0.03, updates=100):
X, Y = dataset(48, seed, noise)
V, T = dataset(24, seed + 1000, noise)
model = TinyCNN(filters, seed)
opt = torch.optim.Adam(model.parameters(), lr=lr)
hist = []
for t in range(updates + 1):
if t % 10 == 0 or t == updates:
with torch.no_grad():
a, b = model(X), model(V)
pred = b.argmax(1)
cm = torch.bincount(3 * T + pred, minlength=9).reshape(3, 3)
hist.append(dict(t=t, tr=F.cross_entropy(a, Y).item(), va=F.cross_entropy(b, T).item(), acc=(pred == T).double().mean().item(), cm=cm.tolist()))
if t == updates:
break
opt.zero_grad(set_to_none=True)
F.cross_entropy(model(X), Y).backward()
opt.step()
return model, hist
if __name__ == "__main__":
X, _ = dataset(3, 3, 0.12)
m, h = run()
for s, p, d in [(1, 0, 1), (2, 1, 1), (1, 2, 2)]:
manual = xcorr_numpy(X[0].numpy(), m.conv.weight.detach().numpy(), m.conv.bias.detach().numpy(), s, p, d)
actual = F.conv2d(X[:1], m.conv.weight, m.conv.bias, stride=s, padding=p, dilation=d)[0].detach().numpy()
np.testing.assert_allclose(manual, actual, atol=1e-12)
for r in [h[0], h[-1]]:
print(r)