2D input with 1D convolution


I was wondering how to handle 2D input data while doing a 1D convolution in PyTorch. This nice answer handles three situations: https://stats.stackexchange.com/questions/292751/is-a-1d-convolution-of-size-m-with-k-channels-the-same-as-a-2d-convolution-o/292791

I am interested in the second example: I have multiple 1D vectors of the same length that I can combine into a 2D matrix as input, and I want a 1D array as output. I would like to do a 1D convolution with 1 channel, a kernelsize of nĂ—1 and a 2D input, but it seems that this is not possible in PyTorch as the input shape of Conv1D is minibatchĂ—in_channelsĂ—iW (implying a height of 1 instead of n).

My question is, how can I do a 1D convolution with a 2D input (aka multiple 1D arrays stacked into a matrix)?

Thanks in advance.

The second example is using basically a 2D convolution where the kernel height is equal to the input height.
This code should yield the desired results:

batch_size = 1
channels = 1
height = 3
length = 10
kernel_size = (height, 5)

x = torch.randn(batch_size, channels, height, length)

conv = nn.Conv2d(
    padding=(0, 2)

output = conv(x)
> torch.Size([1, 1, 1, 10])
1 Like