PyTorch convolutional neural networks
PyTorch convolutional neural networks (Convolutional Neural Networks, CNN) are a class of deep learning models specifically designed to process data with a grid-like topology, such as images.
CNN is a core technology for computer vision tasks such as image classification, object detection, and segmentation.
The figure below shows the structure and workflow of a typical convolutional neural network (CNN) for an image recognition task.

In the figure, the CNN's output layer gives probabilities for three categories: Donald (0.2), Goofy (0.1), and Tweety (0.7), indicating that the network believes the input image is most likely Tweety.
The following is a brief description of each part:
-
Input Image: the raw image data received by the network.
-
Convolution: use a kernel to slide over the input image, extract features, and generate feature maps.
-
Pooling: usually after the convolutional layers, reduce the size of the feature maps through max pooling or average pooling while retaining important features, generating pooled feature maps.
-
Feature Extraction: progressively extract high-level features of the image through a combination of multiple convolutional and pooling layers.
-
Flatten Layer: convert the multi-dimensional feature maps into a one-dimensional vector for input to the fully connected layers.
-
Fully Connected Layer: similar to a traditional neural network layer, used to map the extracted features to output classes.
-
Classification: the network's output layer, which classifies based on the output of the fully connected layers.
-
Probabilistic Distribution: the output layer gives the probability of each category, indicating the likelihood that the input image belongs to each category.
Basic structure of a convolutional neural network
1. Input Layer
Receives the raw image data, which is usually represented as a three-dimensional array, where two dimensions represent the image's width and height, and the third dimension represents color channels (for example, an RGB image has three channels).
2. Convolutional Layer
Use a convolution kernel to extract local features such as edges and textures.
Formula:

