pytorch 修改输入数据转发以使其适合我的模型

pytorch modifying the input data to forward to make it suitable to my model

这是我想做的。 我有一个形状为 (20,20,20) 的单独数据,其中 20 个形状为 (1,20,20) 的张量将用作 20 个独立 CNN 的输入。这是我目前的代码。

class MyModel(torch.nn.Module):
   def __init__(self, ...):
       ...
        self.features = nn.ModuleList([nn.Sequential(
            nn.Conv2d(1,10, kernel_size = 3, padding = 1),
            nn.ReLU(),
            nn.Conv2d(10, 14, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.Conv2d(14, 18, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.Flatten(),
            nn.Linear(28*28*18, 256)
        ) for _ in range(20)])
        self.fc_module = nn.Sequential(
            nn.Linear(256*n_selected, cnn_output_dim),
            nn.Softmax(dim=n_classes)
        )
   
    def forward(self, input_list):
        concat_fusion = cat([cnn(x) for x,cnn in zip(input_list,self.features)], dim = 0)
        output = self.fc_module(concat_fusion)
        return output

forward 函数中 input_list 的形状是 torch.Size([100, 20, 20, 20]),其中 100 是批量大小。 但是,

有一个问题
concat_fusion = cat([cnn(x) for x,cnn in zip(input_list,self.features)], dim = 0)

因为它会导致此错误。

RuntimeError:4 维权重 [10、1、3、3] 的预期 4 维输入,但得到的是大小 [20、20、20] 的 3 维输入

  1. 首先,我想知道为什么它希望我给出 4 维权重 [10,1,3,3]。我见过 但我不确定这些具体数字是从哪里来的。

  2. 我有一个 input_list 是一批 100 个数据。我不确定如何处理形状为 (20,20,20) 的单个数据,以便我实际上可以将其分成 20 块,以将其用作 20 个 CNN 的独立输入。

为什么它希望我给出 4 维权重 [10,1,3,3]。

请注意以下日志表示具有内核 (10, 1, 3, 3) 的 nn.Conv2d 需要 4 维输入。

RuntimeError: Expected 4-dimensional input for 4-dimensional weight [10, 1, 3, 3]

如何将输入沿通道分成 20 块。

迭代 input_list(100, 20, 20, 20) 产生 100 个形状为 (20, 20, 20) 的张量。

如果您想沿通道分割输入,请尝试沿第二个维度分割 input_list。

concat_fusion = torch.cat([cnn(input_list[:, i:i+1]) for i, cnn in enumerate(self.features)], dim = 1)