Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Introduction to CNNs and RNNs

Concise introduction to Convolutional Neural Networks (CNNs) and Recurrent Neural Networks (RNNs), explaining definitions, core math, practical formulas, worked examples (including small Python code), exam tips and quick checks.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Convolutional Neural Networks (CNNs) are used when the input has a spatial structure (images, videos, spectrograms) because they exploit local patterns and are translation equivariant; pooling or global operations can provide some translation invariance. Recurrent Neural Networks (RNNs) are used for sequence data (text, time series, sensor logs) because they model temporal dependencies and variable-length inputs.

Key ideas

Start from first principles: a neural network computes functions by composing simple operations (linear maps and nonlinearities). We build two families adapted to two data types.

  • Convolution: the discrete operation that combines local neighbourhood values with a small weight template. Exact definition (DL convention): we use discrete cross-correlation (often called "convolution" in DL). For an input x and kernel k (valid mode) at position i: y[i] = sum_j x[i + j]·k[j], assuming indices where both exist. If using true mathematical convolution, the kernel is flipped: (x * k)[i] = sum_j x[i - j]·k[j].

  • Kernel (filter): a small matrix or vector of learnable weights that is applied locally to compute features. Define kernel size K as its spatial size (e.g., 3×3).

  • Stride: the step size S by which the kernel moves across the input.

  • Padding: adding zeros (or other values) around the input border; padding P denotes the number of zero rows/columns added on each side.

  • Feature map: the output of applying a kernel over the whole input; for an image, it is a 2D map of activations.

  • Parameter sharing: using the same kernel values across different spatial locations — the core efficiency idea of CNNs. This reduces the number of parameters compared to a fully connected layer.

  • Pooling: a down-sampling operation (e.g., max-pooling or average-pooling) that reduces spatial size and provides local translation invariance.

  • Receptive field: the region of the input that affects one output activation. In deeper layers, receptive fields grow.

  • Convolutional layer (definition): a layer that computes multiple feature maps by convolving multiple kernels across input channels and applying an elementwise activation function.

Derivations examiners often ask for:

  1. Output spatial size of a convolutional layer (assume integer result): draw a 1D input line of length W (draw ticks 0..W-1), a kernel of size K, show padding P zeros at both ends, and show kernel positions offset by stride S. The formula is the number of valid positions the kernel can occupy: (W - K + 2P)/S + 1. For 2D, apply the formula independently to height and width.

  2. Number of parameters in a convolutional layer: For input with C_in channels, kernel size K×K, and C_out output channels (filters), parameters = C_out × C_in × K × K + C_out (biases, if present). Draw a cube for input channels and a small cube for each filter and label dimensions.

  3. Why convolution helps: by sparse interactions (each output depends on a small local input patch) and parameter sharing (same kernel used across many locations) the model needs fewer parameters and generalizes better for local patterns.

Now RNNs:

  • Recurrent neural network (RNN): a neural network with connections that form directed cycles over time, allowing information to persist. Define hidden state h_t as the vector that summarises past inputs up to time t.

  • Basic recurrence (one-layer, vanilla RNN): h_t = f( W_xh x_t + W_hh h_{t-1} + b ), y_t = g( W_hy h_t + c ). Here f is an activation (e.g., tanh), g is output map (e.g., softmax), x_t input at time t.

  • Backpropagation through time (BPTT): to train RNNs, unfold the network in time (draw copies of the RNN for t = 1..T, with shared weights), then apply standard backpropagation on the unfolded network to compute gradients. Label repeated parameters as identical across time.

  • Vanishing and exploding gradients: the gradient ∂L/∂W_hh includes products of Jacobian matrices ∏k ∂h_k/∂h{k-1}. If the spectral radius (largest absolute eigenvalue) of ∂h/∂h is less than 1, gradients shrink (vanish); if >1, they can grow (explode). This is why long-range dependencies are hard for vanilla RNNs. Common mitigation techniques include gradient clipping (to control exploding gradients), careful/orthogonal initialization, and gated architectures (LSTM/GRU).

  • Gated RNNs (high-level): LSTM (Long Short-Term Memory) and GRU (Gated Recurrent Unit) introduce multiplicative gates (forget, input, output for LSTM) to control information flow and mitigate vanishing gradients. Define gate as a sigmoid-activated linear map that multiplies another signal elementwise.

