Understanding Conv2d and ConvTranspose2d

Hi, I am trying to use ConvTranspose2d to reverse the operation performed by Conv2d by using the weight in Conv2d to initialize ConvTranspose2d.

I am reading A guide to convolution arithmetic for deep
and came up with the following code to test my hypothesis about Conv2d and ConvTranspose2d. I thought that my code below should allow me to apply downsampling to an image and then perform upsampling to get the original image back. However, that does not seem to be the case. Can anyone share some insights about understanding Conv2d and ConvTranspose2d?

import torch
from torch.nn import Conv2d, ConvTranspose2d

img = torch.rand(1, 1, 3, 3, requires_grad=False)
downsample = Conv2d(in_channels=1, out_channels=1, kernel_size=3, stride=1, padding=0, bias=False)
upsample = ConvTranspose2d(in_channels=1, out_channels=1, kernel_size=3, stride=1, padding=0, bias=False)

# should I use .t() ? 
upsample.weight.data = downsample.weight.data

out = downsample(img)
inv_img = upsample(out)

torch.allclose(img, inv_img)
1 Like