Press → to start · click the grid icon to jump to any slide
100%
Press → to start · click the grid icon to jump to any slide
Slide 1 / 36
Pinned slides 0
Pins stay while this tab is open, even after a refresh. Closing the tab clears them, so download to keep your notes; you’ll be warned before leaving if they haven’t been downloaded.
CS4337 · Deep Learning · Visual Recognition

Convolutional
Neural Networks

From handwritten checks to learned features, residual networks, and visual prediction
Interactive numerical labs · real browser training and inference · copyable PyTorch examples
Prepared by Keshav
CS4337 · 01 · History / 2

Before ImageNet: a long history

Yann LeCun’s late-1980s work made trainable convolutional networks practical for handwritten recognition.

1980

Kunihiko Fukushima’s Neocognitron established an influential hierarchical, locally connected predecessor.

1989

LeCun and colleagues at Bell Labs trained shared-weight networks with backpropagation to recognize handwritten ZIP-code digits.

1990s

CNN-based document recognition moved into commercial check-reading systems.

1998

LeNet-5 and graph transformer document systems were described in the landmark IEEE paper.

CNNs developed through contributions from many researchers, decades before the AlexNet architecture’s 2012 breakthrough. LeCun and colleagues helped make them practical by combining architectural constraints with gradient-based learning.
PyTorch · expand / copy reference code
from torch import nn lenet = nn.Sequential( nn.Conv2d(1, 6, 5), nn.Tanh(), nn.AvgPool2d(2), nn.Conv2d(6, 16, 5), nn.Tanh(), nn.AvgPool2d(2), nn.Flatten(), nn.Linear(16 * 5 * 5, 120), nn.Tanh(), nn.Linear(120, 84), nn.Tanh(), nn.Linear(84, 10)) # LeNet-inspired modern implementation; not the exact historical wiring.

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

CS4337 · 01 · History / 3

The banking breakthrough

A real industrial problem: turn handwritten amounts on US checks into reliable machine-readable records.

Scan checklocate amount
→
Segment / hypothesescandidate characters
→
CNN recognizerdigit scores
→
Sequence + rulesaccept or review

A deployed system, not only a digit demo

AT&T / NCR systems combined CNN recognition with segmentation and contextual constraints. Low-confidence readings could be sent to human review.

A major success

LeCun’s historical homepage reported an estimate of 10% of all checks written in the US read by a system he helped develop. This is a historical estimate, not a current market-share claim.

The business metric is the trade-off between automatic processing and costly wrong readings—not accuracy on isolated digits alone.
PyTorch · expand / copy reference code
import torch logits = lenet(torch.randn(8, 1, 32, 32)) confidence, digit = logits.softmax(-1).max(-1) review = confidence < 0.95 # illustrative threshold, not a calibrated policy

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

CS4337 · 02 · Mechanics / 4

Think in tensors

A feature map has a spatial grid and a channel axis. A batch adds one more dimension.

Conv2d · output channel 1 · row 0, column 0
Channel 1 of 6
Loading image…

Actual TensorFlow.js convolution · N = 1 · bias = 0 · Conv2d → optional activation → optional pooling. Filters are hand-designed or seeded random, not trained. Feature maps are revealed in row-major order as the selected channel is computed; later channels remain hidden until their turn. Spatial views use the same fixed pixels-per-cell scale. Each map is independently scaled for display; black = its minimum and white = its maximum. All three input channels contribute to each output.

Photo: “Pug sophie” — existentist · CC BY 3.0 · resized and channel-separated for this demonstration.

One output channel

One standard filter has shape Cin × K × K. Its dot product sums over spatial positions and all input channels.

Conventions matter

PyTorch images: NCHW. Browser / TensorFlow.js images: NHWC. This deck labels the layout when showing shapes.

A channel is a learned response field, not necessarily a named object or an RGB color.
PyTorch · expand / copy reference code
import torch from torch import nn x = torch.randn(4, 3, 32, 32) conv = nn.Conv2d(3, 64, 3, padding=1) y = conv(x) # (4, 64, 32, 32) print(conv.weight.shape) # (64, 3, 3, 3)

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

A CNN receives a batch tensor. PyTorch normally uses NCHW: batch, channels, height, width. Each output channel is produced by one learned filter spanning the connected input channels.

Track shapes whenever a layer changes channels or spatial size; most convolution mistakes are dimension or layout mistakes. A feature map is one channel of activations, while a filter is a set of weights that produces one output channel. They are related but are not the same object.

Thinking in tensors makes the computation easier to reason about: a pixel is not a single number but a channel vector, and a feature map is not the whole layer but one plane in its output tensor. The batch axis keeps independent examples together for efficient computation; it does not create connections between those examples. When a framework uses NHWC instead of NCHW, the meaning is unchanged even though the memory order and axis indices differ.

Key relationX ∈ RN×Cin×H×W → Y ∈ RN×Cout×Hout×Wout

For an examination, be able to name every axis and explain why a standard filter has shape Cin×Kh×Kw.

Reflection questions
  1. If the same image is stored as NCHW and NHWC, what changes mathematically and what changes only in representation?
  2. Why does one output feature map correspond to one filter rather than one input channel?
Verified against: PyTorch Conv2d ↗
CS4337 · 02 · Mechanics / 5

01 / Standard convolution: the sliding dot product

Follow the highlighted input and weight. Multiply, add, then write one output value.

Shapes, parameters, and full calculation

Hout = floor((H + 2P − D(K−1) − 1)/S) + 1. PyTorch calls this convolution, but computes cross-correlation: no kernel flip.
PyTorch · expand / copy reference code
layer = nn.Conv2d(Cin, Cout, kernel_size=K, stride=S, padding=P, dilation=D, groups=G, bias=True) y = layer(x) # Cout and Cin must both be divisible by G.

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

A 2D convolution computes a sliding dot product. At one output location, it multiplies a local input patch by a filter, sums over spatial taps and connected input channels, then optionally adds one bias.

Use it when nearby spatial patterns matter and the same detector should work at every image location. Unlike a dense layer, convolution reuses weights across positions. This preserves spatial structure and usually needs far fewer parameters.

Padding controls what happens near image boundaries, stride controls how densely outputs are sampled, and dilation controls the spacing between taps. None of these changes how many times a particular coefficient is learned: the filter remains shared across positions. Groups change channel connectivity, so they affect both the parameter count and the amount of arithmetic. Bias, when enabled, contributes one additional learned scalar per output channel rather than one per pixel.

Key relationHout = ⌊(H+2P-D(K-1)-1)/S+1⌋;   weights = Cout(Cin/G)KhKw

For an examination, given H, K, S, P, D, and G, compute the output size, parameter count, and which input channels feed one output channel.

Reflection questions
  1. How would increasing dilation while keeping K fixed change the sampled input positions and output size?
  2. Which hyperparameters change the number of learned weights, and which change only the number of output computations?
CS4337 · 02 · Mechanics / 6

One filter, reused at every position

Apply a fixed or custom filter to the pug photograph. The weights stay the same as the sampled patch moves.

Fixed demonstration filters, not trained weights · one input plane · stride 1 · zero padding 1 · bias 0. Output display is scaled symmetrically around zero: dark = negative, gray = zero, light = positive. Sampling marks do not change the image.

One shared kernel

If each position had its own kernel

Photo: “Pug sophie” — existentist, CC BY 3.0; resized and converted to a single input plane.

Moving the patch changes the input values, not the kernel weights. A CNN learns its filters during training, then reuses each filter across spatial positions. Different output filters have different weights.
PyTorch · expand / copy reference code
sobel_x = torch.tensor([[-1.,0.,1.],[-2.,0.,2.],[-1.,0.,1.]]) w = sobel_x[None, None] y = torch.nn.functional.conv2d(x, w) # The SAME w is used at every spatial location.

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Weight sharing means the same filter coefficients are applied at every valid spatial position. Training learns one detector that can respond wherever its pattern appears.

Use convolution when translation of a local pattern should not require a new parameter set for every location. Local connectivity limits each output to a neighborhood; weight sharing makes the detector reusable. A locally connected layer has local receptive fields but separate weights at each position.

Sharing is the source of convolution's strong inductive bias. The model assumes that a useful edge, texture, or part detector should remain useful after translation. This assumption greatly improves statistical efficiency, but it can be inappropriate when absolute position has special meaning. Boundary handling, downsampling, and later global aggregation also prevent a complete guarantee of translation equivariance in a practical network.

For an examination, distinguish translation equivariance from invariance: shifting the input shifts a convolutional feature map; pooling or aggregation may add approximate invariance.

Reflection questions
  1. What kind of dataset would make spatial weight sharing a harmful assumption?
  2. Why is convolution translation equivariant rather than automatically translation invariant?
Verified against: PyTorch Conv2d ↗
CS4337 · 02 · Mechanics / 7

Convolution as GEMM: unfold, multiply, reshape

GEMM = General Matrix–Matrix Multiplication. Each patch becomes a column. One flattened filter becomes a row. Their product gives all spatial outputs.

One input channel · one output filter · bias = 0. Gold marks the selected output position; amber cells are zero padding.

Patch columns × filter weights · inspect the actual matrices

All entries are included. Scroll horizontally or vertically for larger matrices; the active column is highlighted.

This is an exact mathematical reformulation. Libraries may use implicit GEMM, direct, Winograd, or FFT algorithms; they need not materialize the large patch matrix.
PyTorch · expand / copy reference code
import torch.nn.functional as F x = torch.arange(1., 10.).reshape(1, 1, 3, 3) w = torch.tensor([[[[1., 0.], [0., -1.]]]]) patches = F.unfold(x, kernel_size=2) # (1, 4, 4) y = (w.flatten(1) @ patches).reshape(1, 1, 2, 2) assert torch.allclose(y, F.conv2d(x, w))

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Unfold (im2col) copies every receptive-field patch into a column. Flattened filters form rows, so one matrix multiplication computes every output position before reshaping the result.

