我正在尝试使用 Pytorch 的 torch.conv2d 函数,但无法得到我理解的结果......

这是一个简单的示例,其中内核 ( filt ) 与输入 ( im ) 的大小相同,以解释我在寻找什么。

import pytorch

filt = torch.rand(3, 3)
im = torch.rand(3, 3)

我想计算一个没有填充的简单卷积,所以结果应该是一个标量(即 1x1 张量)。

我用 conv2d 试过这个:
# I have to convert image and kernel to 4 dimensions tensors to use conv2d
im_torch = im.reshape((im_height, filt_height, 1, 1))
filt_torch = filt.reshape((filt_height, im_height, 1, 1))
out = torch.nn.functional.conv2d(im_torch, filt_torch, stride=1, padding=0)
print(out)

但结果并不是我所期望的:
tensor([[[[0.6067]], [[0.3564]], [[0.5397]]],
    [[[0.2557]], [[0.0493]], [[0.2562]]],
    [[[0.6067]], [[0.3564]], [[0.5397]]]])

为了了解我想要什么,我想重现 scipy convolve2d 行为:
import scipy.signal
out_scipy = scipy.signal.convolve2d(im.detach().numpy(), filt.detach().numpy(), 'valid')
print(out_scipy)

打印:
array([[1.195723]], dtype=float32)

最佳答案

输入和过滤器的张量形状应该是:
(batch, dim_ch, width, height)
并不是:
(width, height, 1, 1)
例如

import torch
import torch.nn.functional as F
x = torch.randn(1,1,4,4);
y = torch.randn(1,1,4,4);
z = F.conv2d(x,y);
z 的输出形状:
torch.Size([1,1,1,1])

关于python - pytorch 中的 conv2d 函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55994955/

10-11 01:46