pytorch 中 MNIST 数据集的 DNN 大小不匹配

Size mismatch for DNN for the MNIST dataset in pytorch

我必须找到一种方法来创建神经网络模型并在 MNIST 数据集上对其进行训练。我需要有 5 层,每层有 100 个神经元。但是,当我尝试设置它时,出现大小不匹配的错误。你能帮忙吗?我希望我可以在下面的模型上训练:

class Mnist_DNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.layer1 = nn.Linear(784, 100)
        self.layer2 = nn.Linear(100, 100)
        self.layer3 = nn.Linear(100, 100)
        self.layer4 = nn.Linear(100, 100)
        self.layer5 = nn.Linear(100, 10)

    def forward(self, xb):
        xb = xb.view(-1, 1, 28, 28)
        xb = F.relu(self.layer1(xb))
        xb = F.relu(self.layer2(xb))
        xb = F.relu(self.layer3(xb))
        xb = F.relu(self.layer4(xb))
        xb = F.relu(self.layer5(xb))
        return self.layer5(xb)

您设置图层以获取一批 784 (=28*28) 暗淡的一维向量。但是,在您的 forward 函数中,您 view 输入为一批大小为 28*28 的二维矩阵。
尝试将输入视为一批 1D 信号:

xb = xb.view(-1, 784)