- x: input image.
- k: convolution kernel (weight matrix).
- b: bias.
Apply a set of learnable filters (or convolution kernels) to perform convolution operations on the input image to extract local features.
Each filter slides over the input image, generating a feature map that represents the filter's activation at different positions.
A convolutional layer can have multiple filters, each generating a feature map, and all the feature maps form a set of feature maps.
3. Activation Function
A nonlinear activation function, such as ReLU (Rectified Linear Unit), is usually applied after convolutional layers to introduce nonlinearity so that the network can learn more complex patterns.
The ReLU function is defined as: f(x)=max(0,x), that is, if the input is less than 0, output 0; otherwise, output the input value.
4. Pooling Layer
- Used to reduce the spatial dimensions of the feature maps, decreasing the amount of computation and the number of parameters while retaining the most important feature information.
- The most common pooling operations are max pooling and average pooling.
- Max pooling selects the maximum value in a region, while average pooling computes the average value in a region.
** 5. Normalization Layer (optional)**
- For example, local response normalization (Local Response Normalization, LRN) or batch normalization (Batch Normalization).
- These layers help speed up the training process and improve the model's stability.
** 6. Fully Connected Layer **
- At the end of a CNN, the feature maps extracted by previous layers are flattened into a one-dimensional vector, which is then input to the fully connected layers.
- Each neuron in a fully connected layer is connected to all neurons in the previous layer, used to integrate features and perform the final classification or regression.
** 7. Output Layer **
Depending on the task, the output layer can take different forms.
For classification tasks, the Softmax function is usually used to convert the output into a probability distribution, representing the probability that the input belongs to each category.
8. Loss Function
Used to measure the difference between the model's predictions and the true labels.
Common loss functions include cross-entropy loss (Cross-Entropy Loss) for multi-class tasks and mean squared error (Mean Squared Error, MSE) for regression tasks.
9. Optimizer
Used to update the network's weights based on the gradient of the loss function. Common optimizers include stochastic gradient descent (SGD), Adam, RMSprop, etc.
10. Regularization (optional)
Includes techniques such as Dropout and L1/L2 regularization to prevent the model from overfitting.
These layers can be stacked to form deeper network structures, improving the model's learning capability.
The depth and complexity of a CNN can be adjusted according to the needs of the task.
PyTorch implementation of a CNN example
The following example shows how to build a simple CNN model with PyTorch for digit classification on the MNIST dataset.
Main steps:
- Data loading and preprocessing: When using
torchvisionLoad and preprocess the MNIST data. - Model construction: Define convolutional, pooling, and fully connected layers.
- Training: Train the model using a loss function and optimizer.
- Evaluation: Compute the model's accuracy on the test set.
- Visualization: Display some test samples and their predictions.
1. Import the necessary libraries
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
2. Data loading
Use the MNIST dataset provided by torchvision to load and preprocess the data.
Example
transform
=
transforms.
Compose
(
[
transforms.
ToTensor
(
)
,
Convert to tensor
transforms.
Normalize
(
(
0.5
,
)
,
(
0.5
,
)
)
Normalize to [-1, 1]
]
)
Load the MNIST dataset
train_dataset
=
datasets.
MNIST
(
root
=
'./data'
,
train
=
True
,
transform
=
transform
,
download
=
True
)
test_dataset
=
datasets.
MNIST
(
root
=
'./data'
,
train
=
False
,
transform
=
transform
,
download
=
True
)
train_loader
=
torch.
utils
.
data
.
DataLoader
(
dataset
=
train_dataset
,
batch_size
=
64
,
shuffle
=
True
)
test_loader
=
torch.
utils
.
data
.
DataLoader
(
dataset
=
test_dataset
,
batch_size
=
64
,
shuffle
=
False
)
3. Define the CNN model
Use
nn.Module
Build a CNN.
Example
class
SimpleCNN
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
SimpleCNN
,
self
)
.
init
(
)
Define a convolutional layer: 1 input channel, 32 output channels, kernel size 3x3
self
.
conv1
=
nn.
Conv2d
(
1
,
32
,
kernel_size
=
3
,
stride
=
1
,
padding
=
1
)
Define a convolutional layer: 32 input channels, 64 output channels
self
.
conv2
=
nn.
Conv2d
(
32
,
64
,
kernel_size
=
3
,
stride
=
1
,
padding
=
1
)
Define the fully connected layers
self
.
fc1
=
nn.
Linear
(
64
7
7
,
128
)
Input size = feature map size * number of channels
self
.
fc2
=
nn.
Linear
(
128
,
10
)
10 classes
def
forward
(
self
,
x
)
:
x
=
F.
relu
(
self
.
conv1
(
x
)
)
First convolution + ReLU
x
=
F.
max_pool2d
(
x
,
2
)
Max pooling
x
=
F.
relu
(
self
.
conv2
(
x
)
)
Second convolution + ReLU
x
=
F.
max_pool2d
(
x
,
2
)
Max pooling
x
=
x.
view
(
1
,
64
7
7
)
Flatten operation
x
=
F.
relu
(
self
.
fc1
(
x
)
)
Fully connected layer + ReLU
x
=
self
.
fc2
(
x
)
Fully connected output layer
return
x
Create a model instance
model
=
SimpleCNN
(
)
4. Define the loss function and optimizer
Use cross-entropy loss and the stochastic gradient descent optimizer.
criterion = nn.CrossEntropyLoss() # 多分类交叉熵损失
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9) # 学习率和动量
5. Train the model
Train the model for 5 epochs, printing the training loss after each epoch.
Example
num_epochs
=
5
model.
train
(
)
Set to training mode
for
epoch
in
range
(
num_epochs
)
:
total_loss
=
0
for
images
,
labels
in
train_loader:
Forward propagation
outputs
=
model
(
images
)
loss
=
criterion
(
outputs
,
labels
)
Backpropagation
optimizer.
zero_grad
(
)
loss.
backward
(
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
(
f
"Epoch [{epoch+1}/{num_epochs}], Loss: {total_loss / len(train_loader):.4f}"
)
6. Test the model
Evaluate the model's accuracy on the test set.
Example
model.
eval
(
)
Set to evaluation mode
correct
=
0
total
=
0
with
torch.
no_grad
(
)
:
No need to compute gradients during evaluation
for
images
,
labels
in
test_loader:
outputs
=
model
(
images
)
_
,
predicted
=
torch.
max
(
outputs
,
1
)
Predict the class
total +
=
labels.
size
(
0
)
correct +
=
(
predicted
==
labels
)
.
sum
(
)
.
item
(
)
accuracy
=
100
- correct / total
(
f
"Test Accuracy: {accuracy:.2f}%"
)
7. Complete code
The complete code is as follows:
Example
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
import
torch.
optim
as
optim
from
torchvision
import
datasets
,
transforms
1. Data loading and preprocessing
transform
=
transforms.
Compose
(
[
transforms.
ToTensor
(
)
,
Convert to tensor
transforms.
Normalize
(
(
0.5
,
)
,
(
0.5
,
)
)
Normalize to [-1, 1]
]
)
Load the MNIST dataset
train_dataset
=
datasets.
MNIST
(
root
=
'./data'
,
train
=
True
,
transform
=
transform
,
download
=
True
)
test_dataset
=
datasets.
MNIST
(
root
=
'./data'
,
train
=
False
,
transform
=
transform
,
download
=
True
)
train_loader
=
torch.
utils
.
data
.
DataLoader
(
dataset
=
train_dataset
,
batch_size
=
64
,
shuffle
=
True
)
test_loader
=
torch.
utils
.
data
.
DataLoader
(
dataset
=
test_dataset
,
batch_size
=
64
,
shuffle
=
False
)
2. Define the CNN model
class
SimpleCNN
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
SimpleCNN
,
self
)
.
init
(
)
Define convolutional layers
self
.
conv1
=
nn.
Conv2d
(
1
,
32
,
kernel_size
=
3
,
stride
=
1
,
padding
=
1
)
1 input channel, 32 output channels
self
.
conv2
=
nn.
Conv2d
(
32
,
64
,
kernel_size
=
3
,
stride
=
1
,
padding
=
1
)
32 input channels, 64 output channels
Define the fully connected layers
self
.
fc1
=
nn.
Linear
(
64
7
7
,
128
)
Flatten before feeding into the fully connected layer
self
.
fc2
=
nn.
Linear
(
128
,
10
)
10 classes
def
forward
(
self
,
x
)
:
x
=
F.
relu
(
self
.
conv1
(
x
)
)
First convolution + ReLU
x
=
F.
max_pool2d
(
x
,
2
)
Max pooling
x
=
F.
relu
(
self
.
conv2
(
x
)
)
Second convolution + ReLU
x
=
F.
max_pool2d
(
x
,
2
)
Max pooling
x
=
x.
view
(
1
,
64
7
7
)
Flatten
x
=
F.
relu
(
self
.
fc1
(
x
)
)
Fully connected layer + ReLU
x
=
self
.
fc2
(
x
)
Output of the final layer
return
x
Create a model instance
model
=
SimpleCNN
(
)
3. Define the loss function and optimizer
criterion
=
nn.
CrossEntropyLoss
(
)
Multi-class cross-entropy loss
optimizer
=
optim.
SGD
(
model.
parameters
(
)
,
lr
=
0.01
,
momentum
=
0.9
)
4. Model training
num_epochs
=
5
model.
train
(
)
Set the model to training mode
for
epoch
in
range
(
num_epochs
)
:
total_loss
=
0
for
images
,
labels
in
train_loader:
outputs
=
model
(
images
)
Forward propagation
loss
=
criterion
(
outputs
,
labels
)
Compute the loss
optimizer.
zero_grad
(
)
Clear the gradients
loss.
backward
(
)
Backpropagation
optimizer.
step
(
)
Update parameters
total_loss +
=
loss.
item
(
)
(
f
"Epoch [{epoch+1}/{num_epochs}], Loss: {total_loss / len(train_loader):.4f}"
)
5. Model testing
model.
eval
(
)
Set the model to evaluation mode
correct
=
0
total
=
0
with
torch.
no_grad
(
)
:
Disable gradient computation
for
images
,
labels
in
test_loader:
outputs
=
model
(
images
)
_
,
predicted
=
torch.
max
(
outputs
,
1
)
total +
=
labels.
size
(
0
)
correct +
=
(
predicted
==
labels
)
.
sum
(
)
.
item
(
)
accuracy
=
100
- correct / total
(
f
"Test Accuracy: {accuracy:.2f}%"
)
Explanation of the results
1. Output training loss
The code prints the average loss once per epoch, for example:
Epoch [1/5], Loss: 0.2325
Epoch [2/5], Loss: 0.0526
Epoch [3/5], Loss: 0.0366
Epoch [4/5], Loss: 0.0273
Epoch [5/5], Loss: 0.0221
**Explanation:** A steadily decreasing loss indicates the model is gradually converging.
2. Accuracy on the test set
The code prints the final classification accuracy on the test set, for example:
Test Accuracy: 98.96%
**Explanation:** The model achieves 98.96% classification accuracy on the MNIST test set, a solid result for a simple CNN model.
7. Visualize the results
We can visualize some samples from the test data along with their predictions.
Example
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
import
torch.
optim
as
optim
from
torchvision
import
datasets
,
transforms
import
matplotlib.
pyplot
as
plt
1. Data loading and preprocessing
transform
=
transforms.
Compose
(
[
transforms.
ToTensor
(
)
,
Convert to tensor
transforms.
Normalize
(
(
0.5
,
)
,
(
0.5
,
)
)
Normalize to [-1, 1]
]
)
Load the MNIST dataset
train_dataset
=
datasets.
MNIST
(
root
=
'./data'
,
train
=
True
,
transform
=
transform
,
download
=
True
)
test_dataset
=
datasets.
MNIST
(
root
=
'./data'
,
train
=
False
,
transform
=
transform
,
download
=
True
)
train_loader
=
torch.
utils
.
data
.
DataLoader
(
dataset
=
train_dataset
,
batch_size
=
64
,
shuffle
=
True
)
test_loader
=
torch.
utils
.
data
.
DataLoader
(
dataset
=
test_dataset
,
batch_size
=
64
,
shuffle
=
False
)
2. Define the CNN model
class
SimpleCNN
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
SimpleCNN
,
self
)
.
init
(
)
Define convolutional layers
self
.
conv1
=
nn.
Conv2d
(
1
,
32
,
kernel_size
=
3
,
stride
=
1
,
padding
=
1
)
1 input channel, 32 output channels
self
.
conv2
=
nn.
Conv2d
(
32
,
64
,
kernel_size
=
3
,
stride
=
1
,
padding
=
1
)
32 input channels, 64 output channels
Define the fully connected layers
self
.
fc1
=
nn.
Linear
(
64
7
7
,
128
)
Flatten before feeding into the fully connected layer
self
.
fc2
=
nn.
Linear
(
128
,
10
)
10 classes
def
forward
(
self
,
x
)
:
x
=
F.
relu
(
self
.
conv1
(
x
)
)
First convolution + ReLU
x
=
F.
max_pool2d
(
x
,
2
)
Max pooling
x
=
F.
relu
(
self
.
conv2
(
x
)
)
Second convolution + ReLU
x
=
F.
max_pool2d
(
x
,
2
)
Max pooling
x
=
x.
view
(
1
,
64
7
7
)
Flatten
x
=
F.
relu
(
self
.
fc1
(
x
)
)
Fully connected layer + ReLU
x
=
self
.
fc2
(
x
)
Output of the final layer
return
x
Create a model instance
model
=
SimpleCNN
(
)
3. Define the loss function and optimizer
criterion
=
nn.
CrossEntropyLoss
(
)
Multi-class cross-entropy loss
optimizer
=
optim.
SGD
(
model.
parameters
(
)
,
lr
=
0.01
,
momentum
=
0.9
)
4. Model training
num_epochs
=
5
model.
train
(
)
Set the model to training mode
for
epoch
in
range
(
num_epochs
)
:
total_loss
=
0
for
images
,
labels
in
train_loader:
outputs
=
model
(
images
)
Forward propagation
loss
=
criterion
(
outputs
,
labels
)
Compute the loss
optimizer.
zero_grad
(
)
Clear the gradients
loss.
backward
(
)
Backpropagation
optimizer.
step
(
)
Update parameters
total_loss +
=
loss.
item
(
)
(
f
"Epoch [{epoch+1}/{num_epochs}], Loss: {total_loss / len(train_loader):.4f}"
)
5. Model testing
model.
eval
(
)
Set the model to evaluation mode
correct
=
0
total
=
0
with
torch.
no_grad
(
)
:
Disable gradient computation
for
images
,
labels
in
test_loader:
outputs
=
model
(
images
)
_
,
predicted
=
torch.
max
(
outputs
,
1
)
total +
=
labels.
size
(
0
)
correct +
=
(
predicted
==
labels
)
.
sum
(
)
.
item
(
)
accuracy
=
100
- correct / total
(
f
"Test Accuracy: {accuracy:.2f}%"
)
6. Visualize the test results
dataiter
=
iter
(
test_loader
)
images
,
labels
=
next
(
dataiter
)
outputs
=
model
(
images
)
_
,
predictions
=
torch.
max
(
outputs
,
1
)
fig
,
axes
=
plt.
subplots
(
1
,
6
,
figsize
=
(
12
,
4
)
)
for
i
in
range
(
6
)
:
axes
[
i
]
.
imshow
(
images
[
i
]
[
0
]
,
cmap
=
'gray'
)
axes
[
i
]
.
set_title
(
f
"Label: {labels[i]}\nPred: {predictions[i]}"
)
axes
[
i
]
.
axis
(
'off'
)
plt.
show
(
)
The visualization shows the actual labels and predicted values for 6 test samples, for example:

-
The top-left of each image is the handwritten digit.
-
The title shows the model's prediction and the true label.
Note a few common errors
When downloading the MNIST dataset, data cannot be fetched because SSL certificate verification failed.
Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
Failed to download (trying next):
...
Solution
Open a terminal and run the following command to install/update SSL certificates:
/Applications/Python\ 3.x/Install\ Certificates.command
Replace 3.x with the Python version you actually have installed.
After running this command, rerun your Python code; it should then download the MNIST dataset successfully.