首页 > 解决方案 > pytorch 中 MNIST 数据集的 DNN 大小不匹配

问题描述

我必须找到一种方法来创建神经网络模型并在 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)

标签: neural-networkpytorchmnist

解决方案


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

xb = xb.view(-1, 784)

推荐阅读