Use this view to derive convolution, debug indexing, or understand why optimized convolution can map to GEMM hardware. The result is exactly the same as direct convolution. Explicit im2col can duplicate data and consume memory, so libraries may use implicit GEMM, direct, Winograd, or FFT kernels instead.

The matrix view separates data rearrangement from arithmetic. Unfold determines exactly which input values belong to every receptive field, while the matrix product applies all filters to all patches in parallel. During backpropagation, gradients from overlapping columns must be accumulated back into their shared input locations. This explains why fold is a sum-over-overlaps operation rather than a simple inverse of unfold.

Key relationXcol ∈ R(CinKhKw)×(HoutWout); WrowXcol → Cout×(HoutWout)

For an examination, explain what one column represents, why columns overlap, and why reshaping restores the spatial output.

Reflection questions
  1. Where does one output pixel appear in Xcol, and what does one row of W represent?
  2. Why can explicit im2col be faster computationally yet more expensive in memory?
CS4337 · 02 · Mechanics / 8

Another view: the sparse operator A

Flatten the input instead. Copy the same kernel into shifted rows of a large, sparse matrix.

How PyTorch implements this in practice
nn.Conv2d / F.conv2d call a convolution backend; they do not build this dense A matrix. The backend selects a fast direct convolution, implicit GEMM, Winograd, FFT, or platform-specific kernel based on tensor shape, device, dtype, and available libraries. This avoids storing mostly-zero A while preserving the same mathematical result.

One input channel · one output filter · bias = 0. Gold marks the selected output position; amber cells are zero padding.

Shifted kernel rows × flattened input · inspect the actual matrices

All entries are included. Scroll horizontally or vertically for larger matrices; the active row is highlighted.

There are only K² kernel parameters even though the same weights appear repeatedly in A. A is an explanatory operator; storing it densely is wasteful.
PyTorch · expand / copy reference code
x_flat = x.flatten() A = torch.tensor([[1.,0,0,0,-1,0,0,0,0], [0,1,0,0,0,-1,0,0,0], [0,0,0,1,0,0,0,-1,0], [0,0,0,0,1,0,0,0,-1]]) y = A @ x_flat

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Convolution is a linear map y = Ax when the input and output are flattened. Each row of sparse A places a shifted copy of the same kernel weights at the input indices used by one output.

Use this operator view to reason about transposed convolution, adjoints, sparsity, and gradients. A is a mathematical construction, not a new set of learned weights. Repeated entries in A are tied to the same K² kernel values, so materializing dense A wastes memory.

The repeated diagonals and shifted rows of A expose two important properties: locality, because each row has only a small set of nonzero entries, and sharing, because those entries reuse the same kernel values. The transpose AT reverses the direction of information flow but does not compute A-1. This distinction is central when interpreting transposed convolution and convolutional gradients.

Key relationy = Ax;   transposed convolution applies AT to an output-shaped signal

For an examination, do not count every nonzero entry of A as a parameter. Count the unique shared kernel coefficients (plus optional bias).

Reflection questions
  1. Why does A contain many repeated numbers but only K² learned parameters in the single-channel example?
  2. What operation does AT perform, and why is it not generally A-1?
CS4337 · Convolution family / 9

02 / Grouped convolution

Split the channels into independent groups. Each output filter sees only the inputs in its own group.

Input stacks · 5 × 5Filter banks · 3 × 3 slicesOutput stacks · 3 × 3

Choose an output channel to bring its map and filter to the front. Matching colors show connectivity; there are no connections between groups. Highlighted input cells form the current 3×3 window. Toy inputs and weights are deterministic; output values are computed exactly.

PyTorch · expand / copy reference code

Matching configuration; PyTorch initializes its own random weights. The browser uses illustrative fixed weights.

Reflection

Grouped convolution partitions the input and output channels into equally sized groups. Each output filter spans every input channel within its group, sums their spatial dot products, and produces one output map. The same filter is reused at every spatial position. Both channel counts must be divisible by the number of groups.

With one group, this is standard convolution. With groups equal to the input-channel count, each filter sees just one input channel: this is depthwise convolution, provided the output count is an integer multiple of the input count. That multiple is the depth multiplier. Grouping reduces connectivity and weights; it does not by itself reduce the requested number of output channels or the output spatial size.

Grouping can lower computation and parameter cost, but information cannot cross group boundaries in this layer. A later ungrouped 1×1 convolution can mix the channels. The weight count is Cout × (Cin / G) × 3 × 3; this example disables bias. With stride 1 and no padding, a 5×5 input produces a 3×3 output.

Think of this as a regular convolution within each group, followed by concatenation of the output maps along the channel axis. Every group scans the full spatial grid; grouping partitions channels, not image regions. Its connectivity can be drawn as independent diagonal blocks. For fixed input/output sizes, both the weight count and convolution MAC count are reduced by a factor of G compared with an ungrouped layer.

AlexNet used grouped connections to split work across two GPUs; ResNeXt later emphasized the number of parallel groups (cardinality). Repeatedly keeping the same groups isolated restricts communication, so architectures can use an ungrouped pointwise layer or channel shuffling followed by further grouped layers to exchange information.

Reflection questions
  1. For six inputs and twelve outputs, which group counts are valid?
  2. What changes in connectivity and weight count when the number of groups doubles?
  3. Why does a depthwise layer commonly need a following pointwise layer?
  4. For three input and three output channels, why are only one or three groups valid?
  5. Sketch which input channels connect to which outputs for one group, two groups, and the depthwise case. Choose channel counts that allow each case.
CS4337 · 03 · Convolution family / 10

03 / Pointwise convolution (1×1)

A learned matrix mixes the channel vector at every sampled pixel, without looking at neighboring pixels.

Input feature planes3 × 8 × 8
→
1×1 convolutionmix channels at each sample
→
Output feature planes4 × Hout × Wout
Input stack
Input channel 2
Input channel 1
Input channel 0
3 planes · 8 × 8 each
→
Animated 1×1 kernelW has shape 4 × 3 × 1 × 1Select one pixel, then mix its three channel values.
→
Output stack
Output channel 3
Output channel 2
Output channel 1
Output channel 0
4 planes · 8 × 8 each

The gold square is one pointwise operation. Stride controls how far it jumps before applying the same 1×1 channel-mixing weights again.

y[:,h,w] = W x[:,h,w] + b

With stride 1 and padding 0, H and W stay the same. With stride 2 on an 8×8 input, the output becomes 4×4. A 1×1 layer can expand, compress, or mix channels; it cannot directly see neighboring pixels.

A 1×1 convolution with stride 2 can downsample. “Spatial size stays the same” assumes stride 1.
PyTorch · expand / copy reference code
pointwise = nn.Conv2d(32, 128, kernel_size=1, bias=False) y = pointwise(torch.randn(2, 32, 28, 28)) # (2,128,28,28)

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

A 1×1 convolution applies the same learned matrix to the channel vector at each sampled pixel. It changes or mixes channels without directly inspecting neighboring pixels.

Use it to compress or expand channels, build bottlenecks, or combine depthwise features efficiently. A spatial K×K convolution mixes neighbors and channels. A pointwise layer only mixes channels; stride greater than one may also downsample by sampling fewer locations.

At each pixel, the layer behaves like a small fully connected layer applied to the channel vector, with the same matrix reused over the entire image. A row of W defines one output channel, and its coefficients say how strongly that output uses each input channel. The layer can therefore learn combinations such as color opponency or recombine specialized feature detectors while retaining the current spatial coordinate.

Key relationy[:,h,w] = Wx[:,h,w]+b;   weights = CoutCin

For an examination, for 3 input and 4 output channels with bias disabled, state why W has shape 4×3 and exactly 12 learned parameters.

Reflection questions
  1. What can a 1×1 convolution learn that a per-channel scale cannot?
  2. How does stride 2 alter a pointwise layer's spatial behavior even though its kernel is 1×1?
Verified against: MobileNet ↗
CS4337 · 03 · Convolution family / 11

04 / Depthwise separable convolution

Factor one full convolution into a spatial stage, then a channel-mixing stage.

Same padding is assumed. Bias is off so the comparison isolates convolution weights and multiply-adds.

Why this works: depthwise convolution is grouped convolution at its maximum grouping: groups = Cin. It performs K×K spatial filtering independently in each channel. The following pointwise 1×1 convolution has groups = 1, so each output channel can combine all depthwise channels.
The weight-count ratio is 1/Cout + 1/K². Compute savings do not translate perfectly to wall-clock speed; hardware and memory access matter.
Example:Open In Colab
PyTorch · expand / copy reference code
separable = nn.Sequential( nn.Conv2d(4, 4, 3, padding=1, groups=4, bias=False), nn.Conv2d(4, 8, 1, bias=False))

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Depthwise separable convolution factorizes a standard convolution into depthwise spatial filtering followed by pointwise channel mixing.

Use it when compute, memory, or model size matters and some loss of cross-channel/spatial coupling is acceptable. It is cheaper than a regular convolution because it replaces CinCoutK² weights with CinK² + CinCout. It is not identical in representational form to one unrestricted convolution.

The factorization imposes a structural constraint: spatial patterns are first learned independently inside channels and only then recombined. That constraint lowers cost but can reduce expressiveness compared with an unrestricted K×K filter that jointly models space and channels. Modern efficient architectures compensate with nonlinearities, normalization, expansion layers, and repeated separable blocks.

Key relationstandard: CinCoutK²;   separable: CinK² + CinCout

For an examination, calculate both counts and explain which stage learns spatial patterns and which stage learns channel combinations.

