【问题标题】:Runtime error, shape is invalid for input运行时错误,输入的形状无效
【发布时间】:2020-05-14 19:16:24
【问题描述】:

我正在尝试获取网络的输入和输出信息。调试时,出现此错误,Runtime, shape ‘[-1, 400]’ is invalid for input of size 384. 我尝试了不同的值,但找不到正确的值。有没有办法解决这个问题?谢谢。

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16*5*5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16*5*5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x
input_shape = (3, 21,21)
        dummy_input = torch.randn(6,*input_shape)
        graph = torch.jit._get_trace_graph(model,  args=dummy_input, _force_outplace=False, _return_inputs_states=False)

错误信息:

RuntimeError: shape '[-1, 400]' is invalid for input of size 384

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    卷积层后张量的形状为[6,16,2,2]。因此,在将它们馈送到线性层之前,您不能将其重塑为 16*5*5。如果您想在卷积层中使用与原始过滤器大小相同的过滤器,则应将您的网络更改为下面给出的网络。

    class Net(nn.Module):
        def __init__(self):
            super(Net, self).__init__()
            self.conv1 = nn.Conv2d(3, 6, 5)
            self.pool = nn.MaxPool2d(2, 2)
            self.conv2 = nn.Conv2d(6, 16, 5)
            self.fc1 = nn.Linear(16*2*2, 120) # changed the size
            self.fc2 = nn.Linear(120, 84)
            self.fc3 = nn.Linear(84, 10)
    
        def forward(self, x):
            x = self.pool(F.relu(self.conv1(x)))
            x = self.pool(F.relu(self.conv2(x)))
            x = x.view(-1, 16*2*2) # changed the size
            x = F.relu(self.fc1(x))
            x = F.relu(self.fc2(x))
            x = self.fc3(x)
            return x
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2021-04-08
    • 2018-08-10
    • 2018-07-31
    • 2020-12-16
    相关资源
    最近更新 更多