Neural Networks • Neural Network Foundations • 16 min read

Convolutional and Recurrent Neural Networks

Start with an example: A photo and a sentence need different kinds of memory

Imagine two problems. In the first, you want to find a crack in a photograph of a road. What matters is whether a small visual pattern appears anywhere in the picture. In the second, you want to interpret the sentence “The package arrived after the driver called.” The order of the words matters, and later words can depend on earlier ones.

A convolutional neural network (CNN) handles the first kind of structure by applying the same learned pattern detector across many image positions. A recurrent neural network (RNN) handles the second kind by updating a hidden state as it reads successive inputs. Neither architecture magically understands images or language. Each gives the learning algorithm a useful way to organize computations.

For a mental model, picture a small window sliding across a photo for a CNN, and a notebook that is updated after each word for an RNN. The sliding window is a rough analogy for a convolutional filter; the notebook is a rough analogy for a recurrent hidden state. Later sections show the actual calculations and where these analogies stop working.

Neural network architecture describes how a model organizes computations and connections between its layers. Different architectures encode different assumptions about data. A convolutional neural network (CNN) is designed to recognize local patterns across spatially organized inputs such as images. A recurrent neural network (RNN) processes an ordered sequence while maintaining a state that carries information from earlier steps.

Both use learned parameters, forward propagation, loss functions, and gradient-based training. Their key difference is how they share parameters and combine information across positions. CNNs reuse filters across locations; RNNs reuse a recurrent transition across sequence steps.

1. Why neural network architecture matters

A fully connected (dense) layer assigns independent weights to its input features. This can be useful for small, fixed-size feature vectors, but it does not automatically exploit spatial neighborhoods or temporal order.

Consider two problems:

  • Image classification: A small edge may matter whether it appears on the left or right of an image. A CNN can apply the same detector in both places.
  • Sequence classification: Whether a word changes the meaning of a sentence can depend on preceding words. An RNN processes tokens in order and updates its hidden state.

The architecture introduces an inductive bias: a built-in preference for certain relationships in the input. This bias can improve learning efficiency when it matches the task. It can also become a limitation when the assumed structure is inappropriate.

PropertyConvolutional neural networkRecurrent neural network
Typical inputImages, feature maps, spatial or local signalsTime series, text tokens, ordered observations
Main reused operationConvolutional filter across positionsState transition across time steps
CapturesLocal spatial patterns, then larger receptive fieldsOrdered dependencies through a hidden state
Weight sharingAcross spatial locationsAcross sequence positions
Main challengeRetaining context and spatial detailLong-range dependencies and sequential computation
Common variants1D/2D/3D CNNs, residual CNNsVanilla RNN, LSTM, GRU

These are architectural tendencies, not strict rules. A 1D CNN can analyze audio or time-series data, while recurrent models can process sequences of image features.

2. Convolutional neural networks

A CNN is a neural network that applies learnable filters to local regions of structured input. The resulting feature maps indicate where learned patterns occur. Stacking layers allows the model to build more complex representations from simpler features.

2.1 Pixels, channels, and tensors

A color image is commonly represented as an array with height HH, width WW, and three color channels. In PyTorch, a batch of images normally has shape:

[batch_size, channels, height, width]

For example, 32 × 3 × 64 × 64 represents 32 RGB images, each 64 pixels high and wide. Input channels may also represent grayscale intensity, sensor readings, or features produced by earlier layers.

2.2 Filters, kernels, and feature maps

A kernel is a small grid of learnable weights. At each position, the network multiplies nearby input values by kernel weights and sums them, usually adding a bias. The kernel is then applied at other positions using the same weights.

For a single-channel 2D input XX and a kernel KK, the operation typically called convolution in deep-learning libraries is technically cross-correlation:

Yi,j=b+∑u=0kh−1∑v=0kw−1Ku,vXi+u,j+vY_{i,j}=b+\sum_{u=0}^{k_h-1}\sum_{v=0}^{k_w-1} K_{u,v}X_{i+u,j+v}

This equation omits padding and stride for clarity. For a multi-channel input, the sum also extends across the input channels. Each learned output filter produces an output feature map.

A three-by-three filter scans a larger image grid, creating a smaller feature map
The same learned filter scans the input, creating responses at different positions. Real CNN filters generally span all input channels.

Parameter sharing is the major benefit. For instance, a 3 × 3 convolution with three input channels and eight output channels has 8(3⋅3⋅3+1)=2248(3\cdot3\cdot3+1)=224 trainable parameters when biases are enabled. Those parameters are reused at every output location; a dense connection to all image pixels would typically need far more weights.

2.3 Stride, padding, and dilation

  • Stride controls how many input positions the kernel moves per step. Larger stride typically reduces output resolution.
  • Padding adds values around the input boundary, often zeros, to control output size and preserve boundary information.
  • Dilation spaces kernel elements farther apart, expanding their receptive field without increasing the number of filter weights.

For one spatial dimension, the output length of a standard convolution is:

Lout=⌊Lin+2p−d(k−1)−1s+1⌋L_{\mathrm{out}}=\left\lfloor\frac{L_{\mathrm{in}}+2p-d(k-1)-1}{s}+1\right\rfloor

Here pp is padding, dd is dilation, kk is kernel size, and ss is stride. The formula applies independently to height and width in 2D convolutions.

For a 32-pixel-wide input, kernel size 3, padding 1, dilation 1, and stride 1, the output width remains 32. Changing stride to 2 reduces it to 16.

2.4 Activation and pooling layers

Convolution produces a weighted response; an activation function, such as ReLU, introduces nonlinearity:

ReLU⁡(x)=max⁡(0,x)\operatorname{ReLU}(x)=\max(0,x)

Pooling summarizes nearby responses. Max pooling keeps the largest value in a local region; average pooling keeps the average. Pooling can reduce spatial size and sensitivity to small shifts, but it also discards some position-specific detail. Some modern CNNs instead use strided convolutions for downsampling.

2.5 Hierarchical features and receptive fields

Early CNN layers may respond to simple local patterns. Later layers combine those responses into more complex features. The receptive field of a unit is the region of the original input that can influence it. Deeper networks or dilated convolutions can increase receptive fields.

A typical image classifier may follow this conceptual pattern:

Image
  → Convolution + activation
  → Convolution + activation
  → Downsampling
  → Deeper feature extraction
  → Global average pooling
  → Linear classification head
  → Class scores

A classifier is not the only possible CNN design. Object detection predicts object locations as well as categories; segmentation requires spatially aligned predictions, often with upsampling or encoder-decoder structures.

3. Recurrent neural networks

An RNN is a neural network in which a hidden state is repeatedly updated while processing an ordered sequence. At step tt, the network uses the current input xtx_t and the previous state ht−1h_{t-1} to compute the next state hth_t.

A simple recurrent update is:

ht=tanh⁡(Wxxt+Whht−1+b)h_t=\tanh(W_xx_t+W_hh_{t-1}+b)

Here WxW_x, WhW_h, and bb are learned parameters shared across all time steps. An output may be produced at every step or only after a sequence has been processed.

Recurrent neural network unfolded across three ordered sequence steps
Unrolling an RNN shows its computation through time. The diagram displays repeated applications of one parameter-sharing recurrent cell.

3.1 Sequence inputs and output patterns

An input sequence can be written as x1,x2,…,xTx_1,x_2,\dots,x_T, where TT is sequence length. Common task patterns include:

  • Many-to-one: Read a sequence and predict one class, such as whether a review is positive.
  • Many-to-many: Assign an output to each time step, such as labeling each sensor reading.
  • Sequence-to-sequence: Encode one sequence and generate another, such as a translation. Early encoder-decoder systems often used RNNs; many current systems use Transformers.

Data is often padded so variable-length sequences can be batched. Without correct padding handling, padded positions may distort a model’s representation or loss.

3.2 Backpropagation through time

An RNN is trained by backpropagation through time (BPTT). The computation is conceptually unrolled across time steps, and gradients are propagated backward through the repeated state transitions. Since the same weights participate at multiple steps, their gradient contributions accumulate.

Long sequences create difficulties:

  • Vanishing gradients: Repeated gradient products can become very small, limiting learning of distant dependencies.
  • Exploding gradients: Repeated products can become very large and destabilize updates; gradient clipping is one possible mitigation.
  • Sequential dependency: Later states depend on earlier ones, which restricts parallel processing across steps.

These difficulties motivated gated architectures, including LSTM and GRU networks.

4. LSTM and GRU networks

4.1 Long short-term memory (LSTM)

A long short-term memory network (LSTM) is a recurrent architecture that maintains a cell state in addition to a hidden state. Learned gates regulate what information is stored, forgotten, or exposed as output.

An LSTM typically includes:

  • Forget gate: Controls retention of the previous cell state.
  • Input gate: Controls how new candidate information enters the cell state.
  • Output gate: Controls what part of the updated cell state affects the hidden output.

For a common LSTM formulation:

ft=σ(Wf[xt;ht−1]+bf)it=σ(Wi[xt;ht−1]+bi)c~t=tanh⁡(Wc[xt;ht−1]+bc)ct=ft⊙ct−1+it⊙c~tot=σ(Wo[xt;ht−1]+bo)ht=ot⊙tanh⁡(ct)\begin{aligned} f_t &= \sigma(W_f[x_t;h_{t-1}]+b_f)\\ i_t &= \sigma(W_i[x_t;h_{t-1}]+b_i)\\ \tilde c_t &= \tanh(W_c[x_t;h_{t-1}]+b_c)\\ c_t &= f_t\odot c_{t-1}+i_t\odot\tilde c_t\\ o_t &= \sigma(W_o[x_t;h_{t-1}]+b_o)\\ h_t &= o_t\odot\tanh(c_t) \end{aligned}

The semicolon indicates vector concatenation, σ\sigma is the sigmoid function, and ⊙\odot means element-wise multiplication. The additive cell-state update creates a more direct path for information and gradients than a vanilla RNN has, although it does not guarantee perfect long-range memory.

4.2 Gated recurrent unit (GRU)

A gated recurrent unit (GRU) is another gated recurrent architecture. It commonly uses an update gate to balance prior and candidate state information and a reset gate to control how much of the previous state contributes to the candidate. A GRU does not maintain a separate LSTM-style cell state.

FeatureVanilla RNNLSTMGRU
Main stateHidden stateHidden state and cell stateHidden state
Learned gatesNoneInput, forget, outputUpdate, reset
Long-range dependency handlingOften difficultImproved through gated cell stateImproved through gated updates
Per-step computationRelatively simpleMore operationsTypically fewer operations than an LSTM
Best choiceSimple baselines and short sequencesTask-dependent; useful for complex temporal dynamicsTask-dependent; often a compact gated alternative

Neither LSTM nor GRU is universally superior. Compare validation results, computational requirements, and task constraints rather than selecting by reputation.

5. CNNs versus RNNs in a real task

Imagine detecting an equipment fault from a sensor that records 100 measurements per second.

A 1D CNN can learn short patterns such as abrupt spikes, short oscillations, and characteristic wave shapes. It can process many local positions in parallel, making it useful for fast pattern detection.

An RNN, LSTM, or GRU can update a state as measurements arrive and represent patterns that depend on their order over time. However, its sequential state updates may make training or long-input inference slower.

A hybrid CNN-RNN model can first extract local signal patterns with a CNN and then feed the extracted sequence of features into an RNN. A Transformer or a simpler statistical model may also be appropriate. Architecture selection is an empirical design decision, not an automatic rule tied to the data modality.

6. Practical PyTorch example: a CNN and a GRU

The examples below show the shapes of two small models. They demonstrate forward passes with synthetic inputs, not meaningful trained predictions. Install a suitable version of PyTorch according to the official setup instructions.

6.1 A CNN image classifier

import torch
from torch import nn

class SmallCNN(nn.Module):
    def __init__(self, num_classes=4):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 8, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2),
            nn.Conv2d(8, 16, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d((1, 1)),
        )
        self.classifier = nn.Linear(16, num_classes)

    def forward(self, x):
        x = self.features(x)
        x = torch.flatten(x, start_dim=1)
        return self.classifier(x)

model = SmallCNN(num_classes=4)
images = torch.randn(5, 3, 32, 32)
logits = model(images)
print(logits.shape)  # torch.Size([5, 4])

Conv2d learns spatial filters, MaxPool2d reduces resolution, and adaptive average pooling creates one value per output channel before the classification layer. The output values are logits, not normalized class probabilities. For labeled multiclass training, nn.CrossEntropyLoss() accepts these logits directly.

6.2 A GRU sequence classifier

import torch
from torch import nn

class SequenceGRU(nn.Module):
    def __init__(self, input_size=6, hidden_size=20, num_classes=3):
        super().__init__()
        self.gru = nn.GRU(input_size, hidden_size, batch_first=True)
        self.classifier = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        _, final_hidden = self.gru(x)
        return self.classifier(final_hidden[-1])

model = SequenceGRU()
sequences = torch.randn(5, 12, 6)
logits = model(sequences)
print(logits.shape)  # torch.Size([5, 3])

Here, [5, 12, 6] represents five sequences with 12 time steps and six features per step. batch_first=True makes the input format [batch, sequence, features]. The GRU returns a hidden state from which the example constructs one classification output for each sequence.

Note: For padded variable-length sequences, taking the last hidden state naively may include padding effects. Use sequence lengths with pack_padded_sequence, masking, or an appropriate pooling strategy when building real systems.

To train either model, add labeled data, a suitable loss, an optimizer, training iterations, and evaluation on held-out data. See Training Neural Networks for that full process.

7. Common architectural decisions