Reflection questions
  1. Which interactions available to a standard convolution are restricted by the depthwise-separable factorization?
  2. For which values of Cin, Cout, and K is the relative saving largest?
Verified against: MobileNet ↗ · Xception ↗
CS4337 · 03 · Convolution family / 12

05 / Dilated (atrous) convolution

Spread the taps apart to see a wider field without adding weights.

Effective kernel width = D(K − 1) + 1
DeepLab uses atrous convolution for dense segmentation context. Repeated dilation patterns can leave sampling gaps; a larger receptive field is not the same as dense coverage.
PyTorch · expand / copy reference code
atrous = nn.Conv2d(64, 64, 3, dilation=2, padding=2) # Nine spatial weights span a 5×5 input region.

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Dilated convolution inserts gaps between sampled kernel taps. It enlarges the receptive field without increasing the number of kernel weights.

Use it when dense prediction needs more context while retaining a relatively high-resolution feature map. Increasing kernel size also enlarges context but adds parameters; dilation preserves K² weights. Large repeated dilation patterns can create gridding gaps, so practical models often vary dilation rates.

Dilation is especially useful when the output must remain dense, because it increases context without an immediate pooling step. However, widely spaced taps may miss fine structures between sampled locations. Combining several dilation rates or mixing dilated and ordinary convolutions helps cover both local detail and broad context, which is why atrous spatial-pyramid designs use parallel rates.

Key relationeffective kernel size Keff = D(K-1)+1

For an examination, compute Keff and then use it in the normal output-size formula. Dilation changes sampled spacing, not the learned-weight count.

Reflection questions
  1. How can two layers with the same parameter count have different receptive fields?
  2. What spatial patterns might be missed when the dilation rate becomes too large?
CS4337 · 03 · Convolution family / 13

06 / Transposed convolution: scatter, add, reshape

As unfold turns convolution into gather-and-multiply, transposed convolution lets each input scale a shifted kernel column. The contributions add into the output.

One input channel · one output filter · bias = 0 · output_padding = 0. Gold marks the selected input and its scattered kernel taps.

Aᵀ columns × input activations · inspect the actual matrices

Each column is one shifted copy of the kernel. The active column is multiplied by the selected input value.

Transposed convolution applies the adjoint connection pattern Aᵀ: it reverses the forward weighted connections, but it is not A⁻¹ and does not restore information that A discarded. In backpropagation, the same relationship appears as ∂L/∂x = Aᵀ(∂L/∂y).
PyTorch · expand / copy reference code
import torch import torch.nn.functional as F v = torch.arange(1, 5, dtype=torch.float32).reshape(1, 1, 2, 2) w = (torch.arange(9, dtype=torch.float32) % 3 - 1).reshape(1, 1, 3, 3) z = F.conv_transpose2d(v, w, stride=2, padding=0)

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript lab does.

Reflection

Transposed convolution applies the transpose of the linear operator associated with convolution: input values scatter weighted contributions into an output grid, and overlaps add.

Use it for learned spatial upsampling in decoders and generative networks when the upsampling kernel should be trainable. It is not an inverse convolution and does not reconstruct lost information automatically. Resize-then-convolve offers more explicit interpolation and can reduce checkerboard artifacts.

Each input cell writes a scaled copy of the kernel into the output canvas. When copies overlap, their contributions add, so the pattern of overlap matters. If the kernel size is not well matched to stride, some output locations receive more contributions than others, which can produce checkerboard structure. A following convolution after explicit interpolation offers another learnable decoder design with more uniform initial coverage.

Key relationHout=(Hin-1)S-2P+D(K-1)+output_padding+1

For an examination, explain scatter-and-add, distinguish output_padding from actual zero padding, and know why uneven overlap can create checkerboards.

Reflection questions
  1. How does overlap in scatter-and-add depend on kernel size and stride?
  2. Why can output_padding resolve a shape ambiguity without behaving like ordinary padding?
CS4337 · 03 · Convolution family / 14

07 / 3D convolution

A Conv3d kernel reads the same spatial neighborhood in adjacent video frames, then writes one value into a spatiotemporal output volume.

Conv3d: K=3 × 3 × 3 · stride=(1,1,1) · padding=(0,1,1)
output (t=0, y=0, x=0)

RGB kernel anatomy

PyTorch stores weights as [Cout, Cin, Kt, Kh, Kw]. With RGB, each output filter owns three 3D slices—one each for R, G, and B—and sums all three.

Why odd kernel sizes?

Sizes such as 3, 5, and 7 have one unambiguous center voxel. Symmetric padding can then keep that center aligned with the output position.

Why square or cubic?

Equal spatial sides avoid favoring one direction and simplify design and optimization. Rectangular or anisotropic kernels are still useful when space and time have different scales.

Time remains an ordered axis. A 3D kernel shares one learned weight volume across clip positions, so it can respond to changes that no single frame reveals.
Example:Open In Colab
PyTorch · expand / copy reference code
import torch from torch import nn clip = torch.randn(2, 3, 3, 36, 48) # N, C, D, H, W conv3d = nn.Conv3d(3, 8, kernel_size=(3, 3, 3), padding=(0, 1, 1), bias=False) y = conv3d(clip) # (2, 8, 1, 36, 48)

Copyable Python reference code. The JavaScript lab crops the first ten frames from the cited sequence and computes every displayed padded, stride-1 output locally.

Reflection

A 3D convolution slides through depth/time as well as height and width. Each filter spans all connected input channels and a Kd×Kh×Kw volume.

Use it for video clips, volumetric medical scans, or other data where nearby slices or frames contain meaningful local structure. Stacking frames as channels loses explicit translation along time. Conv3d preserves a depth/time axis and shares the kernel as it moves through that axis, but costs more memory and compute.

For video, the depth axis normally represents time; for CT or MRI, it represents physical slices. A temporal kernel can detect motion or change because it observes several neighboring frames at once. Kernel depth should reflect the sampling rate and phenomenon being modeled: a very short temporal window may miss slow motion, while a large one increases computation and may blur distinct events.

Key relationweights = Cout(Cin/G)KdKhKw

For an examination, separate the channel axis from the depth/time axis, then compute Dout, Hout, and Wout independently.

Reflection questions
  1. Why should frames usually form a depth/time axis rather than be treated as unrelated channels?
  2. How would changing temporal stride affect motion information and output depth?
Verified against: PyTorch Conv3d ↗ · I3D ↗
CS4337 · 03 · Convolution family / 14

08 / Causal convolution

At time t, use only the present and past. Never leak future values into the prediction.

WaveNet stacks dilated causal convolutions to grow temporal context efficiently.

For next-step forecasting, shift targets by one step. Causality in a layer alone does not prevent leakage elsewhere in preprocessing.
PyTorch · expand / copy reference code
K, D = 3, 2 conv = nn.Conv1d(16, 32, K, dilation=D) x = torch.randn(2, 16, 100) y = conv(F.pad(x, (D * (K - 1), 0))) # left padding only

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

A causal convolution prevents an output at time t from using future inputs. Padding and masking arrange the receptive field entirely at or before t.

Use it for autoregressive generation, streaming inference, forecasting, or any task where future information is unavailable or would leak the answer. A centered convolution sees both past and future and is appropriate for offline sequence labeling. Causality is about information flow, not merely using Conv1d.

Causality is a constraint on dependency rather than a special learned parameter. During training, a mask or asymmetric padding must enforce the same information restriction that will exist during generation or streaming. Dilated causal stacks are attractive because their history grows quickly while computation remains parallel across known training positions, unlike strictly sequential recurrent updates.

Key relationy[t] depends only on x[t], x[t-1], …; with dilation D and kernel K, history span = D(K-1)+1

For an examination, given a stack of dilated causal layers, trace which earlier time steps can influence one output and verify that no future index appears.

Reflection questions
  1. Which input indices may influence y[t] in a two-layer dilated causal network?
  2. What leakage would occur if symmetric padding were used carelessly during forecasting?
Verified against: WaveNet ↗
CS4337 · 03 · Convolution family / 15

09 / Spectral and graph convolution

“Convolution” can be defined through a Fourier basis or a graph Laplacian instead of a rectangular pixel grid.

Frequency domain

y = ℱ⁻¹(ℱ(k) ⊙ ℱ(x))

Zero-padding is needed for linear convolution via FFT; unpadded multiplication corresponds to circular convolution.

Graph domain

H′ = σ(Â H W)
 = D̃⁻½ (A+I) D̃⁻½

A GCN propagates normalized neighbor information. Its local rule is motivated by approximating spectral graph filters.

Nodes + edges
→
Neighbor aggregation
→
Channel mixing
→
New node features
edge_index describes connectivity; it is not a Fourier transform. The common GCN layer avoids explicit Laplacian eigendecomposition.
PyTorch · expand / copy reference code
# Requires torch-geometric from torch_geometric.nn import GCNConv gcn = GCNConv(in_channels=16, out_channels=32) y = gcn(node_features, edge_index) # node_features: [num_nodes,16]; edge_index: [2,num_edges]

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Spectral convolution multiplies Fourier coefficients; graph convolution aggregates information according to graph connectivity or a graph-derived operator. Both generalize structured filtering beyond a regular image grid.

Use FFT methods for large/global or periodic filters when frequency-domain multiplication is advantageous; use graph convolutions for meshes, molecules, social networks, and irregular neighborhoods. Image convolution assumes a regular translation grid. Graph neighborhoods vary by node, while spectral methods define filtering through basis functions or eigenvectors and may have different localization costs.

The Fourier convolution theorem can make very large convolutions efficient, but transforming into and out of the frequency domain has overhead, so small image kernels are often faster with specialized spatial kernels. Graph convolution replaces the regular image neighborhood with edges from an adjacency structure. Its meaning therefore depends on how the graph is built and normalized, not only on the learned weight matrix.

