A torch version compatibility error is occurred when using Conv2d

Viewed 29

I want to use python 2.7 and torch, I am using torch 1.4.0. When I started implemneting a Conv2d example such as this example

c = nn.Conv2d(1, 1, (2, 1), stride=1)
x = torch.rand(1, 4).unsqueeze(-1)

I can execute these two line in python 2.7 and python 3, However when I call the c layer for a forward propagation it only works in python 3.

y = c(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/larc2/.local/lib/python2.7/site-packages/torch/nn/modules/module.py", line 547, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/larc2/.local/lib/python2.7/site-packages/torch/nn/modules/conv.py", line 343, in forward
    return self.conv2d_forward(input, self.weight)
  File "/home/larc2/.local/lib/python2.7/site-packages/torch/nn/modules/conv.py", line 340, in conv2d_forward
    self.padding, self.dilation, self.groups)
RuntimeError: Expected 4-dimensional input for 4-dimensional weight 1 1 2, but got 3-dimensional input of size [1, 4, 1] instead

Whereas, the python 3 result for this exact same code is as follows:

tensor([[[-0.9926],
         [-0.6937],
         [-0.6704]]], grad_fn=<SqueezeBackward1>)
2 Answers

As the error writes you need a 4-D input for a 2-D Conv: (N,C,H,W) You are giving a 3-D input.

Please use 4-D tensor as the Docs ask: https://pytorch.org/docs/1.4.0/nn.html#torch.nn.Conv2d

The reason it works in python 3 is probably that PyTorch adds support for using a 3-D tensor in 2-D Conv (C,H,W) in a newer version and maybe you installed a newer PyTorch version in the python 3 env

instead of:

x = torch.rand(1, 4).unsqueeze(-1)

This code worked for me:

x = torch.rand(1, 1, 4).unsqueeze(-1)
Related