9.3. Building a Basic CNN in PyTorch
Table of Contents
From Idea to `nn.Module`
A basic convolutional neural network in PyTorch is usually built from a small stack of convolution blocks that turn an image tensor into a set of learned feature maps, followed by a classifier head that converts those features into class scores. In code, you package this into an nn.Module so it can be moved across devices, participate in autograd, and expose parameters to an optimizer.
The input you will typically feed to a CNN has shape $(N, C, H, W)$, where $N$ is batch size, $C$ is channels, and $H, W$ are height and width. For example, RGB images are usually $C=3$. Your model’s forward pass should accept that tensor and return logits of shape $(N, \text{num\_classes})$ for classification.
A Minimal CNN Architecture
A common beginner friendly template is two convolution blocks plus a small fully connected head. Each block is usually a convolution plus a nonlinearity, and often some spatial downsampling so the feature maps shrink as depth increases.
Here is a compact, standard implementation:
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicCNN(nn.Module):
def __init__(self, in_channels: int = 3, num_classes: int = 10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(in_channels, 16, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2), # H,W -> H/2,W/2
nn.Conv2d(16, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2), # H,W -> H/4,W/4
)
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(32 * 8 * 8, 128), # assumes input images are 32x32
nn.ReLU(),
nn.Linear(128, num_classes)
)
def forward(self, x):
x = self.features(x)
x = self.classifier(x)
return xThis example assumes your input images are $32 \times 32$. After two $2 \times 2$ max pools, the spatial size becomes $8 \times 8$, so the flattened feature vector has length $32 \cdot 8 \cdot 8$.
:::danger :::
Your first Linear layer must match the flattened size coming out of the conv stack. If you change the number of pools, strides, or the input image size, you must update this dimension or compute it dynamically.
Making the Classifier Head Robust to Input Size
Beginners often run into shape mismatches when they switch datasets with different image sizes. You can avoid hard coding the spatial size by using global pooling that reduces each channel to a single number. In PyTorch, AdaptiveAvgPool2d((1, 1)) converts any $(N, C, H, W)$ into $(N, C, 1, 1)$.
class BasicCNNAdaptive(nn.Module):
def __init__(self, in_channels: int = 3, num_classes: int = 10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(in_channels, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(32, 64, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
)
self.pool = nn.AdaptiveAvgPool2d((1, 1))
self.classifier = nn.Linear(64, num_classes)
def forward(self, x):
x = self.features(x)
x = self.pool(x)
x = torch.flatten(x, 1) # (N, 64)
x = self.classifier(x)
return xThis version works for many input sizes without modification, as long as the feature extractor produces a reasonable spatial resolution before the adaptive pool.
:::danger :::
For multi class classification, return raw logits, not softmax probabilities. Use nn.CrossEntropyLoss, which applies log_softmax internally.
Sanity Checking Shapes with a Dummy Forward Pass
Before training, you should run a single forward pass with a fake batch and confirm that the output shape matches what your loss expects.
model = BasicCNNAdaptive(in_channels=3, num_classes=10)
x = torch.randn(4, 3, 64, 64) # batch of 4 images
logits = model(x)
print(logits.shape) # should be torch.Size([4, 10])If you see a runtime error about matrix multiplication sizes in a linear layer, it means your flatten size and linear input size disagree, or you forgot to flatten.
A Complete Minimal Training Step for the CNN
The training loop structure is covered elsewhere, but it helps to see how the CNN plugs into it. The key is that the CNN outputs logits, you compute loss against integer class labels, then run backprop and an optimizer step.
model = BasicCNNAdaptive(in_channels=3, num_classes=10)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
x = torch.randn(8, 3, 64, 64) # images
y = torch.randint(0, 10, (8,)) # class indices
model.train()
optimizer.zero_grad()
logits = model(x)
loss = criterion(logits, y)
loss.backward()
optimizer.step()
:::danger ::>
CrossEntropyLoss expects targets of shape (N,) with dtype torch.long containing class indices in [0, num_classes-1]. Do not one hot encode the labels for this loss.
Small Practical Implementation Choices
A basic CNN often improves if you add normalization after convolutions. A typical pattern is Conv2d -> BatchNorm2d -> ReLU. If you later add batch normalization, keep in mind that model mode matters, since model.train() and model.eval() change how batch norm behaves.
Another simple improvement is to keep the model definition readable by separating feature extraction and classification into named submodules, as shown above, and keeping forward short so that shape flow is easy to track.
Common Beginner Errors Specific to Basic CNNs
One frequent issue is swapping tensor layout. Many image tools produce (H, W, C) arrays, but Conv2d expects (N, C, H, W). Your preprocessing should ensure channels come before height and width, and you should add a batch dimension.
Another common issue is mismatched channel counts. If your dataset is grayscale, your input has $C=1$, so you must set in_channels=1 in the first Conv2d or convert grayscale to three channels during preprocessing.
:::danger :::
If the first convolution is defined with in_channels=3 but your input batch is (N, 1, H, W), PyTorch will raise a clear error. Fix it by matching in_channels to the data, not by reshaping channels incorrectly.
What You Have After This Chapter
At this point you have a working CNN nn.Module that accepts image batches, produces logits, can be sanity checked with dummy inputs, and can be trained with standard PyTorch losses and optimizers. The next steps are usually improving data and training quality, which are handled in the surrounding chapters on augmentation, transfer learning, and fine tuning.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Orientation and Learning Setup
- ☰ 1.1. Course Goals and How to Use This Outline
- ☰ 1.2. What You Need to Know Before Starting
- ☰ 1.3. Installing Python and PyTorch
- ☰ 1.4. Choosing CPU vs CUDA vs Apple Silicon
- ☰ 1.5. Using Jupyter, VS Code, and Scripts
- ☰ 1.6. Reproducibility, Seeds, and Determinism
-
- ☰ 2. Python and PyTorch Fundamentals
- ☰ 2.1. Tensors and Basic Operations
- ☰ 2.2. Tensor Shapes, Dtypes, and Devices
- ☰ 2.3. Indexing, Slicing, and Broadcasting
- ☰ 2.4. Autograd and Computational Graphs
- ☰ 2.5. Common Tensor Pitfalls and Debugging
- ☰ 2.6. Saving and Loading Tensors
-
- ☰ 3. Neural Network Building Blocks
- ☰ 3.1. Linear Layers and Affine Transforms
- ☰ 3.2. Activation Functions
- ☰ 3.3. Loss Functions
- ☰ 3.4. Optimizers and Learning Rates
- ☰ 3.5. Regularization Basics
- ☰ 3.6. Weight Initialization Concepts
-
- ☰ 4. First Models End to End
- ☰ 4.1. A Simple Regression Model
- ☰ 4.2. A Simple Classification Model
- ☰ 4.3. Data Splitting and Validation Sets
- ☰ 4.4. Training Loop Structure
- ☰ 4.5. Tracking Loss and Metrics
- ☰ 4.6. Basic Overfitting and Underfitting Checks
-
- ☰ 5. Data Handling with PyTorch
- ☰ 5.1. Datasets and DataLoaders
- ☰ 5.2. Transforms and Preprocessing
- ☰ 5.3. Collate Functions and Batching
- ☰ 5.4. Shuffling, Sampling, and Class Imbalance
- ☰ 5.5. Working with Tabular, Text, and Image Data
- ☰ 5.6. Data Pipeline Performance Basics
-
- ☰ 6. Training Loops in Practice
- ☰ 6.1. Forward Pass and Backward Pass
- ☰ 6.2. Gradient Zeroing and Accumulation
- ☰ 6.3. Device Placement and Mixed Precision Basics
- ☰ 6.4. Learning Rate Schedules
- ☰ 6.5. Gradient Clipping
- ☰ 6.6. Logging with TensorBoard
-
- ☰ 7. Debugging and Model Troubleshooting
- ☰ 7.1. Verifying Shapes and NaNs
- ☰ 7.2. Checking Gradients and Vanishing Gradients
- ☰ 7.3. Sanity Checks and Overfit a Small Batch
- ☰ 7.4. Common Causes of Training Instability
- ☰ 7.5. Interpreting Learning Curves
- ☰ 7.6. Practical Tips for Faster Iteration
-
- ☰ 8. Feedforward Networks for Structured Data
- ☰ 8.1. Feature Scaling and Normalization
- ☰ 8.2. Embeddings for Categorical Features
- ☰ 8.3. Multi-Layer Perceptrons in PyTorch
- ☰ 8.4. Choosing Hidden Sizes and Depth
- ☰ 8.5. Evaluation Metrics for Classification and Regression
- ☰ 8.6. Model Export and Inference Basics
-
- ☰ 9. Convolutional Neural Networks for Images
- ☰ 9.1. Convolutions, Padding, and Stride
- ☰ 9.2. Pooling and Feature Maps
- ☰ 9.3. Building a Basic CNN in PyTorch
- ☰ 9.4. Data Augmentation for Vision
- ☰ 9.5. Transfer Learning with Pretrained Models
- ☰ 9.6. Fine-Tuning and Freezing Layers
-
- ☰ 10. Recurrent and Sequence Models
- ☰ 10.1. Sequences, Tokens, and Padding
- ☰ 10.2. RNNs, LSTMs, and GRUs
- ☰ 10.3. Handling Variable-Length Sequences
- ☰ 10.4. Teacher Forcing and Sequence Losses
- ☰ 10.5. Basic Text Classification Pipeline
- ☰ 10.6. Simple Sequence-to-Sequence Overview
-
- ☰ 11. Attention and Transformers Fundamentals
- ☰ 11.1. Why Attention Helps
- ☰ 11.2. Self-Attention Intuition
- ☰ 11.3. Transformer Building Blocks
- ☰ 11.4. Using Transformer Models in PyTorch
- ☰ 11.5. Fine-Tuning for Text Classification
- ☰ 11.6. Managing Tokenizers and Batching
-
- ☰ 12. Model Evaluation and Experiment Management
- ☰ 12.1. Train, Validation, and Test Best Practices
- ☰ 12.2. Cross-Validation Basics
- ☰ 12.3. Calibration and Thresholding
- ☰ 12.4. Error Analysis and Confusion Matrices
- ☰ 12.5. Experiment Tracking Concepts
- ☰ 12.6. Comparing Models Fairly
-
- ☰ 13. Saving, Loading, and Deployment Readiness
- ☰ 13.1. Saving Model Weights and Full Checkpoints
- ☰ 13.2. Loading for Inference and Resuming Training
- ☰ 13.3. TorchScript and Tracing Basics
- ☰ 13.4. Exporting to ONNX Overview
- ☰ 13.5. Batch Inference and Latency Considerations
- ☰ 13.6. Reproducible Packaging of Code and Weights
-
- ☰ 14. Performance and Scaling Basics
- ☰ 14.1. Profiling and Bottleneck Identification
- ☰ 14.2. DataLoader Optimization
- ☰ 14.3. GPU Utilization and Memory Management
- ☰ 14.4. Gradient Accumulation for Large Batches
- ☰ 14.5. Distributed Training Concepts Overview
- ☰ 14.6. Practical Guidelines for Faster Training
-
- ☰ 15. Best Practices and Next Steps
- ☰ 15.1. Choosing Hyperparameters Systematically
- ☰ 15.2. Regularization and Generalization Toolkit
- ☰ 15.3. Responsible Use and Dataset Considerations
- ☰ 15.4. Reading PyTorch Documentation Effectively
- ☰ 15.5. Suggested Projects for Beginners
- ☰ 15.6. Pathways to Advanced Topics
-
Comments
Please login to add a comment.
Don't have an account? Register now!