Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch convolutional neural networks

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:

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:

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

** 5. Normalization Layer (optional)**

** 6. Fully Connected Layer **

** 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:

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

(

)

   

print

(

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

print

(

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

(

)

   

print

(

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

print

(

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

(

)

   

print

(

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

print

(

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:

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.