Key relationspatial convolution: y=x*k;   Fourier theorem: F(y)=F(x)⊙F(k);   GCN: H'=σ(D̂-1/2ÂD̂-1/2HW)

For an examination, state the domain, the neighborhood definition, and whether the method is local, global, or graph-structured before comparing costs.

Reflection questions
  1. When can FFT overhead outweigh its asymptotic advantage?
  2. How does changing a graph's adjacency matrix change the meaning of one graph-convolution layer?
Verified against: GCN ↗ · PyTorch FFT ↗
CS4337 · 04 · Building blocks / 17

Pooling: summarize a neighborhood

Max pooling preserves the strongest response; average pooling measures the average response.

Pooling has no learned weights. Downsampling loses spatial detail and may alias; it is a design choice, not a mandatory CNN layer.
PyTorch · expand / copy reference code
max_pool = nn.MaxPool2d(2, stride=2) avg_pool = nn.AvgPool2d(2, stride=2) y = max_pool(torch.randn(4, 64, 32, 32)) # (4,64,16,16)

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Pooling summarizes each local window. Max pooling retains the strongest response; average pooling retains the mean. Pooling has no learned weights unless embedded in a learned mechanism.

Use it to downsample, enlarge later receptive fields, reduce compute, or aggregate a fixed-size summary. A strided convolution learns how to downsample and may change channels. Pooling uses a fixed reduction and normally preserves channel count; it trades precise spatial layout for compactness.

Max pooling answers whether a strong feature occurred in a window, whereas average pooling answers how much of that feature was present on average. Both reduce spatial precision, and repeated pooling can remove small objects or boundary detail. Modern networks sometimes replace pooling with strided convolution so that downsampling itself is learned, but this adds parameters and does not automatically preserve more information.

Global average pooling averages the entire spatial map independently for each channel. An N × C × H × W tensor becomes N × C × 1 × 1. It provides a compact fixed-length descriptor for a classification head even when spatial input size varies, subject to the backbone’s constraints. It discards spatial layout and can dilute a small localized response. Max pooling is useful for retaining strong local detections; local average pooling summarizes distributed responses more smoothly. Neither guarantees translation invariance or preserves all useful detail.

For an examination, compare max, average, adaptive, and strided-convolution outputs; know that pooling is generally not invertible.

Reflection questions
  1. Which pooling choice better preserves weak repeated evidence, and which preserves one strong response?
  2. What information would be required to invert a pooling operation?
Verified against: PyTorch pooling layers ↗
CS4337 · 04 · Building blocks / 18

BatchNorm2d vs LayerNorm: which axes define “normal”?

Both standardize activations and can then learn γ and β. They differ in which values share statistics, whether behavior depends on the batch, and where they fit in an architecture.

Xi denotes the temporary activation tensor produced by layer i. Open a PyTorch tab to compute its statistics and normalized output explicitly. correction=0 matches the displayed population-variance formulas; keepdim=True retains axes for broadcasting.

BatchNorm2d

Stabilize each feature channel

Uses that channel’s values across N×H×W. It suits classic CNN stages, but training statistics depend on the mini-batch.

LayerNorm over C×H×W

Stabilize each whole sample

Uses all channels and pixels within one image. It is batch-independent, while strong regions can influence the sample-wide scale.

LayerNorm over C only

Stabilize each pixel’s feature vector

Uses the channels at each (n,h,w) independently. It preserves separate spatial positions and fits token-style vision blocks.

Normalize first, then choose a useful scale and offset

γ scales; β shifts. They let the network choose how normalized responses should reach the next layer, rather than forcing every response group to stay standardized. For example, β can change which values pass through ReLU. They do not guarantee prevention of overfitting, dead neurons, or vanishing gradients. ε is the numerical safeguard when variance is very small.

Off: output is x̂ (equivalent to γ = 1, β = 0); no affine tensors are stored. Frozen parameters: existing γ and β are still applied, but not updated. Evaluation mode: a separate setting; it does not turn off the affine transformation.

BatchNorm2d · one statistic pair per channel

Training computes statistics across N, H, W. Evaluation normally uses running statistics. The same γ and β are reused at every pixel and in every sample within a channel.

LayerNorm

Statistics come from each example in both training and evaluation. The axes used to compute statistics and the positions with distinct learned parameters are different concepts.

QuestionBatchNorm2dLayerNorm
What is standardized?Each channel using N,H,W samplesEach sample using chosen feature axes
Train vs evaluation?Batch statistics → running statisticsSame per-sample calculation in both
Prefer when…Classic CNN; moderate batch; efficient deploymentMicro-batch, transformer/hybrid, variable batch
Main tradeoffBatch coupling and train/eval stateAxis/layout choice and possibly more affine values

If a model contains both

Convolutional stageConv → BatchNorm2d → activationthen reshape / patchifyToken or transformer stageLayerNorm → attention or MLP → residual add

Keep each normalization local to the block it was designed for. Avoid placing BatchNorm and LayerNorm directly back-to-back: the second normalization largely redefines the scale produced by the first. There is no universal BN→LN or LN→BN rule for the same activation; treat that as an architecture choice requiring an ablation.

Learned versus calculated: γ and β are trainable affine parameters. μ and σ² are calculated statistics. BatchNorm running statistics are state buffers, not optimizer-trained parameters. ε is fixed. Affine ON adds learned scale and shift; affine OFF retains normalization with no learned affine parameters. Freezing affine parameters and switching to evaluation mode are separate operations.
BatchNorm2d is a channel-wise CNN prior with batch-dependent training statistics. LayerNorm is sample-wise and batch-independent. Neither is universally stronger: choose the statistics that match the architecture, batch regime, tensor layout, and deployment behavior.
PyTorch · expand / copy reference code
# Manual tensor operations for X_i; updated by the slide controls.

Copyable Python reference code. The browser updates axes, parameter counts, and example ordering; Python does not execute inside this HTML.

Reflection

BatchNorm2d computes one mean and variance per channel over N, H, and W. LayerNorm computes statistics over the chosen trailing dimensions for each sample. Learnable γ and β restore affine flexibility; ε is numerical stabilization.

Use BatchNorm in many CNNs with reliable batch statistics; use LayerNorm when batch size varies or in architectures that normalize within each example. BatchNorm uses running estimates at evaluation and couples examples during training. LayerNorm uses the current example in both modes. Applying both sequentially is uncommon unless an architecture gives a specific reason.

The choice of axes determines which variations are removed. BatchNorm treats all pixels and examples for one channel as samples from the same training-time distribution; LayerNorm standardizes selected features inside each example. The affine parameters do not undo normalization: they let the network learn a useful scale and offset after standardization. Small or non-independent batches make BatchNorm statistics noisy, while LayerNorm remains independent of other batch members.

Key relationBN: μc=(NHW)-1Σn,h,wxnchw;   x̂=(x-μ)/√(σ²+ε);   y=γx̂+β

For an examination, for NCHW input, state the reduction axes and statistic shapes: BN has C statistics; full CHW LayerNorm has N independent statistic pairs.

Reflection questions
  1. Which examples influence one BatchNorm statistic during training?
  2. How would BatchNorm and LayerNorm behave differently when batch size becomes one?
CS4337 · 04 · Building blocks / 19

Activations make the network nonlinear

Without nonlinearities, compositions of linear layers collapse into one linear operation.

ReLU clips negative values; Leaky ReLU retains a small negative slope. Sigmoid and tanh saturate at large input magnitudes.
PyTorch · expand / copy reference code
relu = nn.ReLU() leaky = nn.LeakyReLU(negative_slope=0.1) sigmoid = nn.Sigmoid() tanh = nn.Tanh() # For multiclass training: raw logits → CrossEntropyLoss (no extra softmax).

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

An activation applies a nonlinear function after a learned affine operation. Without nonlinearities, stacked convolutions collapse to one linear operator and cannot model complex decision boundaries.

ReLU is a simple CNN default; leaky variants preserve a small negative slope; sigmoid is useful for independent probabilities or gates; softmax converts logits into a categorical distribution. ReLU is cheap but can produce inactive units. Smooth activations such as GELU have different gradient behavior. The output task, not visual preference, determines sigmoid versus softmax.

An activation also shapes optimization. Saturating sigmoid or tanh regions produce small gradients, while ReLU keeps a constant positive-side derivative but discards negative responses. The final layer has a different purpose from hidden activations: it must match the semantics of the target and loss. For example, raw logits are preferred by cross-entropy implementations because they can combine softmax and logarithms stably.

Key relationReLU(x)=max(0,x);   σ(x)=1/(1+e-x);   softmax(z)i=ezi/Σjezj

For an examination, explain why nonlinearity is essential and match an output activation/loss to multiclass versus multilabel prediction.

Reflection questions
  1. Why would a network containing only linear layers remain linear regardless of depth?
  2. Which output activation and loss would you choose for mutually exclusive versus independent labels?
CS4337 · 04 · Building blocks / 20

Regularization lab: drop paths or shrink weights

Use the same pug input to distinguish activation regularization from parameter regularization. Select one method to activate its visualization.

How to read the kernel bars: each kernel uses its own original maximum magnitude as the fixed ±1 display scale. The cyan “next” label reports the numerical update, so changes remain visible even when a large coefficient makes the bar-height change subtle.

Why are there two L1 update equations?

Subgradient SGD directly differentiates the combined objective:

Ltotal = Ltask + λ‖w‖1
wnext = w − η∇Ltask − ηλ sign(w)

The sign depends on the weight: positive weights receive +λ inside the gradient, while negative weights receive −λ. Either way, the update pulls toward zero. A small weight can cross zero and oscillate around it.

Proximal gradient first takes the task step and then applies soft thresholding:

z = w − η∇Ltask
wnext = sign(z) max(|z| − ηλ, 0)

