PyTorch用torch.nn.functional.conv2d替换torch.nn.Conv2d

时间:2018-04-18 10:09:40

标签: pytorch

所以我对PyTorch有this MNIST example。 我想用功能方法替换conv2d。但出现意外错误。

我将self.conv1 = nn.Conv2d(1, 32, 5, padding=2)替换为self.w_conv1 = Variable(torch.randn(1, 32, 5))

在转发方法中,我将x = F.max_pool2d(F.relu(self.conv1(x)), 2)替换为x = F.max_pool2d(F.relu(F.conv2d(x, self.w_conv1, padding=2),2))

然后它会给我一个错误:

Expected 4-dimensional input for 4-dimensional weight [1, 32, 5], but got input of size [50, 1, 28, 28] instead

之前的代码工作过,我认为我用它的功能等同替换了这个类。

1 个答案:

答案 0 :(得分:0)

albanD回答了https://discuss.pytorch.org/t/pytorch-replace-torch-nn-conv2d-with-torch-nn-functional-conv2d/16596

中的问题
  

您好,

     

错误信息不是很清楚我害怕因为它来自   深入C后端。这里的问题是,当你做一个   具有大小(批量,in_chan,宽度,高度)的2D图像上的卷积,   你想要一个大小的输出(批量,out_chan,宽度',高度'),   卷积的权重应该是(out_chan,in_chan,   width_kern_size,height_kern_size),基本上当你使用内核时   Conv2d函数的大小为5,与内核相同   宽度为5,高度为5.因此你应该有self.w_conv1 =   变量(torch.randn(32,1,5,5))。有关详细信息,请参阅doc