如何在PyTorch conv2d函数中使用groups参数

mar*_*man 6 convolution pytorch

我试图在PyTorch中计算每个通道的渐变图像.为此,我想在图像的每个通道上使用Sobel滤波器执行标准2D卷积.我正在使用这个torch.nn.functional.conv2d功能

在我下面的最小工作示例代码中,我收到一个错误:

import torch
import torch.nn.functional as F

filters = torch.autograd.Variable(torch.randn(1,1,3,3))
inputs = torch.autograd.Variable(torch.randn(1,3,10,10))
out = F.conv2d(inputs, filters, padding=1)
Run Code Online (Sandbox Code Playgroud)

RuntimeError:给定组= 1,权重[1,1,3,3],所以预期输入[1,3,10,10]有1个通道,但得到3个通道

这表明groups需要为3.但是,当我制作时groups=3,我得到一个不同的错误:

import torch
import torch.nn.functional as F

filters = torch.autograd.Variable(torch.randn(1,1,3,3))
inputs = torch.autograd.Variable(torch.randn(1,3,10,10))
out = F.conv2d(inputs, filters, padding=1, groups=3)
Run Code Online (Sandbox Code Playgroud)

RuntimeError:无效参数4:超出范围/usr/local/src/pytorch/torch/lib/TH/generic/THTensor.c:440

当我检查THTensor类中的代码片段时,它引用了一堆维度检查,但我不知道我哪里出错了.

这个错误是什么意思?如何使用此conv2d功能执行我想要的卷积?我相信我误解了groups参数.

ent*_*phy 7

如果您想应用每个频道的卷积,那么您out-channel应该与您的相同in-channel.这是预期的,考虑到每个输入通道都会创建一个与之对应的单独输出通道.

简而言之,这将有效

import torch
import torch.nn.functional as F

filters = torch.autograd.Variable(torch.randn(3,1,3,3))
inputs = torch.autograd.Variable(torch.randn(1,3,10,10))
out = F.conv2d(inputs, filters, padding=1, groups=3)
Run Code Online (Sandbox Code Playgroud)

然而,过滤器的大小(2, 1, 3, 3)(1, 1, 3, 3)不起作用.

此外,您还可以使您out-channel的倍数in-channel.这适用于您希望为每个输入通道设置多个卷积滤镜的情况.

但是,这只有在倍数时才有意义.如果没有,那么pytorch会回落到最接近的倍数,这个数字比你指定的数字少.这再次是预期的行为.例如,尺寸为(4, 1, 3, 3)或者的过滤器(5, 1, 3, 3)将产生out-channel尺寸为3 的过滤器.