7.1 Choose the appropriate data representation

A 2D CNN expects spatial dimensions; an RNN expects sequence order. Arbitrarily reshaping tabular data into an image or sequence does not automatically create meaningful spatial or temporal relationships.

7.2 Match model outputs to the task

For classification, produce one logit per class or binary logits as appropriate. For per-time-step forecasting or labeling, preserve the time axis. For segmentation, preserve or recover spatial resolution.

7.3 Evaluate with realistic data splits

Image datasets may contain near-duplicate frames or samples from the same person, location, or recording. Time series may contain future information if randomly shuffled across a forecasting boundary. Split datasets in ways that reflect how predictions will be used in practice.

7.4 Compare simpler baselines

A small CNN, GRU, or even a non-neural baseline can outperform a larger network on a modest dataset. Evaluate accuracy alongside latency, memory use, robustness, and deployment cost.

8. Where these architectures are used

ApplicationWhy the architecture can helpImportant qualification
Image classificationCNN filters detect local visual patternsVision Transformers are also common
Medical image analysisCNNs can learn spatial featuresClinical validation and safety controls are essential
Object detectionCNN backbones extract spatial featuresDetection needs additional localization components
Speech and audio1D/2D CNNs capture temporal or spectral patternsAudio pipelines may use attention-based models
Sensor anomaly detectionCNNs find local patterns; RNNs track temporal stateRare events require careful evaluation
Language sequence labelingRNNs represent token order and contextTransformers are widely used alternatives
Time-series forecastingRNNs encode previous observationsClassical forecasting and simpler ML remain viable

9. Limitations and the relationship to Transformers

CNNs are efficient at local feature extraction, but their receptive fields and downsampling choices affect how global relationships and fine spatial details are represented. Deep or attention-augmented CNNs can address some of these limitations.

RNNs model sequential order directly, but long-term dependencies can remain hard to learn, and their recurrent computation limits parallelism over sequence positions. LSTMs and GRUs mitigate, rather than completely eliminate, these issues.

A Transformer uses attention mechanisms to relate sequence positions more directly and can train with greater parallelism over positions, although attention has its own memory and computational costs. Transformers are particularly important for modern large language models. CNNs and recurrent architectures remain useful in constrained devices, smaller datasets, streaming systems, and specialized signal-processing tasks.

10. Common misconceptions

  • “CNNs only work on images.” One-dimensional convolutions also process audio, time-series data, and other ordered signals.
  • “An RNN stores its entire history exactly.” Its finite-dimensional state is a learned representation, not a perfect archive.
  • “LSTMs solve every long-context problem.” Gating helps gradient flow, but very long dependencies can still be difficult.
  • “More layers always produce a better model.” Additional capacity can increase compute cost and overfitting risk.
  • “Modern Transformers made CNNs and RNNs useless.” The appropriate architecture depends on data, hardware, latency, and evaluation results.

11. Check your understanding

  1. Why does parameter sharing make convolution different from a fully connected operation?
  2. What happens to the output width of a convolution when stride increases, all else being equal?
  3. What information is reused from one RNN time step to the next?
  4. How does BPTT relate to ordinary backpropagation?
  5. What additional state does an LSTM maintain that a GRU does not?
  6. Why might a 1D CNN be preferable to an RNN for short, local sensor patterns?
Show worked answers
  1. The same filter weights are applied at multiple spatial positions, allowing one learned local detector to be reused across the input.
  2. The spatial output normally becomes shorter because the kernel moves farther between evaluated positions.
  3. The recurrent hidden state and shared transition parameters connect steps; the current input is processed alongside the previous state.
  4. BPTT applies the chain rule to a network unrolled across time and combines gradient contributions for parameters reused at each step.
  5. An LSTM has an explicit cell state in addition to the hidden state; a conventional GRU uses a single hidden state.
  6. A CNN evaluates local windows in parallel and may need fewer sequential operations when the relevant signals are mostly local.

Prerequisites

Continue learning

The future article links are planned routes in the PlainCS AI Knowledge Map and will become active when their pages are published.

13. References and further reading

Related articles in

  • Deep Learning with PyTorch — Build, train, evaluate, and save a neural network with PyTorch using tensors, automatic differentiation, datasets, and optimization loops.
  • Forward Propagation and Backpropagation — Learn how neural networks compute predictions with forward propagation and calculate parameter gradients with backpropagation, using the chain rule and a worked example.
  • Neural Networks: Neurons, Layers, Weights, and Biases — Understand the fundamental components of artificial neural networks, including neurons, weights, biases, layers, activation functions, and how networks represent learned patterns.

Image preview

Fit