PyTorch多分支CNN如何调整输入维度适配前向传播解决报错

实现需求
我有形状为(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
模型前向函数的输入input_list形状为torch.Size([100, 20, 20, 20]),其中100为批量大小。在执行特征拼接的代码行时,出现如下报错:RuntimeError: Expected 4-dimensional input for 4-dimensional weight [10, 1, 3, 3], but got 3-dimensional input of size [20, 20, 20] instead
我目前有两个待解决的问题:
- 为什么Conv2d要求输入为4维,对应权重形状为[10,1,3,3]?我参考了相关报错说明,但不清楚这些维度的具体含义
- 我的输入是包含100个样本的批量数据,如何处理形状为(20,20,20)的单个样本,将其拆分为20个独立输入分别传给20个CNN分支?
内容的提问来源于stack exchange,提问作者Burger
相关产品推荐
相关产品推荐

