out_channels=2 的 Conv2d 产生 1 个通道的输出

Conv2d with out_channels=2 producing output with 1 channel

据我了解,out_channels 应该决定输出中的通道数(我是 pytorch 的新手)。 我是运行这个代码:

import torch
from torch import nn

img = torch.tensor([[[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]],[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]]])
torchDetector = nn.Conv2d(in_channels=2,out_channels=2, kernel_size=(2, 2),bias=False, stride=1, padding=0)
filter = torch.tensor([[[[1,1],[1,1]],[[-1,-1],[-1,-1]]]])
torchDetector.weight = nn.Parameter(filter, requires_grad=False)
torchDetected = torchDetector(img)

print(torchDetected)

并期待 2 个通道的结果,但得到 1 个通道:

tensor([[[[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]]])

我期待这个结果:

tensor([[[[ 8.,  8.,  8.],
          [ 8.,  8.,  8.],
          [ 8.,  8.,  8.]],

         [[-8., -8., -8.],
          [-8., -8., -8.],
          [-8., -8., -8.]]]])

我错过了什么?

您需要将频道添加到过滤器

import torch
import math
from torch import nn

img = torch.tensor([[[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]],[[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]]])
print(img.shape)
print(img)
print()
torchDetector = nn.Conv2d(2,2, kernel_size=(2, 2),bias=False, stride=1, padding=0)
filter = torch.tensor([
                       [[[1, 1,],[1, 1]],
                        [[1, 1,],[1, 1]]],
                       [[[-1, -1,],[-1, -1]],
                        [[-1, -1,],[-1, -1]]]
                       ])
torchDetector.weight = nn.Parameter(filter, requires_grad=False)
torchDetected = torchDetector(img)

print(torchDetected.shape)
print(torchDetected)

输出:

torch.Size([1, 2, 4, 4])
tensor([[[[1, 1, 1, 1],
          [1, 1, 1, 1],
          [1, 1, 1, 1],
          [1, 1, 1, 1]],

         [[1, 1, 1, 1],
          [1, 1, 1, 1],
          [1, 1, 1, 1],
          [1, 1, 1, 1]]]])

torch.Size([1, 2, 3, 3])
tensor([[[[ 8,  8,  8],
          [ 8,  8,  8],
          [ 8,  8,  8]],

         [[-8, -8, -8],
          [-8, -8, -8],
          [-8, -8, -8]]]])