Important diagram instructions to draw (exam answers often expect diagrams):

  • CNN diagram: draw an input image rectangle labelled H×W×C_in, draw a small square kernel sliding across producing a feature map H'×W'×C_out, show a pooling block reducing size, then a flatten arrow to a fully connected (dense) block, label activations (ReLU) between layers.

  • RNN diagram: draw sequence positions t=1..T horizontally, draw hidden state circles h_t stacked above each input x_t, draw arrows from x_t to h_t and from h_{t-1} to h_t, then draw the unfolded-in-time version with copies and shared weight labels.

Assumptions: when deriving formulas, assume integer outputs (stride divides appropriately) and zero padding edges unless stated. For gradient spectral radius discussion, assume linearized dynamics or small-signal approximation (use Jacobians).

Formulas

O = floor((W - K + 2P)/S) + 1
O = output size (one dimension), W = input size, K = kernel size, P = padding, S = stride. Units: count (dimensionless). Applies along one axis; in discrete implementations a floor is taken. For 'same' padding with stride S, choose P = floor((K - 1)/2) so that O = ceil(W/S).

params_conv = C_out * C_in * K * K + C_out
C_out = number of filters, C_in = input channels, K = kernel width (assumes square kernel). Units: count of parameters. Applies per convolutional layer including one bias per output channel.

y[i, j, m] = sum_{c=1..C_in} sum_{u=0..K-1} sum_{v=0..K-1} x[i*S + u - P, j*S + v - P, c] * w[u, v, c, m] + b[m]
This is the standard discrete cross-correlation form producing output channel m at spatial location (i,j), with stride S and zero-padding P per side (indices outside the input are treated as zeros). Units: activation units (dimensionless). Applies per convolutional layer.

h_t = f( W_xh x_t + W_hh h_{t-1} + b )
h_t = hidden state at time t (vector), x_t = input at time t, W_xh = input-to-hidden weights, W_hh = hidden-to-hidden weights, b = bias, f = activation (e.g., tanh). Units: dimensionless activations. Applies to vanilla RNN.

∂L/∂W_hh = sum_{t=1..T} (∂L/∂h_t) * (sum_{k<=t} (∏_{j=k+1..t} J_j) * ∂h_k/∂W_hh)
Here J_j = ∂h_j/∂h_{j-1} is the Jacobian at time j. This shows that gradients involve products of J matrices which can shrink or grow exponentially with t. Units: gradient units same as W_hh units. Applies when using BPTT.

ReLU(x) = max(0, x)
Simple activation used widely in CNNs. Units: activation.

softmax(z)_i = exp(z_i) / sum_j exp(z_j)
Used for multiclass outputs to produce probabilities.

Worked examples

Example 1 — Numerical CNN layer size and parameter count

Problem: Input image size 32×32 with 3 channels (RGB). A convolutional layer uses 10 filters, each 5×5, stride S = 1, padding P = 0, and biases included. Compute output size and number of parameters.

Steps: 1) Apply output formula per axis: O = (W - K + 2P)/S + 1 = (32 - 5 + 0)/1 + 1 = 28. So output feature maps have spatial size 28×28.

  1. Number of parameters: params = C_out × C_in × K × K + C_out = 10 × 3 × 5 × 5 + 10 = 10 × 75 + 10 = 750 + 10 = 760.

Answer: Output shape = 28 × 28 × 10. Number of parameters = 760.

Example 2 — Simple 1D convolution in numpy (programming) and sample run

Python program (runs with numpy):

import numpy as np

