22.02.2024 Views

Daniel Voigt Godoy - Deep Learning with PyTorch Step-by-Step A Beginner’s Guide-leanpub

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

In code, as usual, PyTorch gives us two options: functional (F.pad()) and module

(nn.ConstantPad2d). Let’s start with the module version this time:

constant_padder = nn.ConstantPad2d(padding=1, value=0)

constant_padder(image)

Output

tensor([[[[0., 0., 0., 0., 0., 0., 0., 0.],

[0., 5., 0., 8., 7., 8., 1., 0.],

[0., 1., 9., 5., 0., 7., 7., 0.],

[0., 6., 0., 2., 4., 6., 6., 0.],

[0., 9., 7., 6., 6., 8., 4., 0.],

[0., 8., 3., 8., 5., 1., 3., 0.],

[0., 7., 2., 7., 0., 1., 0., 0.],

[0., 0., 0., 0., 0., 0., 0., 0.]]]])

There are two arguments: padding, for the number of columns and rows to be

stuffed in the image; and value, for the value that is filling these new columns and

rows. One can also do asymmetric padding by specifying a tuple in the padding

argument representing (left, right, top, bottom). So, if we were to stuff our

image on the left and right sides only, the argument would go like this: (1, 1, 0,

0).

We can achieve the same result using the functional padding:

padded = F.pad(image, pad=(1, 1, 1, 1), mode='constant', value=0)

In the functional version, one must specify the padding as a tuple. The value

argument is straightforward, and there is yet another argument, mode, which was

set to constant to match the module version above.

Convolutions | 359

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!