Skip to content

Instantly share code, notes, and snippets.

@AhmadMoussa
Created December 8, 2019 07:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AhmadMoussa/d32c41c11366440bc5eaf4efb48a2e73 to your computer and use it in GitHub Desktop.
Save AhmadMoussa/d32c41c11366440bc5eaf4efb48a2e73 to your computer and use it in GitHub Desktop.
Calculate padding of Conv1D and ConvTranspose1D in pytorch
import math
def calculatePadding(L, KSZ, S, D, deconv = False):
'''
:param L: Input length (or width)
:param KSZ: Kernel size (or width)
:param S: Stride
:param D: Dilation Factor
:return: Returns padding such that output width is exactly half of input width
'''
if not deconv:
return math.ceil((S * (L/2) - L + D * (KSZ - 1)-1)/2)
else:
print(L, S, D, KSZ)
pad = math.ceil(((L - 1) * S + D * (KSZ - 1) + 1 - L * 2)/2)
print("PAD", pad)
output_size = (L - 1) * S - 2 * pad + D * (KSZ - 1) + 1
print("OUTPUT SIZE", output_size)
return pad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment