jaytimbadia
(Jay Timbadia)
September 25, 2024, 8:52am
1
Hello there,
I was wondering what is the amount of padding used when I put padding = “same” in conv2D!
I have an image.
import torch
image = torch.randn((1, 3 ,224, 224))
conv2 = torch.nn.Conv2d(
in_channels=3,
out_channels=5,
kernel_size=16,
stride=1,
padding='same'
)
conv2(image).shape # 1, 5, 224, 224
But how to know what amount of padding has been used?
Since I have manually checked using padding = 4,5,6,7,8.
None of the padding gives 224 as output shape.
So that means is it using fractional padding?
Jay
Soumya_Kundu
(Soumya Snigdha Kundu)
September 25, 2024, 10:21am
2
Yes!
Not sure unfortunately. Afaik, it’s been handled internally. There may be some way to print it.
I think this is a nice hardcoded way to check?
kernel_size = conv2.kernel_size
if isinstance(kernel_size, int):
padding = kernel_size // 2
else:
padding = (kernel_size[0] // 2, kernel_size[1] // 2)
print(f"Padding used: {padding}")
output = conv2(image)
print(f"Output shape: {output.shape}")
jaytimbadia
(Jay Timbadia)
September 25, 2024, 10:47am
3
Thanks @Soumya_Kundu for your reply!
With the code you provided, value of padding is coming as 8, but if we put 8 back, its nor preserving the image dimension.
Jay
jaytimbadia
(Jay Timbadia)
September 25, 2024, 4:50pm
4
Can anyone please help here?
ptrblck
September 26, 2024, 8:08pm
5
You could check conv2._reversed_padding_repeated_twice
and use F.pad
before applying the convolution to get the same output, but keep in mind it’s an internal attribute and could change in the future.