CNN Cheat Sheet β€” Convolutional Neural Networks, Filters, Pooling, ResNet Dataplexa
CNN icon

Convolutional Neural Networks

convolution Β· filters Β· pooling Β· stride Β· padding Β· ResNet Β· transfer learning

Sheet 2 of 4 Deep Learning Intermediate Printable

What Is a CNN?

Foundations

A Convolutional Neural Network (CNN) is a deep learning architecture designed for grid-structured data (images, video, audio). It uses learnable filters to detect spatial patterns automatically β€” edges, textures, shapes, objects.

Layer TypeRole
Conv2DDetect local patterns using learned filters
ActivationNon-linearity β€” ReLU after each conv
BatchNormNormalize + stabilize training
PoolingDownsample β€” reduce spatial size
FlattenConvert 3D feature map β†’ 1D vector
DenseClassification or regression head
CNNs vs Dense: Dense layers connect every input to every neuron β€” too many weights for images. CNNs share filter weights spatially, making them efficient and translation-invariant.

Convolution Operation

Core Mechanism

A filter (kernel) slides over the input, computing dot products at each position to produce a feature map.

Output Size Formula
W_out = (W_in βˆ’ F + 2P) / S + 1
W = width Β· F = filter size Β· P = padding Β· S = stride
ParameterEffect
Filter size (F)3Γ—3 most common; larger = bigger receptive field
Stride (S)Step size. S=2 halves output size
Padding (P)SAME keeps size; VALID shrinks output
# Filters= # output channels / feature maps
Conv2D in Keras
keras.layers.Conv2D(
 filters=32, # number of filters
 kernel_size=(3,3), # filter size
 strides=(1,1), # stride
 padding='same', # SAME or VALID
 activation='relu' # fused activation
)

Pooling Layers

Downsampling

Pooling reduces spatial dimensions, decreasing computation and providing spatial invariance to small translations.

TypeOperationUse When
MaxPoolTake max in each windowMost common β€” preserves strongest activations
AvgPoolAverage in each windowSmoother features; used in later layers
GlobalAvgPoolOne average per channelReplaces Flatten β€” fewer parameters
GlobalMaxPoolOne max per channelCompact feature extraction
Pooling in Keras
# Standard: 2Γ—2 window, stride 2
keras.layers.MaxPooling2D(pool_size=(2,2))

# Global β€” removes spatial dims entirely
keras.layers.GlobalAveragePooling2D()

# Adaptive β€” specify output size (PyTorch)
nn.AdaptiveAvgPool2d(output_size=(1,1))
Modern trend: Replace MaxPool with strided Conv2D (stride=2). Strided convolutions are learnable β€” they often outperform fixed pooling.

Receptive Field & Feature Maps

Spatial Concepts

The receptive field is the region of the input that a neuron in a deeper layer "sees". Deeper layers have larger receptive fields and detect more abstract features.

Layer DepthDetectsReceptive Field
Conv Layer 1Edges, gradients, colours3Γ—3 – 7Γ—7
Conv Layer 2Corners, textures, curves~15Γ—15
Conv Layer 3Parts, patterns, shapes~31Γ—31
Conv Layer 4+Objects, faces, scenesFull image
Receptive Field Growth
RF_L = RF_{L-1} + (Fβˆ’1) Γ— ∏S_i
F = filter size Β· S = stride at each layer Β· stacks multiplicatively
Dilated convolutions expand the receptive field without extra parameters by inserting gaps (dilation rate r) between filter elements. Used in segmentation models.

Standard CNN Architecture Pattern

Design Blueprint
Classic Image Classifier (Keras)
from tensorflow import keras

model = keras.Sequential([
 # Block 1
 keras.layers.Conv2D(32, (3,3), padding='same', activation='relu',
 input_shape=(224,224,3)),
 keras.layers.BatchNormalization(),
 keras.layers.Conv2D(32, (3,3), padding='same', activation='relu'),
 keras.layers.MaxPooling2D((2,2)),
 keras.layers.Dropout(0.25),

 # Block 2
 keras.layers.Conv2D(64, (3,3), padding='same', activation='relu'),
 keras.layers.BatchNormalization(),
 keras.layers.Conv2D(64, (3,3), padding='same', activation='relu'),
 keras.layers.MaxPooling2D((2,2)),
 keras.layers.Dropout(0.25),

 # Classifier head
 keras.layers.GlobalAveragePooling2D(),
 keras.layers.Dense(256, activation='relu'),
 keras.layers.Dropout(0.5),
 keras.layers.Dense(10, activation='softmax')
])

CNN Design Rules

  • Double filters after each MaxPool: 32 β†’ 64 β†’ 128 β†’ 256. Spatial size halves, depth doubles.
  • Use 3Γ—3 filters throughout. Two 3Γ—3 layers have the same receptive field as one 5Γ—5 but fewer parameters.
  • BatchNorm after Conv, before activation (or after β€” both are common; before is theoretically cleaner).
  • GlobalAvgPool instead of Flatten to reduce parameters and overfitting in the classifier head.
  • Dropout 0.25 after pooling blocks, 0.5 before the final Dense.
  • He initialization for all ReLU layers β€” set kernel_initializer='he_normal'.