Example: if z = 0.02 and ηλ = 0.05, subgradient SGD crosses to −0.03, whereas soft thresholding sets the coefficient exactly to zero. This makes the proximal form useful when exact sparsity is the goal.

In this lab: enable Soft threshold for the proximal rule or disable it for ordinary subgradient SGD. Both include the toy task gradient.
Dropout changes the activation pathway on each training pass. L1, L2, and Elastic Net leave the forward-path structure intact and instead change the optimization objective or parameter update. Dropout randomness is disabled at inference; the weights learned under regularization remain.
PyTorch · expand / copy reference code
import torch from torch import nn drop = nn.Dropout(p=0.3) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4) logits = model(images) l1 = 1e-5 * sum(p.abs().sum() for p in model.parameters()) loss = nn.functional.cross_entropy(logits, labels) + l1 loss.backward() optimizer.step()

The browser runs a labeled toy simulation. The PyTorch block is reference code and can be copied.

Reflection

Dropout regularizes activations by sampling paths during training. L1, L2, and Elastic Net regularize weights by adding penalties to the task loss; optimizer details determine the exact update.

Use dropout to reduce co-adaptation; L1 to encourage exact sparsity; L2/weight decay to discourage large weights; Elastic Net when both sparsity and shrinkage are useful. L1 exerts roughly constant-magnitude pull and can reach zero. L2 pull grows with |w| and usually shrinks smoothly. Decoupled weight decay is not always identical to adding L2 to the loss for adaptive optimizers.

Regularization changes the preference among solutions that fit the training data. Dropout injects multiplicative noise into intermediate representations; weight penalties change the optimization objective or parameter update. Their effects are not guaranteed to match a simple visual story for every weight, because the task gradient acts at the same time. A coefficient can still grow under L2 if the task gradient pushing it outward is stronger than the shrinkage term.

Key relationL=Ltask+λ1Σ|w|+(λ2/2)Σw²;   ∇wL2=λ2w

For an examination, distinguish activation regularization from parameter regularization, and explain subgradient versus proximal L1 updates without treating them as the same algorithm.

Reflection questions
  1. Can a weight increase after an L2-regularized training step? What competing terms determine the result?
  2. How do a subgradient L1 step and a proximal soft-threshold step differ near zero?
Verified against: Dropout ↗ · AdamW ↗
CS4337 · Building blocks / 21

Building a convolution block

A common starting point, with deliberate choices for normalization, nonlinearity, and downsampling.

Why bias=False before BatchNorm?

A convolution bias adds the same number to every spatial value in one output channel. During training, BatchNorm subtracts that channel’s mean, cancelling this constant offset. Its learned β already supplies a new offset.

(z + b) − mean(z + b) = z − mean(z)

Disable convolution bias when BatchNorm directly follows it. BatchNorm still learns γ and β. Do not simply remove bias from an already trained model without adjusting its stored statistics.

BatchNorm or LayerNorm?

Usually choose one normalization suited to the architecture. BatchNorm pools statistics across batch and space per channel; small or unrepresentative batches can make its statistics unreliable. LayerNorm uses each example’s configured axes and has no running batch statistics.

Channel-only LayerNorm normalizes across channels at each pixel. Per-channel convolution biases do not generally cancel under this normalization, so the BatchNorm bias rule does not carry over. In PyTorch, LayerNorm(C) needs C as the last tensor dimension.

Reflection

A useful conventional block is convolution, BatchNorm, activation, and optional downsampling. Convolution learns spatial and channel combinations, normalization controls the scale and offset of its responses, and an activation makes the transformation nonlinear. A stack of linear operations alone cannot supply the same expressive power. Pooling reduces spatial resolution only when the architecture needs it; it is not required after every convolution.

There is no single correct order for all CNNs. Preactivation residual networks put normalization and activation before convolutions, while ConvNeXt uses depthwise convolution, channel-wise LayerNorm, channel expansion, GELU, projection, and a residual addition. These are designed blocks, not arbitrary permutations. When reproducing an architecture, preserve its specified order. Do not routinely stack BatchNorm and LayerNorm as though both were required.

Choose either pooling or a strided convolution for a planned downsampling stage unless two reductions are intended. Repeated downsampling can erase small objects and boundaries. Residual additions require matching shapes, sometimes via projection; global average pooling belongs near a classification head when spatial layout is no longer needed. Dropout or stochastic depth are optional regularizers with placement and strength chosen for the architecture.

For BatchNorm, training uses batch statistics and evaluation normally uses running statistics. Use model.train() and model.eval() appropriately. LayerNorm uses input-derived statistics in both modes. Shape tracing, correct channel axes, a suitable normalization, and a verified implementation matter more than treating one block ordering as universal.

Reflection questions
  1. Why is the convolution bias redundant before BatchNorm but not generally before channel-only LayerNorm?
  2. What happens to spatial size if stride-2 convolution and stride-2 pooling are both applied?
  3. When would preserving resolution be more useful than early downsampling?
Example:Open In Colab
PyTorch · expand / copy reference code
CS4337 · Architecture overview / 22

CNNs: One Backbone, Multiple Applications

A Convolutional Neural Network (CNN) extracts hierarchical visual features that can support a wide range of computer vision tasks.

1 · Feature extraction (encoder)

Convolutional blocks typically reduce spatial dimensions (H × W) while increasing feature channels (C), learning increasingly complex visual patterns.

2 · Shared feature representation

Feature maps—for example, 2048 × 7 × 7 in C × H × W order—encode high-level visual information. Dense tasks may also use earlier, higher-resolution maps.

3 · Task-specific prediction heads

The head transforms these features into the output required by the task. The backbone and head are normally trained or adapted together for that task.

Classification

Predicts image-level class scores, converted to probabilities when needed.

Object detection

Locates and classifies objects using bounding boxes.

Segmentation

Assigns pixel-level labels or individual object masks.

Depth & optical flow

Estimates scene geometry and pixel motion.

Reconstruction & super-resolution

Generates or enhances images using decoder networks.

Keypoints & embeddings

Predicts landmark locations or compact feature vectors.

Key takeaway: The CNN backbone learns visual representations; the prediction head determines what the network does with those features.
CS4337 · 05 · Learning & looking inside / 23

Smaller maps, more channels, a wider view

Fixed-size kernels remain local within each layer, while deeper activations integrate increasingly large regions of the original image.

