为什么我输入的张量是错误的?

Why am I wrong in the input of the tensor?

这是我的 class 的 cnn。

classSimpleCnn(nn.Module):

def __init__(self, n_classes):
    super().__init__()
    self.layer1 = nn.Sequential(   # 224*224
        nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, padding=1),
        nn.ReLU(),
        nn.BatchNorm2d(64),
        nn.MaxPool2d(kernel_size=2, stride=2)
    )
    self.layer2 = nn.Sequential(   # 112*112
        nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, padding=1),
        nn.ReLU(),
        nn.BatchNorm2d(128),
        nn.MaxPool2d(kernel_size=2, stride=2)
    )
    self.layer3 = nn.Sequential(   # 56*56
        nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, padding=1),
        nn.ReLU(),
        nn.BatchNorm2d(256),
        nn.MaxPool2d(kernel_size=2, stride=2)
    )
    self.layer3 = nn.Sequential(   # 28*28
        nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        nn.ReLU(),
        nn.BatchNorm2d(512),
        nn.MaxPool2d(kernel_size=2, stride=2)
    )
    self.layer4 = nn.Sequential(   # 14*14
        nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, padding=1),
        nn.ReLU(),
        nn.BatchNorm2d(512),
        nn.MaxPool2d(kernel_size=2, stride=2)
    )
    self.out1 = nn.Linear(512*7*7, 4096)   # 7*7
    self.out2 = nn.Linear(4096, n_classes)
def forward(self, x):
    x = self.layer1(x)
    x = self.layer2(x)
    x = self.layer3(x)
    x = self.layer4(x)

    x = x.view(1, -1)
    x = self.out1(x)
    logits = self.out2(x)
    return logits  

而且 returns 这样的错误。

RuntimeError: 给定组数=1,权重大小 [512, 256, 3, 3],预期输入 [64, 128, 56, 56] 有 256 个通道,但得到的是 128 个通道。

我见过其他此类错误,但找不到我错在哪里。 谢谢你的回答。

在您的代码中,self.layer3 首先被定义,然后被覆盖(我认为是 copy-pasta 错误?)。抛出错误是因为在 layer3 的重新定义中,您假设输入有 256 个通道,但 self.layer2 的输出只有 128 个通道。