From Individual Layers to a Complete Blueprint
You have studied the convolution operation, learned how pooling compresses spatial dimensions, and understood how activation functions inject non-linearity. Each of these components is powerful on its own, but none can solve a real-world problem alone. A CNN architecture is the engineering blueprint that specifies how to stack these building blocks together so that raw pixels flow in at one end and a confident prediction — "crack" or "no crack" — emerges at the other.
This sub-chapter teaches you to read, reason about, and design CNN architectures. By the end you will be able to sketch a complete network for crack classification, calculate its parameter count, and explain every layer's purpose.
Designing a CNN is remarkably similar to designing a structural system. Just as a building has foundations, columns, beams, and a roof — each serving a distinct structural role — a CNN has convolutional blocks, pooling stages, normalization layers, and a classifier head. Change one component and the entire system's behaviour shifts.
We will walk through each stage of the architecture from input to output, introduce two critical regularisation techniques (batch normalization and dropout), explain the concept of receptive fields, and visualise the feature hierarchy that makes CNNs so effective. Two interactive demos will let you build and explore architectures hands-on.
This sub-chapter builds on Sub-chapter 4.2: The Convolution Operation and Sub-chapter 4.3: Pooling & Stride. You should be comfortable with how convolutional kernels produce feature maps and how pooling reduces spatial dimensions. Familiarity with ReLU and the concept of trainable parameters is assumed.
The Big Picture: Anatomy of a CNN
Every image classification CNN follows the same high-level pattern. Data flows through two conceptual stages:
Two Stages of a CNN
- Feature Extraction (backbone) — Alternating convolutional and pooling layers progressively transform the raw image into compact, high-level feature representations. Spatial dimensions shrink while the number of channels (feature maps) grows.
- Classification Head — The extracted features are flattened into a 1-D vector and passed through one or more fully connected (dense) layers that map the features to class probabilities.
This two-stage pattern holds from the simplest networks (LeNet-5, 1998) to modern architectures (ResNet, EfficientNet). The differences lie in the number and arrangement of layers, kernel sizes, channel depths, and the use of modern techniques like batch normalization and skip connections.
A CNN is like a multi-stage quality assurance pipeline on a construction site. Raw materials (pixels) arrive at the gate. Each inspection station (convolutional block) tests for specific properties — first checking obvious defects, then subtler issues. After each station, a summary report is created (pooling) that discards irrelevant details. Finally, the quality manager (classifier head) reads the consolidated reports and makes a pass/fail decision. The pipeline is fixed once designed, but the inspectors' criteria (kernel weights) are trained to recognise the defects that matter.
Typical Layer Ordering
Within the feature extraction stage, layers are typically arranged in repeating blocks. The most common block pattern is:
Input Image
|
v
[ Conv -> BatchNorm -> ReLU ] x N (convolutional block, repeated N times)
|
v
[ MaxPool 2x2 ] (spatial downsampling)
|
v
[ Conv -> BatchNorm -> ReLU ] x M (deeper block, more filters)
|
v
[ MaxPool 2x2 ]
|
v
... (repeat pattern, increasing filters)
|
v
[ Flatten ] (reshape 3-D feature map to 1-D vector)
|
v
[ Dense -> ReLU -> Dropout ] (fully connected layer)
|
v
[ Dense -> Softmax ] (output: class probabilities)
Let us now examine each layer type in detail, starting with the convolutional layers at the foundation.
Convolutional Layers: The Feature Detectors
You already know the mechanics of convolution from Sub-chapter 4.2. In an architecture context, the key design decisions for each convolutional layer are:
Convolutional Layer Hyperparameters
- Number of filters (channels) — How many distinct feature maps this layer produces. Common progressions: 32 → 64 → 128 → 256. More filters = more features detected, but more parameters and computation.
- Kernel size — 3×3 is the modern default. Two stacked 3×3 layers cover the same receptive field as one 5×5 layer but with fewer parameters and an extra non-linearity.
- Padding — "Same" padding preserves spatial dimensions; "valid" (no padding) shrinks them by (kernel_size − 1).
- Stride — Usually 1 within a block. Stride 2 may replace pooling for downsampling in some architectures.
Parameter Count for a Conv Layer
The number of learnable parameters in a single convolutional layer is:
params = (kernel_h x kernel_w x input_channels + 1) x num_filters
^ ^ ^
spatial kernel size bias term output channels
For example, a Conv layer with 64 filters of size 3×3 applied to an input with 32 channels has:
(3 x 3 x 32 + 1) x 64 = 289 x 64 = 18,496 parameters
Understanding this formula is essential for estimating model size and computational cost — a civil engineer's instinct for "bill of quantities" applied to neural network design.
Channel Progression: Why Filters Double
A recurring pattern in CNN design is to double the number of filters each time the spatial dimensions are halved by pooling: 32 → 64 → 128 → 256. The reasoning is practical: after 2×2 pooling cuts spatial area by 4×, doubling channels only doubles the total activations (rather than quadrupling them). This keeps the computational load roughly constant per block while allowing deeper layers to capture more complex features.
Activation Functions: Injecting Non-Linearity
Without activation functions, stacking any number of convolutional layers would be mathematically equivalent to a single linear transformation. The activation function applied after each convolution is what gives the network the power to learn complex, non-linear relationships between pixels and labels.
ReLU — Rectified Linear Unit
ReLU Definition
ReLU(x) = max(0, x) If x > 0 -> output = x (pass through) If x <= 0 -> output = 0 (clamp to zero)
ReLU is the default activation in virtually all modern CNNs. It is computationally trivial (a single comparison), avoids the vanishing gradient problem that plagued sigmoid/tanh in deep networks, and introduces sparsity by zeroing out negative values.
ReLU is applied element-wise to every value in the feature map. If a convolution kernel produces a feature map where some positions are negative (indicating the pattern was not found), ReLU sets those to zero. Positive values pass through unchanged, preserving the strength of detected features.
Why Not Sigmoid or Tanh?
Older networks used sigmoid (output range 0–1) or tanh (range −1 to 1). Both suffer from vanishing gradients: for large positive or negative inputs, the gradient approaches zero, effectively stopping learning in early layers. ReLU's gradient is either 0 (for negative inputs) or 1 (for positive inputs), so gradients flow freely through deep networks.
ReLU Variants
Several variants address the "dying ReLU" problem (neurons that output zero for all inputs and stop learning):
- Leaky ReLU: allows a small negative slope (e.g. 0.01x) instead of clamping to zero.
- PReLU (Parametric ReLU): learns the negative slope as a trainable parameter.
- ELU / SELU: smooth approximations that can produce slightly negative outputs.
In practice, standard ReLU works well for the vast majority of CNN architectures, including crack detection models.
Pooling Layers in Context
You studied pooling in depth in Sub-chapter 4.3. In the context of a full architecture, pooling layers serve as stage boundaries. After one or more Conv-BN-ReLU blocks extract features at a given spatial resolution, a 2×2 max pooling layer halves both height and width, producing a more compact representation for the next stage.
Pooling's Role in Architecture
- Reduces spatial dimensions — cuts each dimension by half, reducing total activations by 4×.
- Provides translation invariance — small shifts in the input do not change the pooled output.
- Expands the effective receptive field — after pooling, each position in the next layer "sees" a larger region of the original input.
- Zero parameters — adds no trainable weights, keeping model size constant.
A typical classification network has 3–5 pooling stages. Starting from a 224×224 input, five rounds of 2×2 max pooling yield a 7×7 feature map — compact enough to flatten and feed into a dense classifier.
The Flatten Layer: Bridging 2-D and 1-D
Convolutional and pooling layers produce 3-D tensors with shape (height × width × channels). Fully connected layers expect 1-D vectors. The flatten layer bridges these two worlds by reshaping the 3-D tensor into a single long vector.
Flatten Example
Before flatten: 7 x 7 x 256 = 12,544 values in a 3-D tensor After flatten: 12,544 values in a 1-D vector No computation occurs. No parameters. Just a reshape.
Think of it as unrolling a 3-D blueprint into a single-line bill of materials. The information is identical — only the arrangement changes.
Flatten is one of the simplest operations in a CNN, but it marks a critical architectural transition. Everything before the flatten preserves spatial structure; everything after treats the data as an unordered collection of features. This is why convolutional layers must do the heavy lifting of spatial feature extraction before the flatten point.
Fully Connected (Dense) Layers
After flattening, the feature vector passes through one or more fully connected (FC) layers, also called dense layers. In an FC layer, every input neuron is connected to every output neuron, with each connection carrying a learnable weight.
Dense Layer Parameter Count
params = (input_size + 1) x output_size
^ ^
bias per neuron neurons in this layer
Example: a dense layer connecting 12,544 inputs to 512 neurons has (12,544 + 1) × 512 = 6,422,528 parameters. Dense layers dominate the total parameter count in many CNNs.
FC layers act as the decision-making component of the network. They combine the spatial features extracted by convolutional layers into a holistic representation. A common configuration is one or two hidden FC layers (e.g. 512 or 256 neurons each) followed by the output layer.
The dense layer is the project manager reading all inspection summaries simultaneously. The convolutional layers are specialist inspectors who each examine one aspect (cracks, spalling, corrosion). The dense layer receives all their reports and combines them — "there's a crack AND it's in a load-bearing member AND there's corrosion nearby" — to make a single decision: critical repair needed or routine maintenance.
Softmax: The Output Layer
The final layer of a classification CNN uses the softmax activation function, which converts raw output values (logits) into probability estimates that sum to 1.0.
Softmax Mechanics
softmax(z_i) = exp(z_i) / sum(exp(z_j)) for all classes j
Example for crack/no-crack (2 classes):
Logits: [3.2, 1.1]
Exponentials: [24.5, 3.0]
Sum: 27.5
Probabilities: [0.89, 0.11] -> 89% crack, 11% no-crack
For a binary classification task like crack/no-crack, the output layer has 2 neurons. For multi-class problems (e.g. classifying damage into "crack", "spalling", "corrosion", "delamination", "intact") the output layer has one neuron per class. The class with the highest probability is the network's prediction.
The number of neurons in the output layer is the only place where the task definition directly shapes the architecture. Everything else — depth, width, kernel sizes — is an engineering design choice optimised through experimentation.
Batch Normalization
Introduced in 2015, batch normalization (BatchNorm) has become a near-universal component in modern CNN architectures. It normalizes the activations within each mini-batch to have zero mean and unit variance, then applies a learnable scale and shift.
BatchNorm in Four Steps
- Compute mini-batch mean — average the activations across all samples in the batch for each channel.
- Compute mini-batch variance — measure how spread out the activations are.
- Normalize — subtract the mean and divide by the standard deviation (plus a small epsilon for numerical stability).
- Scale and shift — multiply by a learnable parameter gamma and add a learnable parameter beta. This lets the network undo the normalization if that is optimal.
Why BatchNorm Helps
- Stabilizes training: prevents activations from exploding or collapsing to zero across layers, a problem called internal covariate shift.
- Allows higher learning rates: the normalized distribution makes the loss landscape smoother, so larger steps are safe.
- Acts as mild regularization: the noise introduced by batch statistics provides a slight regularisation effect, sometimes reducing the need for dropout.
BatchNorm Parameters
BatchNorm adds 4 values per channel: two learnable (gamma, beta) and two tracked statistics (running mean, running variance). For a layer with 64 channels, that is 4 × 64 = 256 values. Only gamma and beta (128 parameters) are learnable — a negligible addition compared to the convolution weights.
Batch normalization is like standardising measurement units on a multi-team construction project. Different survey crews may report deflections in millimetres, inches, or even thousandths of an inch. Before the structural engineer can compare readings across beams, all measurements must be normalised to a common scale. BatchNorm does the same for neural activations — ensuring that every layer receives inputs in a consistent, well-behaved range.
Dropout: Preventing Overfitting
Dropout is a regularization technique that randomly deactivates a fraction of neurons during each training step. At test time, all neurons are active, but their outputs are scaled down to compensate.
How Dropout Works
- During training: each neuron is independently set to zero with probability p (commonly 0.5 for FC layers, 0.2–0.3 for conv layers). The remaining neurons are scaled up by 1/(1−p) to maintain the expected output magnitude.
- During inference: no neurons are dropped. The full network is used, producing the average of all the "thinned" networks seen during training.
Dropout forces the network to learn redundant representations. No single neuron can become overly specialized because it might be absent in the next training step. This prevents co-adaptation — the phenomenon where neurons learn to depend on specific other neurons rather than contributing independently useful features.
Where to Place Dropout
- After FC layers (most common) — dropout rates of 0.5 are standard. This is where most parameters reside and overfitting risk is highest.
- After conv layers (less common) — lower dropout rates (0.1–0.25) are used because spatial correlations make aggressive dropout harmful.
- Never after the output layer — dropping outputs would randomly remove class predictions.
Dropout is like cross-training your engineering team. If the only person who understands the structural analysis software is absent, the project stalls. By randomly "removing" team members during practice exercises (training), you force the remaining staff to develop overlapping skills. When the full team is present on the real project (inference), the redundancy makes the team more resilient and capable.
Receptive Field: What Each Neuron "Sees"
The receptive field of a neuron is the region of the original input image that influences its value. In the first convolutional layer with a 3×3 kernel, each output neuron's receptive field is exactly 3×3 pixels. But as we stack layers and pooling, each deeper neuron's receptive field grows dramatically.
Receptive Field Growth
| After Layer | Receptive Field | What It Captures |
|---|---|---|
| Conv1 (3×3) | 3×3 | Individual pixel relationships |
| Conv2 (3×3) | 5×5 | Edges, small gradients |
| Pool (2×2, s=2) | 6×6 | Edges at multiple orientations |
| Conv3 (3×3) | 10×10 | Texture patches, crack segments |
| Conv4 (3×3) | 14×14 | Object parts, crack junctions |
| Pool + Conv5 | 30×30+ | Whole crack patterns, context |
The progressive growth of receptive fields is why deeper layers capture higher-level features. A neuron deep in the network might have a receptive field covering a 100×100 pixel region — large enough to recognise an entire crack pattern with surrounding concrete context.
For crack detection, ensuring that the receptive field is large enough to capture the full extent of typical cracks is a critical design consideration. Too small a receptive field and the network sees fragments without context; too large and fine details are lost.
Feature Hierarchy: Edges to Objects
One of the most profound insights about CNNs is that they automatically learn a hierarchical representation of the input. Each layer builds upon the features detected by the previous layer, creating an increasingly abstract understanding of the image.
The Four Levels of Feature Abstraction
- Layer 1 — Edges: the first convolutional layer learns to detect simple edges at various orientations (horizontal, vertical, diagonal). In concrete imagery, these correspond to sharp brightness transitions at crack boundaries.
- Layer 2 — Textures: combinations of edges form textures. Concrete grain, aggregate patterns, and surface roughness are captured here. Crack textures (thin dark lines) become distinguishable from concrete textures.
- Layer 3 — Parts: textures combine into recognisable parts — a crack segment, a patch of intact concrete, a spalling region. The network begins to "understand" meaningful structural features.
- Layer 4+ — Objects / Scenes: parts combine into full objects or scene-level representations. A branching crack pattern, a corroded rebar exposure, or a clean concrete surface are each represented as distinct activation patterns.
This hierarchical decomposition is not hand-programmed. It emerges naturally from training on labelled data. The network discovers that edges are useful building blocks for textures, textures for parts, and parts for final classification — an emergent structure remarkably similar to how human visual cortex processes images.
The feature hierarchy is like progressive levels of detail in engineering drawings. A site plan shows the building footprint (high-level, abstract). Structural drawings show individual members and connections (mid-level). Shop drawings detail every bolt, weld, and dimension (low-level, concrete). The CNN works in reverse: starting from the most detailed view (pixels) and progressively abstracting to the highest level (classification).
Case Study: Crack Classification Architecture
Let us put everything together and design a concrete (pun intended) CNN architecture for classifying 128×128 grayscale images of concrete surfaces as "crack" or "no crack".
CrackNet-Lite: Layer-by-Layer
| # | Layer | Output Shape | Params |
|---|---|---|---|
| 0 | Input | 128 × 128 × 1 | — |
| 1 | Conv2D 3×3, 32 filters, same pad | 128 × 128 × 32 | 320 |
| 2 | BatchNorm + ReLU | 128 × 128 × 32 | 64 |
| 3 | MaxPool 2×2 | 64 × 64 × 32 | 0 |
| 4 | Conv2D 3×3, 64 filters, same pad | 64 × 64 × 64 | 18,496 |
| 5 | BatchNorm + ReLU | 64 × 64 × 64 | 128 |
| 6 | MaxPool 2×2 | 32 × 32 × 64 | 0 |
| 7 | Conv2D 3×3, 128 filters, same pad | 32 × 32 × 128 | 73,856 |
| 8 | BatchNorm + ReLU | 32 × 32 × 128 | 256 |
| 9 | MaxPool 2×2 | 16 × 16 × 128 | 0 |
| 10 | Conv2D 3×3, 256 filters, same pad | 16 × 16 × 256 | 295,168 |
| 11 | BatchNorm + ReLU | 16 × 16 × 256 | 512 |
| 12 | MaxPool 2×2 | 8 × 8 × 256 | 0 |
| 13 | Flatten | 16,384 | 0 |
| 14 | Dense 256 + ReLU | 256 | 4,194,560 |
| 15 | Dropout (0.5) | 256 | 0 |
| 16 | Dense 2 + Softmax | 2 | 514 |
| Total Parameters | 4,583,874 | ||
Notice that the dense layer (#14) alone accounts for over 91% of the total parameters. This is common in CNN architectures and is precisely why Global Average Pooling (GAP) is increasingly favoured in modern designs — it eliminates the massive flatten-to-dense connection entirely.
Design Rationale
- Four conv-pool stages: progressively grow the receptive field from 3×3 to over 40×40, sufficient to capture typical concrete crack patterns.
- Filter doubling (32→64→128→256): keeps per-stage computation balanced while increasing feature capacity.
- BatchNorm after every conv: stabilises training and allows higher learning rates.
- Single dense layer + dropout: minimises overfitting risk while providing sufficient classification capacity for a binary task.
- ~4.6M parameters: small enough to train on a single GPU in minutes with a dataset of ~40,000 crack images.
Interactive Demo: CNN Architecture Builder
Use this interactive tool to build your own CNN architecture. Click the layer buttons below to add layers to the network. The visualisation shows the data flow, output shapes, and running parameter count. Experiment with different layer combinations to understand how each choice affects the network's structure.
Visualising What Each Layer Sees
Understanding the feature hierarchy is not just theoretical. Researchers have developed techniques to visualise what each layer of a trained CNN responds to. These visualisations confirm the edges-to-textures-to-parts -to-objects hierarchy and provide invaluable debugging insight.
Visualisation Techniques
- Filter visualisation: display the learned kernel weights as small images. First-layer kernels typically resemble Gabor filters (oriented edge detectors).
- Activation maps: feed an image through the network and visualise the output of each layer. Bright regions indicate where the layer "fires" — i.e. detects the feature it has learned.
- Gradient-weighted Class Activation Mapping (Grad-CAM): highlights the regions of the input image that most influence the final classification, creating a heatmap overlay.
The demo below simulates the feature hierarchy for a concrete crack image. Each stage shows an approximate representation of what the network "sees" at that depth — from raw pixel edges to the final abstract pattern that drives the crack/no-crack decision.
Interactive Demo: Feature Hierarchy Visualizer
This visualiser simulates how a CNN progressively transforms a concrete surface image through four stages of feature extraction. Use the buttons to switch between layers and observe how the representation evolves from low-level edges to high-level crack patterns.
Milestone CNN Architectures
The principles we have discussed are embodied in several landmark architectures that have shaped the field. Understanding them provides context for the design choices you will make in practice.
Key Architectures Through the Years
| Year | Name | Depth | Key Innovation |
|---|---|---|---|
| 1998 | LeNet-5 | 5 layers | Proved Conv-Pool-FC pipeline works |
| 2012 | AlexNet | 8 layers | GPU training, ReLU, dropout |
| 2014 | VGG-16 | 16 layers | Uniform 3×3 kernels, depth matters |
| 2014 | GoogLeNet | 22 layers | Inception modules, GAP |
| 2015 | ResNet | 50–152 | Skip connections, BatchNorm |
| 2019 | EfficientNet | varies | Compound scaling (depth+width+resolution) |
For civil engineering applications, ResNet-50 and EfficientNet-B0 are popular backbone choices. They offer an excellent balance of accuracy, computational efficiency, and availability of pre-trained weights (transfer learning), which we will explore in Sub-chapter 4.5.
Practical Architecture Design Guidelines
While there is no single "correct" CNN architecture, decades of research have established rules of thumb that produce reliable starting points.
Eight Design Rules for CNN Beginners
- Use 3×3 kernels. They are the most parameter-efficient way to capture spatial patterns. Stack two 3×3 layers instead of one 5×5.
- Double filters when halving spatial dimensions. After each pooling stage, double the number of filters (32 → 64 → 128 → 256).
- Use "same" padding. This preserves spatial dimensions within a block, making size calculations easier.
- Apply BatchNorm after every Conv layer. It stabilises training and usually improves accuracy.
- Use ReLU activation throughout. Only use softmax at the output layer.
- Add Dropout (0.5) before the output layer. This is the single most effective regularisation for the dense classifier head.
- Start simple. Begin with 3–4 conv-pool stages and increase complexity only if underfitting.
- Consider transfer learning first. A pre-trained ResNet or EfficientNet fine-tuned on your crack data will almost always outperform a network trained from scratch on small datasets.
Civil Engineering Application: Designing CNNs for Structural Health Monitoring
The architecture choices you make directly impact real-world deployment on bridges, buildings, and dams:
Edge Deployment
Field inspection drones have limited compute (NVIDIA Jetson, ~0.5 TFLOPS). A 5-layer CNN with depthwise separable convolutions can classify crack/no-crack at 30 FPS on-device. Deeper architectures (50+ layers) need cloud processing, adding latency.
Architecture for Bridge Inspection
Typical pipeline: Conv(3×3,32) → Pool → Conv(3×3,64) → Pool → Conv(3×3,128) → Pool → Dense(256) → Dense(4 classes: intact/crack/spall/corrosion). ~500K parameters, trains in 2 hours on 10,000 labeled images from SDNET2018.
Input Size Tradeoffs
224×224 inputs: fast, good for binary classification. 512×512: better for detecting thin cracks (<0.3mm). 1024×1024: needed for segmentation tasks but requires 16× more memory. Engineers must balance resolution against field computational constraints.
Knowledge Check
Test your understanding of CNN architecture with these four questions.
In a typical CNN architecture, which component contains the most learnable parameters?
What is the primary purpose of batch normalization in a CNN?
In the CNN feature hierarchy, what do the deepest layers typically detect?
A Conv2D layer has 128 filters of size 3×3 applied to an input with 64 channels. How many learnable parameters does it have (including bias)?
Chapter Summary
Key Takeaways
- A CNN has two stages: a feature extraction backbone (conv + pool) and a classification head (flatten + dense + softmax).
- Convolutional layers detect spatial features through learned kernels. Use 3×3 kernels and double filters when halving spatial dimensions.
- ReLU is the standard activation function. It prevents vanishing gradients and introduces non-linearity.
- Pooling layers reduce spatial dimensions, provide translation invariance, and have zero parameters.
- Flatten reshapes 3-D feature maps into a 1-D vector for the classifier head. No computation, no parameters.
- Fully connected layers combine features for classification. They dominate the parameter count.
- Softmax converts logits to class probabilities in the output layer.
- Batch normalization stabilises training by normalizing activations. Place it after every conv layer.
- Dropout prevents overfitting by randomly deactivating neurons during training.
- The receptive field grows with depth, allowing deeper layers to capture larger patterns.
- CNNs learn a feature hierarchy: edges → textures → parts → objects.