Last active
January 25, 2021 13:41
-
-
Save hccho2/ebf352d843897e351110bdeaa3bb00a5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
import numpy as np | |
from torch import nn | |
import torch.nn.functional as F | |
H=4;W=3 | |
pad = 1 | |
stride=2 | |
kernel_size = 3 | |
image = np.arange(H*W).reshape(1,1,H,W).astype(np.float32) # (N,C,H,W) random image | |
image = torch.tensor(image) | |
print("random image", image) | |
weight = torch.randn(1,1,kernel_size,kernel_size) | |
out = F.conv_transpose2d(image,weight,padding=pad,stride=stride) | |
print(f'output size: {(H-1)*stride - 2*pad+ + kernel_size} x {(W-1)*stride - 2*pad+ + kernel_size}') | |
print(f'weight: {weight}') | |
print(f'output: {out}') | |
##################################################### | |
##################################################### | |
# transpose convolution by normal convolution | |
image_stride = np.zeros((1,1,(H-1)*stride+1,(W-1)*stride+1)) | |
image_stride[:,:,::stride,::stride] = image | |
image_stride = torch.tensor(image_stride,dtype=torch.float32) | |
print('new image', image_stride) | |
image_padded = F.pad(image_stride,(kernel_size-1 - pad,kernel_size-1 - pad,kernel_size-1 - pad,kernel_size-1 - pad)) | |
print("padded image", image_padded) | |
out2 = F.conv2d(image_padded,torch.flip(weight,[2,3]),padding=0,stride = 1) | |
print(f'manual output: {out2}') |
Author
hccho2
commented
Jan 25, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment