【问题标题】:How to use groups parameter in PyTorch conv2d function如何在 PyTorch conv2d 函数中使用组参数
【发布时间】:2018-03-14 04:49:20
【问题描述】:

我正在尝试在 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)

RuntimeError: Given groups=1, weight[1, 1, 3, 3], 所以预期 input[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)

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

当我检查THTensor类中的那个代码sn-p时,它指的是一堆维度检查,但我不知道我哪里出错了。

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

【问题讨论】:

    标签: convolution pytorch


    【解决方案1】:

    如果您想应用每通道卷积,那么您的 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)
    

    而大小为(2, 1, 3, 3)(1, 1, 3, 3) 的过滤器将不起作用。

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

    但是,这只有在它是倍数时才有意义。如果不是,那么 pytorch 会回退到最接近的倍数,这个数字小于您指定的数字。这再次是预期的行为。例如,大小为 (4, 1, 3, 3)(5, 1, 3, 3) 的过滤器将产生大小为 3 的 out-channel

    【讨论】:

      猜你喜欢
      • 2021-07-05
      • 2019-09-23
      • 1970-01-01
      • 2018-06-22
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 2021-06-18
      相关资源
      最近更新 更多