Learn Before
Code

Bilinear Kernel for Transposed Convolution

The upsampling operation of bilinear interpolation can be implemented using a transposed convolutional layer by initializing its weights with a specially constructed bilinear kernel. A programmatic implementation of this kernel calculates weights based on relative distances from the center. For example, the bilinear_kernel function constructs a kernel tensor where the values decrease linearly from the center, effectively mimicking the distance-weighted averaging of bilinear interpolation.

def bilinear_kernel(in_channels, out_channels, kernel_size): factor = (kernel_size + 1) // 2 if kernel_size % 2 == 1: center = factor - 1 else: center = factor - 0.5 og = (torch.arange(kernel_size).reshape(-1, 1), torch.arange(kernel_size).reshape(1, -1)) filt = (1 - torch.abs(og[0] - center) / factor) * \ (1 - torch.abs(og[1] - center) / factor) weight = torch.zeros((in_channels, out_channels, kernel_size, kernel_size)) weight[range(in_channels), range(out_channels), :, :] = filt return weight

0

1

Updated 2026-05-21

Contributors are:

Who are from:

Tags

D2L

Dive into Deep Learning @ D2L