gpt4 book ai didi

python - pytorch 中的 conv2d 函数

转载 作者:行者123 更新时间:2023-11-28 21:32:40 25 4
gpt4 key购买 nike

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

这是一个简单的示例,其中内核 (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)

最佳答案

输入和过滤器的张量形状应为:

(批处理,dim_ch,宽度,高度)

而不是:

(宽度, 高度, 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com