Blind observers touching different elephant parts, followed by a CNN hierarchy whose spatial maps shrink, channels increase, and receptive fields grow
Blind-observer analogy and receptive-field hierarchy · click to enlarge
Big elephant + small hand gives a local clue. A smaller elephant + the same hand gives broader context. In a CNN, smaller feature maps and stacked local operations let deep spatial activations integrate wider context, while many channels carry complementary learned evidence.
PyTorch · expand / copy reference code
encoder = nn.Sequential( nn.Conv2d(3, 64, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(128, 256, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(256, 512, 3, stride=2, padding=1), nn.ReLU(), ) # Spatial size: 224 → 112 → 56 → 28 → 14 # Channels: 3 → 64 → 128 → 256 → 512 # Every convolution still uses a local 3×3 kernel.

Copyable Python reference code. ReLU changes values, not receptive-field geometry.

Reflection

The receptive field of a deeper unit is the region of the original image that can influence it. Repeated convolution and downsampling let fixed small kernels integrate evidence from progressively larger regions.

Use receptive-field reasoning when a prediction needs sufficient context, especially in detection, segmentation, and dense prediction. More channels provide more learned feature types; they do not themselves enlarge the spatial receptive field. Depth, kernel size, stride, pooling, and dilation control receptive-field growth.

A deeper feature channel should not be interpreted as a literal picture of one object part in every case. It is a distributed learned response whose meaning emerges together with other channels. Downsampling makes each remaining cell summarize a larger input region, while additional channels provide capacity for more response types. The elephant analogy is useful for local evidence, but the network combines overlapping, learned measurements rather than independent verbal descriptions.

Key relationjump jl=jl-1Sl;   receptive field rl=rl-1+(Keff,l-1)jl-1

For an examination, differentiate theoretical receptive field from effective receptive field: all positions may be reachable, but influence is often concentrated near the center.

Reflection questions
  1. Does adding channels alone enlarge the receptive field?
  2. Why can the effective receptive field be smaller than the theoretical receptive field?
CS4337 · 04 · Building blocks / 24

After the backbone: flatten or global pool?

The task determines the head: classification may collapse space, while dense prediction must return a spatial field.

Flatten → fully connected

  • Pro: preserves which channel and spatial cell produced each value.
  • Con: parameter-heavy and tied to the selected H × W.

Global pool → fully connected

  • Pro: far fewer parameters; one head accepts different valid H × W.
  • Con: discards the exact spatial arrangement within each channel.
Official YOLOv1 architecture: convolutional feature extractor followed by fully connected detection layers
YOLOv1 architecture from the original paper.
Object detection

YOLOv1 preserves a 7 × 7 detection grid

448 × 448 image → convolutional backbone → 7 × 7 × 1024 → flatten → FC 4096 → FC 1470 → reshape 7 × 7 × 30.

Each grid cell predicts boxes, object confidence, and class scores. YOLOv1 therefore does not use global pooling: collapsing the 7 × 7 grid would erase which cell owns each detection. Newer YOLO families generally use fully convolutional, multi-scale detection heads rather than YOLOv1’s two fully connected layers.

Output: N × 7 × 7 × 30

Redmon et al., YOLOv1 ↗

MobileNet-v1 body architecture table ending in average pooling and a fully connected classifier
MobileNet-v1 body architecture, Table 1 of the paper.
Image classification

MobileNet-v1 really does use global average pooling

Depthwise 3 × 3 filters handle cheap spatial processing; pointwise 1 × 1 convolutions mix channels. The final feature tensor is 7 × 7 × 1024. A 7 × 7 average pool produces 1 × 1 × 1024, then an FC layer produces 1000 ImageNet logits.

Pool parameters0
FC parameters1024 × 1000 + 1000 = 1,025,000

This head accepts other valid spatial sizes when implemented with adaptive global pooling, because it always returns one number per channel.

Output: N × 1000

Howard et al., MobileNets ↗

U-Net encoder decoder architecture with skip connections
U-Net: encoder, bottleneck, decoder, and matching-resolution skip connections.
Semantic segmentation

U-Net keeps and restores spatial layout

The contracting path increases semantic context while shrinking H and W. The expanding path upsamples. Skip connections copy fine, same-resolution encoder features into the decoder so object boundaries are not reconstructed from the bottleneck alone.

Flattening or global pooling would destroy the per-pixel correspondence required by segmentation. A final 1 × 1 convolution maps the decoder features to K class logits at every pixel.

Output: N × K × H × W

Ronneberger et al., U-Net ↗

FlowNet encoder decoder architecture with conv6, coarse flow predictions, upconvolutions and skip connections
FlowNetS-style coarse-to-fine optical-flow decoder.
Dense motion

conv6 is the deepest backbone feature; the decoder refines a flow pyramid

The encoder forms progressively smaller feature maps through conv1 … conv6. A coarse flow is predicted at conv6, then upconvolutions combine that prediction with higher-resolution encoder features and refine it at flow5, flow4, flow3, and flow2.

This is a multi-resolution feature/prediction pyramid: several scales represent the scene, and coarse motion guides finer estimates. It predates and differs from the named FPN detection neck, but uses the same coarse-to-fine idea.

Final dense field: N × 2 × H × W · channels are horizontal u and vertical v motion

Dosovitskiy et al., FlowNet ↗

Coarse and refinement encoder decoder network for image inpainting
Image-to-image inpainting with coarse and refinement networks.
Image reconstruction

An encoder–decoder predicts pixels, not one class vector

The encoder compresses local texture and wider context into learned features. The decoder expands those features back to a spatial image. This example uses a coarse prediction followed by a refinement network; autoencoders and VAEs use the same broad encode–latent–decode pattern, although a VAE additionally learns a probabilistic latent distribution.

No global classifier pool is used at the end because the network must emit a value for every output location. Depending on the task, the last convolution commonly produces one grayscale channel or three RGB channels.

Output: N × Cout × H × W

Architecture image source ↗

Ten classes: scores are not probabilities

Linear layer → 10 logits → optional probability conversion. Each row is a different sample. Edit its scores and compare both conversions side by side in class space.

Batch size11–10 samples · 10 classes per row · edit any logit

Logits · [N, 10]

Signed scores, −5 to +5

Softmax · [N, 10]

Computed independently per sample across classes

Divide by score sum · [N, 10]

zᵢ / Σzⱼ · not an arithmetic mean; may give invalid probabilities

pi=ezi−m∑j=110ezj−m,m=maxjzj,∑i=110pi=1

Subtracting the largest logit keeps computation stable without changing the probabilities.

Why softmax? Dividing scores by their sum can produce negative values, values above 1, or division by zero. Softmax first maps signed scores to positive values, then normalizes. It preserves score ranking and depends on score differences; adding the same constant to every score changes nothing.

When to use softmax: when displaying class probabilities, sampling a class, or supplying probabilities to a downstream calculation for mutually exclusive classes. It is unnecessary for choosing the largest-score class: argmax is unchanged. High probability does not guarantee correctness; independent multi-label outputs generally use sigmoid.

PyTorch · train with logits; convert only when needed

CrossEntropyLoss expects raw prediction logits and has no from_logits switch. Do not apply softmax before it. It performs the stable log-softmax-based calculation internally. Class-index targets below are integer labels, not logits.

import torch import torch.nn.functional as F logits = torch.tensor([[2., -1., 0., 3., -2., 1., .5, -.5, 2.5, -3.]], requires_grad=True) # [1, 10] target = torch.tensor([3], dtype=torch.long) # [1] loss = F.cross_entropy(logits, target) # scalar [] # Prediction label: no softmax needed. predicted_class = logits.argmax(dim=1) # [1] # Convert when displaying or using probabilities. probs = torch.softmax(logits.detach(), dim=1) # [1, 10] probability_sum = probs.sum(dim=1) # [1], approximately 1 # Do NOT pass probs to cross_entropy as the prediction input.

Reference: PyTorch CrossEntropyLoss ↗

Flatten gives the classifier a separate weight for every channel and spatial position. Global pooling gives it one value per channel. The choice trades spatial detail and parameter capacity for size flexibility and efficiency.
PyTorch · expand / copy reference code
from torch import nn # Assume the backbone returns [N, 64, 7, 7]. flat_head = nn.Sequential( nn.Flatten(), nn.Linear(64 * 7 * 7, 1000), ) gap_head = nn.Sequential( nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 1000), )

Copyable Python reference code. The browser diagram updates the tensor shapes and parameter counts.

Reflection

Flatten preserves every spatial cell before a dense layer; global average pooling reduces each channel to one number before classification.

Use flatten when the head must depend on a fixed spatial arrangement. Use global pooling for fewer parameters, varying compatible input sizes, and channel-level evidence summaries. Flatten retains layout but its dense layer scales with H×W and fixes the expected feature-map size. Global pooling discards location and uses only C features, so it is compact but unsuitable when exact spatial arrangement is essential.

Suppose a backbone outputs C feature maps. Flatten asks the classifier to learn a separate coefficient for every channel-location pair, so moving the same feature to a different position changes the dense input coordinate. Global pooling summarizes each channel first, making the head indifferent to that within-channel location. This is often suitable for whole-image classification but unsuitable as the only head for detection or segmentation, where location is part of the answer.

Key relationflatten head weights=(CHW)Cclasses;   GAP head weights=CCclasses

For an examination, given C, H, W, and class count, compute both parameter counts and identify what information GAP removes.

Reflection questions
  1. What spatial distinctions can a flatten head learn that a GAP head cannot?
  2. How do the two head parameter counts change if input resolution doubles?
CS4337 · Building blocks / 25

Feature Manipulation: Upsampling, Skip Connections, and Attention

Upsampling / Interpolation architecture diagram
Example:Open In Colab

Reflection · Upsampling / Interpolation

Upsampling increases the spatial resolution of an image or feature map. Imagine enlarging an image by estimating values at new pixel locations. Nearest neighbor copies nearby values; bilinear and bicubic interpolation use weighted neighboring values. Transposed convolution instead learns weights for an upsampling operation—it is not a fixed interpolation rule.

Used in segmentation, super-resolution, reconstruction, and generative decoders. Increasing resolution alone does not recover details already lost; learned decoders use features and training data to predict plausible detail.

Uneven overlap in transposed convolution can create checkerboard artifacts. Resize + convolution is a useful alternative, not a guarantee of artifact-free images.
Reflection

Upsampling increases spatial resolution; shortcuts add or concatenate earlier features; attention reweights information according to context. They solve different problems and can coexist in one decoder.

Use resize or transposed convolution for resolution, skip connections for detail/gradient flow, and attention when the model should emphasize informative channels or positions dynamically. Interpolation has no learned parameters. Transposed convolution learns upsampling. Additive shortcuts require compatible shapes; concatenation increases channels. Attention adds data-dependent weighting and computation.

A decoder often combines all three mechanisms: interpolation or transposed convolution grows the grid, a skip connection restores high-resolution encoder evidence, and attention chooses which restored evidence is useful. The order and fusion method affect both shape and meaning. Addition assumes the two paths already express compatible features; concatenation lets a following layer learn how to combine them.

For an examination, for a proposed block, name whether it changes resolution, preserves information, or changes weighting; do not use these terms interchangeably.

Reflection questions
  1. When should skip features be added, and when is concatenation safer?
  2. Which component changes resolution, which restores earlier detail, and which performs data-dependent selection?
CS4337 · 05 · Learning & looking inside / 26

Real inference, entirely in your browser

Embedded MobileNet-v1 · width multiplier 0.25 · ImageNet · 224×224 RGB. Choose a photo and inspect actual learned activations.

Press Run MobileNet.

No model inference has run yet.

Actual feature maps

Each map is independently normalized for visibility; brightness is not comparable across maps. A channel has no guaranteed human-readable meaning.

Real trained weights, not a scripted classifier. Images stay in this page. First inference may compile GPU kernels; later runs are faster. The tiny model can confidently misclassify unusual images.
PyTorch · expand / copy reference code
from torchvision.models import mobilenet_v2, MobileNet_V2_Weights weights = MobileNet_V2_Weights.DEFAULT model = mobilenet_v2(weights=weights).eval() x = weights.transforms()(pil_image).unsqueeze(0) with torch.no_grad(): probs = model(x).softmax(1) # Python counterpart uses torchvision MobileNet-v2. # Browser lab uses the embedded TensorFlow.js MobileNet-v1 0.25 model.

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Inference is a forward pass with learned parameters fixed. Evaluation mode changes layers such as dropout and BatchNorm; disabling gradient tracking saves memory and overhead.

Use model.eval() and an inference/no-grad context for deployment or evaluation, while applying exactly the preprocessing expected by the trained model. eval() changes module behavior but does not disable autograd. no_grad()/inference_mode() disables gradient recording but does not switch BatchNorm or dropout to evaluation behavior; both concerns must be handled.

A reproducible inference pipeline includes model weights, architecture, input resizing, color order, numerical range, normalization constants, and class labels. A correct forward pass with incorrect preprocessing can produce confident but meaningless predictions. Deployment also requires deciding how to batch examples, which device and precision to use, and whether the measured latency includes preprocessing and data transfer.

For an examination, explain logits versus probabilities and identify preprocessing, model mode, gradient tracking, and label mapping as separate inference steps.

Reflection questions
  1. Why are model.eval() and inference_mode() separate steps?
  2. Which preprocessing mismatch could preserve tensor shape while still invalidating the prediction?
CS4337 · 05 · Learning & looking inside / 27

Grad-CAM: where did evidence come from?

Class-conditioned localization from activations and gradients—not a proof of causality.

The calculation

αₖᶜ = meanᵢⱼ(∂sᶜ/∂Aₖᵢⱼ)
Lᶜ = ReLU(Σₖ αₖᶜ Aₖ)

For this MobileNet’s global-average-pool + linear logit head, these gradient weights are proportional to classifier weights. The lab computes this exact special case from trained features.

Uses the image from the previous slide. Map is coarse (7×7), resized for display.

A heat map shows sensitivity associated with a class. It can expose shortcuts or background reliance, but it is not an object mask or a complete explanation.
Example:Open In Colab
PyTorch · expand / copy reference code
model.eval() # Capture A from the chosen conv layer using a forward hook. score = logits[:, class_id].sum() # pre-softmax logit grad = torch.autograd.grad(score, A, retain_graph=True)[0] alpha = grad.mean(dim=(2,3), keepdim=True) cam = (alpha * A).sum(dim=1).relu() cam = F.interpolate(cam[:,None], image.shape[-2:], mode="bilinear", align_corners=False)

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Grad-CAM weights a convolutional layer's feature maps by gradients of a selected class score, then combines them into a coarse localization heatmap.

Use it to inspect which spatial regions support a class prediction, compare failures, or communicate model evidence. It is a post-hoc explanation, not a proof of causality or correctness. Resolution is limited by the chosen feature map, and changing the layer or class can change the map.

Grad-CAM is class-specific because its weights come from the gradient of one chosen score. A region can be visually salient yet absent from the map if it does not positively support that class score at the selected layer. Upsampling the coarse heatmap improves display size but does not create new explanatory resolution. Reliable interpretation therefore compares classes, layers, examples, and ideally intervention-based checks.

Key relationαkc=meani,j(∂yc/∂Aijk);   LcGrad-CAM=ReLU(ΣkαkcAk)

For an examination, name the target class and target layer, explain gradient pooling, and state why ReLU keeps positive supporting evidence in the original method.

Reflection questions
  1. How would the map change if a shallower convolutional layer were selected?
  2. What evidence would be needed before treating a Grad-CAM region as causal?
Verified against: Grad-CAM ↗
CS4337 · 06 · The depth revolution / 28

2012: AlexNet changes the scale

Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton made CNNs the headline of large-scale visual recognition.

ILSVRC 2012

15.3%

Top-5 test error for their ensemble competition entry, versus 26.2% for the next-best entry. These are challenge results, not the paper’s separate ILSVRC-2010 experiment.

What made it work

Five convolutional layers + three dense layers; ReLU; GPU training; data augmentation; dropout; about 60 million parameters.

The first huge ImageNet-era CNN breakthrough—not the first CNN success.

Pixels
→
Conv + ReLU + pools
→
4096 → 4096
→
1000 classes
Top-5 error means the correct class is absent from the five highest-ranked predictions. It is not the same as top-1 error.
PyTorch · expand / copy reference code
from torchvision.models import alexnet net = alexnet(weights=None) logits = net(torch.randn(1,3,224,224)) print(logits.shape) # (1,1000)

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

CS4337 · 06 · The depth revolution / 29

Depth helped—but optimization became difficult

VGG and GoogLeNet already trained deeper networks. ResNet addressed a specific degradation problem.

The surprising observation

Some plain deeper networks had higher training error than shallower counterparts. That cannot be explained by overfitting alone.

More layers can make an identity mapping unnecessarily hard to learn.

The residual answer

Deep Residual Learning for Image Recognition

Kaiming He, Xiangyu Zhang, Shaoqing Ren, and Jian Sun (2015; CVPR 2016).

H(x) = x + F(x)
ResNet did not make all earlier deep networks possible retroactively. It supplied a scalable way to optimize much deeper architectures, including 152-layer ImageNet models.
PyTorch · expand / copy reference code
class ResidualSameShape(nn.Module): def __init__(self, channels): super().__init__() self.f = nn.Sequential( nn.Conv2d(channels,channels,3,padding=1,bias=False), nn.BatchNorm2d(channels), nn.ReLU(), nn.Conv2d(channels,channels,3,padding=1,bias=False), nn.BatchNorm2d(channels)) def forward(self,x): return F.relu(x + self.f(x))

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

Very deep plain networks can suffer a degradation problem: training error becomes worse as depth increases, even when the deeper model could represent the shallower solution.

Use residual parameterization when optimizing deep stacks of transformations is difficult. This degradation is not simply overfitting because training error also rises. A residual block learns a correction F(x) around an identity path instead of learning the full mapping H(x) directly.

Residual learning provides a convenient identity reference. If extra layers are not useful, they can in principle drive their residual branch toward zero instead of reconstructing an identity transformation through many nonlinear layers. This does not mean every block learns only a tiny correction, but it improves information and gradient flow enough to make substantially deeper networks trainable.

Key relationH(x)=F(x)+x;   if the desired mapping is identity, the residual solution is F(x)=0

For an examination, distinguish optimization degradation from vanishing gradients and from generalization/overfitting, although these phenomena can interact.

Reflection questions
  1. Why is rising training error in a deeper plain network not explained by overfitting alone?
  2. How does learning F(x)=0 simplify representing an identity mapping?
Verified against: ResNet ↗
CS4337 · 06 · The depth revolution / 30

Why the shortcut helps

Learn a correction while preserving a direct route—and build the residual architecture block by block.

One residual transformation

Why it helpsThe local derivative contains an identity term: I + JF. The gradient therefore has a direct path through each block.

Editable residual stack

Click a block, then change its internal depth.

OUTPUT ↑
A residual block is a reusable module: its internal layers learn F(x), while the shortcut carries x to the addition. Adding blocks increases network depth; adding layers inside a block makes each correction path deeper. The identity term helps optimization, but does not mathematically guarantee non-vanishing gradients.
PyTorch · expand / copy reference code
# Ignoring the final activation for the derivative: # y = x + F(x) # dL/dx = dL/dy @ (I + J_F(x)) # Across blocks: product of (I + J_F), not just J_F. class ResidualBlock(nn.Module): def __init__(self, channels, layers=2): super().__init__() body = [] for i in range(layers): body += [nn.Conv2d(channels, channels, 3, padding=1, bias=False), nn.BatchNorm2d(channels)] if i + 1 < layers: body += [nn.ReLU()] self.body = nn.Sequential(*body) def forward(self, x): return torch.relu(x + self.body(x))

This editor keeps tensor shapes fixed inside a block, so the shortcut can remain an identity.

Reflection

A residual shortcut provides an identity or projected path around a block. The addition gives activations and gradients a direct route through depth.

Use identity shortcuts when shapes match; use a learned projection when spatial size or channel count changes. Addition preserves channel width and merges paths elementwise. Concatenation preserves both tensors explicitly but increases channel count and is the characteristic DenseNet connection pattern.

The shortcut creates two simultaneous computational paths: a transformed residual path and a simpler reference path. During differentiation, the identity path contributes a direct term to the gradient, reducing dependence on every residual weight being well conditioned. When resolution changes, the shortcut must use stride, pooling, padding, or projection so that the tensors can be combined legally.

Key relationy=F(x;W)+x, or y=F(x;W)+Wsx when a projection Ws is required

For an examination, check tensor compatibility before addition, and explain why a projection shortcut has parameters while an identity shortcut does not.

Reflection questions
  1. When must an identity shortcut be replaced by a projection?
  2. How does the gradient through an additive shortcut differ from a chain containing only the residual branch?
Verified against: ResNet ↗
CS4337 · 06 · The depth revolution / 31

Build and compare the ResNet family

Configure the four stages, inspect the complete residual pipeline, and compare plain versus residual depth.

OUTPUT ↑ · each stage shows one block’s internal layers and its repetition count
VGG-19, 34-layer plain network, and 34-layer residual network architecture comparison
VGG-19 vs 34-layer plain vs 34-layer residual architecture · click to enlarge
Exact operation, shape, and parameter table
OperationOutput · NCHW (N=1)Trainable parametersCumulative

Counts include BN γ and β and the FC bias; BN running statistics are buffers and are excluded.

Basic blocks use two 3×3 convolutions. Bottlenecks use 1×1 reduction, 3×3 spatial processing, and 1×1 expansion by four. Projection shortcuts match changed spatial or channel dimensions at stage transitions. The shortcut changes optimization without removing representational depth.
PyTorch · expand / copy reference code
from torchvision.models.resnet import ResNet, BasicBlock, Bottleneck # BasicBlock example: ResNet-18 model18 = ResNet(BasicBlock, [2, 2, 2, 2], num_classes=1000) # Bottleneck example: ResNet-50 model50 = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=1000) trainable = sum(p.numel() for p in model18.parameters() if p.requires_grad) print(trainable) # 11,689,512

The browser builder calculates BasicBlock and Bottleneck shapes and trainable parameters directly.

Reflection

ResNet organizes residual blocks into stages. Basic blocks use two 3×3 convolutions; bottleneck blocks use 1×1, 3×3, 1×1 layers to compress, process, then expand channels.

Basic blocks are common in ResNet-18/34; bottlenecks make deeper ResNet-50/101/152 models computationally practical. A bottleneck's 1×1 layers reduce the expensive 3×3 channel width, but the final expansion and projection shortcuts affect the exact parameter count.

A ResNet stage keeps a common output resolution and channel scale across several blocks; the first block of a new stage usually downsamples and increases channels. Bottleneck blocks save computation by doing the expensive 3×3 operation at a narrower width. Model names count weighted layers under the paper's convention, so understanding the stage configuration is more reliable than inferring structure from the number alone.

For an examination, know the block type, stage repetition counts, and when the shortcut needs stride or projection; derive counts from tensor shapes rather than memorizing totals alone.

Reflection questions
  1. Why are bottleneck blocks preferred in the deepest ResNet families?
  2. Which block in a new stage changes spatial size and shortcut shape?
Verified against: ResNet ↗
CS4337 · 07 · Architectures in action / 32

Classification backbones: ResNet and DenseNet

Both preserve earlier information, but ResNet adds a shortcut while DenseNet keeps every earlier feature map available by concatenation.

ResNet · refine by addition

xₗ₊₁ = xₗ + Fₗ(xₗ)

The block learns a correction to the current representation. Addition keeps the channel width fixed and provides a direct path for signals and gradients.

DenseNet · reuse by concatenation

xₗ = Hₗ([x₀, x₁, …, xₗ₋₁])

Each layer receives the feature maps produced by every earlier layer in the dense block, then contributes a small set of new maps.

DenseNet block showing each layer connected to all later layers
Inside one dense block, every later layer can read all earlier feature maps. Source: UvA Deep Learning Tutorials.

Intuition: a shared feature notebook

Imagine each layer writes a few useful observations into a shared notebook. Later layers read the entire notebook instead of repeatedly rediscovering edges, textures, or shapes.

  • Growth rate k: each layer adds only k new channels.
  • Concatenation: old maps remain separate and reusable; channels grow through the block.
  • Transition layer: a 1×1 convolution compresses channels, then pooling reduces spatial size.
  • Why do it? Feature reuse improves information and gradient flow while allowing narrow individual layers.
Image
→
Dense blocks + transitions
→
Global pooling
→
N × classes
DenseNet does not make every layer fully connected neuron-by-neuron. It concatenates feature-map channels between convolutional layers within a dense block. A classifier still produces one class-score vector per image and needs task-appropriate supervision.
PyTorch · expand / copy reference code
from torchvision.models import densenet121 model = densenet121(weights=None) model.classifier = nn.Linear(model.classifier.in_features, num_classes) logits = model(images) loss = F.cross_entropy(logits, labels)

DenseNet-121 uses dense blocks separated by transition layers; its final classifier follows global average pooling.

Reflection

ResNet adds a block's input to its output. DenseNet concatenates every earlier feature map within a dense block, so each new layer directly reuses all previous features.

Use ResNet for a strong general-purpose backbone; DenseNet is useful when feature reuse and parameter efficiency are priorities. DenseNet's growth rate k controls how many new channels each layer contributes. Concatenation improves reuse but activation memory and channel count grow, so transition layers compress and downsample.

Dense connectivity gives every layer short routes to the loss and exposes earlier features directly instead of repeatedly relearning them. Because a layer receives the concatenation of all earlier outputs, its input width grows inside the block even though it contributes only k new channels. Transition layers use 1×1 convolution and pooling to control this growth between blocks.

Key relationDenseNet layer l: xl=Hl([x0,x1,…,xl-1]);   channels=C0+lk

For an examination, compare addition with concatenation and explain growth rate, dense blocks, and transition layers.

Reflection questions
  1. How does DenseNet's channel count grow within a block?
  2. Why can feature reuse reduce parameters while increasing activation-memory pressure?
Verified against: DenseNet ↗ · ResNet ↗
CS4337 · 07 · Architectures in action / 33

One backbone, many output tensors

Keep the backbone fixed, then choose a task-specific head, tensor shape, and training objective. Change the controls to inspect concrete outputs.

Same embedded “Pug sophie” photograph used earlier · illustrative output, not model inference.

Image restoration

Denoising, deblurring, and super-resolution usually predict N×3×H×W (or a larger spatial size). Pixel and perceptual losses teach different visual qualities.

Depth and geometry

Depth uses N×1×H×W; surface normals use N×3×H×W. The targets and loss give those channels their physical meaning.

Beyond photographs

The same backbone-and-head pattern supports medical volumes, satellite maps, industrial inspection, scientific fields, audio, and graphs.

The output head and its supervision define what every channel means. More channels do not automatically mean more objects: a channel may hold a class logit, displacement component, depth value, surface-normal component, color value, or learned feature. PyTorch normally uses NCHW.
PyTorch · expand / copy reference code
classification = torch.randn(B, C) segmentation = torch.randn(B, C, H, W) # PyTorch logits segmentation_nhwc = segmentation.permute(0,2,3,1) flow = torch.randn(B, 2, H, W) depth = torch.randn(B, 1, H, W) # Example task-specific heads on the same backbone features: rgb_head = nn.Conv2d(64, 3, 1) depth_head = nn.Sequential(nn.Conv2d(64, 1, 1), nn.Softplus()) normal_head = nn.Conv2d(64, 3, 1) normals = F.normalize(normal_head(features), dim=1)

Copyable Python reference code. Python does not execute inside this HTML; the labeled JavaScript labs do.

Reflection

A shared convolutional backbone can feed task-specific heads. Classification produces class scores; detection produces boxes and classes; segmentation produces per-pixel labels; optical flow produces a 2D motion vector per pixel.

Use task-specific heads when the same learned representation must be decoded into different output structures. Global pooling is appropriate for image-level decisions but destroys location. Dense tasks retain or recover spatial grids, often using pyramids and skip connections for multiple scales.

The backbone answers 'what visual evidence is present?' while each head converts that evidence into the structure required by a task. Feature pyramids expose several spatial scales so large semantic regions and small detailed objects can both be handled. Multi-task systems may share a backbone but must balance losses carefully, because gradients from different heads can reinforce or compete with one another.

For an examination, match the output tensor, loss, and decoder to the task. State which axes carry class, box, or motion information.

Reflection questions
  1. Why is global pooling appropriate for classification but destructive for dense prediction?
  2. How might gradients from two task heads compete inside a shared backbone?
Verified against: FCN segmentation ↗ · YOLO ↗ · FlowNet ↗
CS4337 · 07 · Architectures in action / 34

Computer vision applications: from pixels to decisions

Select an application family to see its output, real-world implication, and representative papers. The map covers the major families; deployed systems often combine several.

Two-stream convolutional network with spatial RGB and temporal optical-flow streams fused for action recognition
Concrete example · Two-stream action recognition: an RGB stream models appearance; an optical-flow stream models motion; their class evidence is fused.

Why two streams?

A still frame can show a person holding a cup, but motion distinguishes lifting, drinking, and putting it down. The spatial stream asks what is visible?; the temporal stream asks how is it moving?

RGB frames+Optical flow→Fused action class

This 2014 design is one example. Later video models learn spatiotemporal features with 3D convolution, recurrence, or attention.

A computer-vision model becomes useful only when its output representation, data, evaluation metric, and operational decision match the real problem. Accuracy alone does not settle privacy, bias, safety, latency, or failure-recovery requirements.
PyTorch · expand / copy reference code
# One backbone can support several task-specific heads. features = backbone(images) class_logits = classification_head(features) # N × classes boxes = detection_head(features) # boxes + scores mask_logits = segmentation_head(features) # N × classes × H × W flow = motion_head(features_t0, features_t1) # N × 2 × H × W # Two-stream idea: fuse appearance and motion evidence. action_logits = spatial_stream(rgb) + temporal_stream(optical_flow)

The exact head, targets, losses, and postprocessing depend on the application.

CS4337 · 09 · References / 35

Sources, reproducibility, and teaching notes

Primary papers and official APIs. Links are optional reading; the slides and inference work offline.

CS4337 · 09 · References / 36

Further reading & the offline runtime

Original diagrams are rendered locally. Model outputs are clearly separated from illustrative task animations.

Runtime: TensorFlow.js 4.22.0 (Apache-2.0). Model: TensorFlow.js MobileNet-v1 0.25 / 224; weights and ImageNet class names embedded at build time. Sample image from the TensorFlow.js MobileNet demo. Asset provenance and checksums are saved with the source. Browser inference uses WebGL when available, CPU otherwise.

Presentation controls: Home / arrows / slide grid · fit and zoom · hidden marker palette · copyable Python references · pins and downloadable notes. Code edits persist locally. Pins are session notes: download before closing; refresh can also trigger the unsaved-note warning. A crash can bypass it.

CS4337 · 10 · Reflection / 37

Reflection: the convolution toolkit

Concise concept summaries for revision. Choose a topic, review the key ideas, and try one reflection question.

TOPIC 01 / 17

Tensors, filters, and feature maps

A CNN represents an image as a tensor and learns filters that detect useful local patterns. In N × C × H × W, N is batch size, C is channels, and H × W is spatial size.

  • One filter produces one output channel. A standard 3×3 RGB filter contains 27 weights: nine for each input channel. Their products are summed to form one output value.
  • Weight sharing: the same filter is reused at every location. This reduces parameters and lets a pattern be detected throughout the image.
  • Features are learned: early maps often respond to edges or textures; deeper maps combine evidence. A channel need not correspond to one named object.
  • Filters are parameters; feature maps are input-dependent activations. Training changes parameters; a forward pass computes activations.

Reflection question

  1. Why does a six-filter RGB convolution produce six output channels?
Bring the ideas togetherPractice tracing a small CNN from image to prediction. At each stage, calculate the shape and parameter count, explain the connectivity and information loss, then justify an alternative. Be ready to distinguish parameters from activations, training from inference, and a useful visualization from proof of model behavior.

These notes synthesize this deck's examples with the CS231n convolution curriculum and the primary references linked beside each topic. Framework-specific details follow PyTorch documentation, including floor-based output sizes, normalization axes, and optimizer distinctions. History and reference-only slides provide context; the focus here is reasoning about the computational concepts.