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

PyTorch torch.nn.Conv2d function

PyTorch torch.nn.Conv2d function

PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual


torch.nn.Conv2d is the module for two-dimensional convolution in PyTorch, and a core component of convolutional neural networks (CNNs).

It extracts spatial features by applying learnable convolution kernels to the input tensor, and is widely used in image processing and computer vision tasks.

Function definition



torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')

Parameter Description:

property through the following steps:


Usage examples

Example 1: Basic usage

Create a simple two-dimensional convolution layer:

Example

import

torch

import

torch.

nn

as

nn

Create a convolution layer: 3 input channels, 32 output channels, 3x3 kernel

conv

=

nn.

Conv2d

(

in_channels

=

3

,

out_channels

=

32

,

kernel_size

=

3

)

Print the shapes of the weights and bias

print

(

"Weight shape:"

,

conv.

weight

.

shape

)

 

torch.Size([32, 3, 3, 3])

print

(

"Bias shape:"

,

conv.

bias

.

shape

)

   

torch.Size([32])

Create an input tensor: batch=1, channels=3, height=32, width=32

input_tensor

=

torch.

randn

(

1

,

3

,

32

,

32

)

Forward propagation

output

=

conv

(

input_tensor

)

print

(

"Input shape:"

,

input_tensor.

shape

)

 

torch.Size([1, 3, 32, 32])

print

(

"Output shape:"

,

output.

shape

)

     

torch.Size([1, 32, 30, 30])

The output is:



权重形状: torch.Size([32, 3, 3, 3])

偏置形状: torch.Size([32])

输入形状: torch.Size([1, 3, 32, 32])

输出形状: torch.Size([1, 32, 30, 30])

By default, padding=0, so the output size decreases. To keep the size, you can add padding.

Example 2: Use padding to preserve size

Adding padding can keep the input and output sizes consistent:

Example

import

torch

import

torch.

nn

as

nn

Create a convolution layer with padding: padding=1 preserves the size

conv_pad

=

nn.

Conv2d

(

in_channels

=

3

,

out_channels

=

32

,

kernel_size

=

3

,

padding

=

1

)

Input

input_tensor

=

torch.

randn

(

1

,

3

,

32

,

32

)

Forward propagation

output

=

conv_pad

(

input_tensor

)

print

(

"Input shape:"

,

input_tensor.

shape

)

print

(

"Output shape:"

,

output.

shape

)

 

Preserves 32x32

The output is:



输入形状: torch.Size([1, 3, 32, 32])

输出形状: torch.Size([1, 32, 32, 32])

Example 3: Different stride and dilation

Adjusting stride and dilation can change the output size and receptive field:

Example

import

torch

import

torch.

nn

as

nn

Strided convolution: stride=2 reduces the size

conv_stride

=

nn.

Conv2d

(

3

,

32

,

kernel_size

=

3

,

stride

=

2

,

padding

=

1

)

input_tensor

=

torch.

randn

(

1

,

3

,

32

,

32

)

output_stride

=

conv_stride

(

input_tensor

)

print

(

"Stride=2 -> output shape:"

,

output_stride.

shape

)

Dilated convolution: dilation=2 enlarges the receptive field

conv_dilation

=

nn.

Conv2d

(

3

,

32

,

kernel_size

=

3

,

dilation

=

2

)

output_dilation

=

conv_dilation

(

input_tensor

)

print

(

"Dilation=2 -> output shape:"

,

output_dilation.

shape

)

The output is:



Stride=2 -> 输出形状: torch.Size([1, 32, 16, 16])

Dilation=2 -> 输出形状: torch.Size([1, 32, 28, 28])

Example 4: Grouped convolution

The groups parameter enables grouped convolution, commonly used in lightweight networks:

Example

import

torch

import

torch.

nn

as

nn

Grouped convolution: groups=2 splits the input into 2 groups

conv_group

=

nn.

Conv2d

(

in_channels

=

4

,

out_channels

=

8

,

kernel_size

=

3

,

groups

=

2

)

Input with 4 channels

input_tensor

=

torch.

randn

(

1

,

4

,

16

,

16

)

Forward propagation

output

=

conv_group

(

input_tensor

)

print

(

"Input shape:"

,

input_tensor.

shape

)

print

(

"Output shape:"

,

output.

shape

)

print

(

"Weight shape:"

,

conv_group.

weight

.

shape

)

 

The weight shape differs after grouping

The output is:



输入形状: torch.Size([1, 4, 16, 16])

输出形状: torch.Size([1, 8, 14, 14])

权重形状: torch.Size([8, 2, 3, 3])

Example 5: Use in a neural network

Build a simple handwritten digit recognition network:

Example

import

torch

import

torch.

nn

as

nn

class

SimpleCNN

(

nn.

Module

)

:

   

def

init

(

self

,

num_classes

=

10

)

:

       

super

(

SimpleCNN

,

self

)

.

init

(

)

       

First convolution block

       

self

.

conv1

=

nn.

Conv2d

(

1

,

32

,

kernel_size

=

3

,

padding

=

1

)

       

self

.

bn1

=

nn.

BatchNorm2d

(

32

)

       

self

.

relu1

=

nn.

ReLU

(

)

       

Second convolution block

       

self

.

conv2

=

nn.

Conv2d

(

32

,

64

,

kernel_size

=

3

,

padding

=

1

)

       

self

.

bn2

=

nn.

BatchNorm2d

(

64

)

       

self

.

relu2

=

nn.

ReLU

(

)

       

Pooling layers

       

self

.

pool

=

nn.

MaxPool2d

(

2

,

2

)

       

Fully connected layer

       

self

.

fc

=

nn.

Linear

(

64

7

7

,

num_classes

)

   

def

forward

(

self

,

x

)

:

       

First convolution block

        x

=

self

.

conv1

(

x

)

        x

=

self

.

bn1

(

x

)

        x

=

self

.

relu1

(

x

)

        x

=

self

.

pool

(

x

)

       

Second convolution block

        x

=

self

.

conv2

(

x

)

        x

=

self

.

bn2

(

x

)

        x

=

self

.

relu2

(

x

)

        x

=

self

.

pool

(

x

)

       

Flatten and classify

        x

=

x.

view

(

x.

size

(

0

)

,

1

)

        x

=

self

.

fc

(

x

)

       

return

x

Create the model

model

=

SimpleCNN

(

num_classes

=

10

)

Test input: batch=4, grayscale image 28x28

input_image

=

torch.

randn

(

4

,

1

,

28

,

28

)

output

=

model

(

input_image

)

print

(

"Input shape:"

,

input_image.

shape

)

print

(

"Output shape:"

,

output.

shape

)

 

torch.Size([4, 10])


Output size calculation

The formula for calculating the output size of a convolution layer:



H_out = floor((H_in + 2 * padding[0] - dilation[0] * (kernel_size[0] - 1) - 1) / stride[0]) + 1

W_out = floor((W_in + 2 * padding[1] - dilation[1] * (kernel_size[1] - 1) - 1) / stride[1]) + 1


Common questions

Q1: How to choose the kernel size?

Common kernel sizes:

Q2: How to choose padding and stride?


Use Cases

nn.Conv2d is one of the most important layers in computer vision; main application scenarios include:

Tip: In modern CNNs, 3x3 convolutions are the most common; they cover sufficient spatial information while keeping the parameter count small.


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual