我正在尝试使用 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]]]])
为了了解我想要什么,我想重现 scipyconvolve2d行为:
import scipy.signal
out_scipy = scipy.signal.convolve2d(im.detach().numpy(), filt.detach().numpy(), 'valid')
print(out_scipy)
打印:
array([[1.195723]], dtype=float32)