Parameter Count β€” Conv2D
params = FΒ² Γ— C_in Γ— C_out + C_out
F = filter size Β· C_in = input channels Β· C_out = output channels Β· +C_out for bias

Famous CNN Architectures

Timeline & Key Ideas
ArchitectureYearKey InnovationTop-1 (ImageNet)Best For
LeNet-51998First successful CNN; conv + pool patternβ€”Digit recognition (MNIST)
AlexNet2012Deep CNN on GPU; ReLU; Dropout63.3%Sparked deep learning revolution
VGG-16/192014All 3Γ—3 filters; very deep (16–19 layers)74.5%Feature extraction baseline
GoogLeNet2014Inception modules; 1Γ—1 convolutions74.8%Efficient multi-scale features
ResNet-502015Residual (skip) connections; very deep76.1%General backbone; most popular
DenseNet2017Dense connections; every layer β†’ all later77.2%Feature reuse; medical imaging
MobileNetV22018Depthwise separable conv; lightweight72.0%Mobile / edge deployment
EfficientNet-B02019Compound scaling (width+depth+resolution)77.1%Best accuracy/efficiency trade-off
ConvNeXt2022Modernized ResNet; ViT-inspired design82.1%Pure-CNN alternative to ViT
Recommendation: Use EfficientNetB0–B4 for most classification tasks. Use MobileNetV2 for mobile/edge. Use ResNet50 as a reliable baseline for transfer learning experiments.

Residual Connections (ResNet)

Skip Connections

ResNet's key innovation: skip connections that add the input directly to the output of a stack of layers. This solves the vanishing gradient problem, enabling networks with 50–152+ layers.

Residual Block Formula
y = F(x, {Wα΅’}) + x
F = learned residual function Β· x = identity shortcut
Residual Block (Keras Functional API)
def residual_block(x, filters):
 shortcut = x

 x = keras.layers.Conv2D(filters, (3,3),
 padding='same')(x)
 x = keras.layers.BatchNormalization()(x)
 x = keras.layers.Activation('relu')(x)

 x = keras.layers.Conv2D(filters, (3,3),
 padding='same')(x)
 x = keras.layers.BatchNormalization()(x)

 x = keras.layers.Add()([x, shortcut]) # skip!
 x = keras.layers.Activation('relu')(x)
 return x
Projection shortcut: When filter count changes (e.g. 64β†’128), use a 1Γ—1 Conv2D on the shortcut to match dimensions before the Add layer.

1Γ—1 Convolutions

Bottleneck

A 1Γ—1 conv applies a learned linear combination across channels at each spatial position β€” no spatial aggregation, pure channel mixing.

Use CaseHow
Channel reduction256 β†’ 64 channels before expensive 3Γ—3 conv (bottleneck)
Channel expansion64 β†’ 256 after depthwise conv (MobileNet inverted residual)
Dimension matchingMatch channels in skip connections
Pointwise mixingMix channel information without spatial context
Bottleneck Param Savings
Without: 3Β² Γ— 256 Γ— 256 = 589,824
With 1Γ—1 (64): 1Β²Γ—256Γ—64 + 3Β²Γ—64Γ—64 + 1Β²Γ—64Γ—256 = 69,632
~8.5Γ— fewer parameters β€” same receptive field
Depthwise Separable Conv (MobileNet): Depthwise (one filter per channel) + Pointwise (1Γ—1). Reduces cost by ~8–9Γ— vs standard Conv2D.

Transfer Learning

Pretrained Models

Reuse a model pretrained on a large dataset (ImageNet) as a feature extractor for a new task β€” dramatically reduces data and compute needs.

  • Load pretrained base: EfficientNet, ResNet50, MobileNetV2 with include_top=False.
  • Freeze base weights: base.trainable = False β€” only train new head.
  • Add custom head: GlobalAvgPool β†’ Dense β†’ Softmax for your classes.
  • Train head only for 5–10 epochs with higher LR (1e-3).
  • Fine-tune: Unfreeze top layers of base, retrain with low LR (1e-5).
Transfer Learning (Keras)
base = keras.applications.EfficientNetB0(
 include_top=False, weights='imagenet',
 input_shape=(224,224,3)
)
base.trainable = False # freeze base

x = keras.layers.GlobalAveragePooling2D()(base.output)
x = keras.layers.Dense(128, activation='relu')(x)
out = keras.layers.Dense(num_classes,
 activation='softmax')(x)

model = keras.Model(base.input, out)

Fine-tuning Strategy

When & How
ScenarioStrategyLR
Small data, similar domainFreeze all base; train head only1e-3
Small data, different domainFreeze early layers; unfreeze top 20%1e-4
Large data, similar domainUnfreeze all; fine-tune everything1e-4
Large data, different domainTrain from scratch or fine-tune all1e-3
Unfreeze Top Layers for Fine-tuning
# After training head, unfreeze top layers
base.trainable = True

# Keep early layers frozen
for layer in base.layers[:100]:
 layer.trainable = False

# Recompile with much lower LR
model.compile(
 optimizer=keras.optimizers.Adam(1e-5),
 loss='categorical_crossentropy'
)
Layer-wise LR decay: Use smaller LR for earlier layers, larger for later. Libraries like keras-cv support discriminative LR directly.

Data Augmentation

Image Transforms
Keras Built-in Augmentation
aug = keras.Sequential([
 layers.RandomFlip("horizontal"),
 layers.RandomRotation(0.15),
 layers.RandomZoom(0.1),
 layers.RandomContrast(0.1),
 layers.RandomBrightness(0.1),
 layers.RandomTranslation(0.1, 0.1),
], name="augmentation")
TechniqueWhen to Use
Horizontal FlipNatural images (not medical, text, digits)
Rotation Β±15Β°Most tasks; use Β±90Β° for microscopy
CutOut / ErasingForce model to use full image context
MixupBlend 2 images + labels; strong regularizer
CutMixPaste crop of one image onto another
RandAugmentAutomatic augmentation policy search
Apply only to training data β€” never augment validation or test sets. Augmentation layers in Keras are automatically off during model.predict().

Beyond Classification

Detection & Segmentation
TaskOutputKey Models
ClassificationClass labelResNet, EfficientNet, VGG
LocalizationLabel + bounding boxResNet + regression head
Object DetectionMultiple boxes + labelsYOLO, SSD, Faster R-CNN
Semantic Seg.Class per pixelU-Net, DeepLab, FCN
Instance Seg.Mask per object instanceMask R-CNN, SOLO
Pose EstimationKeypoint locationsOpenPose, HRNet
YOLO (You Only Look Once) is the go-to for real-time detection β€” single forward pass, extremely fast. U-Net dominates medical image segmentation due to its skip-connection encoder-decoder design.

CNN Hyperparameters & Troubleshooting

Tuning Guide

Key Hyperparameters

ParamTypical Values
Filter sizes3Γ—3 (default), 5Γ—5, 7Γ—7 (first layer)
Num filters32β†’64β†’128β†’256 (doubling)
Stride1 (conv), 2 (downsample)
PaddingSAME (keeps size), VALID (shrinks)
Dropout0.25 (after pool), 0.5 (before dense)
Batch size32–128 for images
LR1e-3 (Adam), 1e-5 (fine-tune)

Common Problems & Fixes

ProblemFix
High train acc, low val accMore augmentation, dropout, L2 reg
Low train + val accMore filters, more layers, longer training
Loss not decreasingLower LR, check normalization, fix data pipeline
Checkerboard artifactsUse resize-conv instead of ConvTranspose
Very slow trainingUse GPU, mixed precision, prefetch data
NaN lossLower LR, gradient clipping, check labels

Input Preprocessing

Normalize Inputs
# Scale to [0, 1]
x = x / 255.0

# ImageNet normalization
mean = [0.485,0.456,0.406]
std = [0.229,0.224,0.225]
x = (x - mean) / std

# Keras built-in per model
preprocess = keras.applications\
 .efficientnet.preprocess_input
x = preprocess(x)
Always use the preprocessing function that matches your pretrained backbone β€” each model was trained with a specific normalization.

CNN β€” Mastery Checklist

Self-Assessment

Core Concepts

  • Explain how a filter slides over an image to produce a feature map
  • Calculate output size using W_out = (Wβˆ’F+2P)/S + 1
  • Describe what MaxPool vs GlobalAvgPool does
  • Explain what the receptive field is and how it grows
  • Distinguish SAME vs VALID padding and their output sizes
  • Count parameters in a Conv2D layer: FΒ²Γ—C_inΓ—C_out + C_out

Architecture & Design

  • Build a 3-block CNN in Keras with Convβ†’BNβ†’ReLUβ†’Pool
  • Explain why residual connections help very deep networks
  • Implement a residual block using the Functional API
  • Explain what a 1Γ—1 conv does and when to use it
  • Compare EfficientNet, ResNet, and MobileNet trade-offs
  • Choose the right architecture for mobile vs server deployment

Transfer Learning & Tuning

  • Load EfficientNetB0 with include_top=False and add a custom head
  • Freeze and unfreeze base layers correctly
  • Apply the right LR for head training vs fine-tuning
  • Apply 4+ image augmentation techniques appropriately
  • Diagnose overfitting vs underfitting from learning curves
  • Preprocess inputs correctly for a given pretrained backbone
Next in Deep Learning Series
Sheet 3 Β· RNN & LSTM
sequence Β· gates Β· vanishing gradient Β· LSTM Β· GRU Β· bidirectional
RNN & LSTM Sheet β†’
← Back