def conv1d(x, k, stride=1, padding=0):
    x_p = np.pad(x, (padding, padding), mode='constant')
    n = len(x_p)
    m = len(k)
    out_len = (n - m)//stride + 1
    out = np.zeros(out_len, dtype=float)
    for i in range(out_len):
        out[i] = np.dot(x_p[i*stride:i*stride+m], k)
    return out

x = np.array([1.0, 2.0, 3.0, 4.0])
k = np.array([1.0, 0.0, -1.0])
print(conv1d(x, k))

Sample input: x = [1, 2, 3, 4], k = [1, 0, -1]. Exact output printed by program: [-2. -2.]

(Manual check: position 0: 11 + 20 + 3*(-1) = -2; position 1: 21 + 30 + 4*(-1) = -2.)

Example 3 — Simple RNN forward pass in numpy and sample run

Python program (runs with numpy):

import numpy as np

def rnn_forward(x_seq, Wxh, Whh, b, h0=None):
    T = len(x_seq)
    h = np.zeros(T)
    if h0 is None:
        prev = 0.0
    else:
        prev = h0
    for t in range(T):
        a = Wxh * x_seq[t] + Whh * prev + b
        h_t = np.tanh(a)
        h[t] = h_t
        prev = h_t
    return h

x = np.array([1.0, 2.0, -1.0])
Wxh = 0.8
Whh = 0.5
b = 0.0
print(np.round(rnn_forward(x, Wxh, Whh, b), 3))

Sample input: x = [1, 2, -1], Wxh = 0.8, Whh = 0.5, b = 0. Exact output printed: [ 0.664 0.959 -0.310]

(Manual check: h1 = tanh(0.81 + 0.50) = tanh(0.8) ≈ 0.664; h2 = tanh(1.6 + 0.332) = tanh(1.932) ≈ 0.958; h3 = tanh(-0.8 + 0.479) = tanh(-0.321) ≈ -0.310.)

Common mistakes

  • Forgetting channel counts: when counting parameters, missing the multiplication by input channels C_in.
  • Using the output-size formula without rounding or without checking stride divides correctly — always state integer-output assumption or how to handle remainder.
  • Ignoring bias terms when counting parameters.
  • Drawing an RNN without indicating weight sharing across time or forgetting to unfold when explaining BPTT.
  • Claiming LSTM/GRU eliminate vanishing gradients completely — they mitigate it, but do not eliminate all training difficulties.

For your exam

Question types: short definitions (define convolution, kernel, stride, padding, receptive field, RNN, hidden state), derivations (output size formula, parameter count), numerical problems (compute sizes and parameter counts), programming (small conv1d or RNN forward pass), and diagrams (draw CNN architecture or unfolded RNN and label weights).

Full-marks checklist:

  • For a definition: give the formal definition and a one-line explanation of why it matters.
  • For derivation: show step-by-step reasoning (draw the sliding kernel positions for output size, show algebra to get formula), state assumptions (integer result, padding convention).
  • For numericals: show every step, substitute numbers into formulas, compute intermediate results and show final shape and parameter count with units (counts).
  • For diagrams: label axes, sizes (e.g., H×W×C), show stride/padding, indicate shared weights over time for RNN diagrams.
  • For code: provide runnable code and one exact sample input and output.

Quick check

  1. Define a kernel (filter) in CNNs in one sentence.
  2. Give the 1D output size formula for a convolution with input W=10, K=3, P=1, S=2; compute numeric output.
  3. In an RNN with h_t = tanh(W_xh x_t + W_hh h_{t-1}), explain in one sentence why gradients can vanish.

Answers: 1) A kernel (filter) is a small matrix of learnable weights applied locally across an input to compute a feature map. 2) O = floor((W - K + 2P)/S) + 1 = floor((10 - 3 + 2)/2) + 1 = floor(9/2) + 1 = 4 + 1 = 5. 3) Gradients can vanish because the gradient backpropagated through time is a product of many Jacobian matrices; if their spectral radius is <1 the product shrinks exponentially.

(End of notes.)

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?