PyTorch线性图层中的尺寸不匹配

时间:2019-06-28 16:40:20

标签: python conv-neural-network pytorch

在此页面上的PyTorch培训课程之后:https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py

基本上是他们的“ Hello World!”图片分类器的版本。

我想做的是手动编码网络中的训练步骤,以确保我理解每个步骤,但是我目前在我的线性层之一中遇到了尺寸不匹配的问题,这让我很困惑。特别是由于(AFAIK),我正在完全重新创建本教程中的步骤。

无论如何.....

我的网络:

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.fc2   = 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

net = net()

相信,这与他们在自己的页面上看到的完全一样。

我正在尝试计算以下没有循环的步骤:

for epoch in range(2):  # loop over the dataset multiple times

  running_loss = 0.0
  for i, data in enumerate(trainloader, 0):
    # get the inputs; data is a list of [inputs, labels]
    inputs, labels = data

    # zero the parameter gradients
    optimizer.zero_grad()

    # forward + backward + optimize
    outputs = net(inputs)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()

    # print statistics
    running_loss += loss.item()
    if i % 2000 == 1999:    # print every 2000 mini-batches
        print('[%d, %5d] loss: %.3f' %
              (epoch + 1, i + 1, running_loss / 2000))
        running_loss = 0.0

  print('Finished Training')

我正在做什么:

data = enumerate(trainloader)
inputs, labels = next(data)[1]
outputs = net(inputs)

最后一行给出了以下回溯:

RuntimeError                              Traceback (most recent call last)
<ipython-input-285-d4be5abf5bb1> in <module>
----> 1 outputs = net(inputs)

~\Anaconda\lib\site-packages\torch\nn\modules\module.py in __call__(self, 
*input, **kwargs)
    487             result = self._slow_forward(*input, **kwargs)
    488         else:
--> 489             result = self.forward(*input, **kwargs)
    490         for hook in self._forward_hooks.values():
    491             hook_result = hook(self, input, result)

<ipython-input-282-a6eca2e3e9db> in forward(self, x)
    14         x = x.view(-1, 16 * 5 * 5)
    15         x = F.relu(self.fc1(x))
---> 16         x = F.relu(self.fc2(x))
    17         x = self.fc3(x)

以以下方式结束:

RuntimeError: size mismatch, m1: [4 x 120], m2: [84 x 10] at 
c:\a\w\1\s\tmp_conda_3.7_110206\conda\conda- 
bld\pytorch_1550401474361\work\aten\src\th\generic/THTensorMath.cpp:940

我知道这意味着我的尺寸值不匹配,并且我怀疑这与我从卷积层到线性层的线x = x.view(-1, 16 * 5 * 5)有关,但是我有两个困惑:

  • 据我所知,我的网络与PyTorch页面上的内容完全匹配
  • 我的错误发生在第二个线性层上,而不是第一个线性层上,并且先前层的列与当前层的行匹配,因此我感到困惑,为什么会发生此错误。

2 个答案:

答案 0 :(得分:2)

实际上,您在self.fc3(x)函数中提到的__init__()中没有forward()。尝试通过更改

来运行代码 self.fc2 = nn.Linear(84, 10)中的

__init__()功能 self.fc3 = nn.Linear(84, 10)

以上错误是您得到错误的原因。在上述代码中两次初始化self.fc2时,请参见以下几行:

self.fc2   = nn.Linear(120, 84)
self.fc2   = nn.Linear(84, 10)

此处,self.fc2的第一个值被更高的值覆盖。因此,最后使用带有输入通道84和输出通道10的线性层对其进行初始化。 稍后,在正向功能中,您将x = F.relu(self.fc1(x))的输出通道(即120)作为输入通道传递到x = F.relu(self.fc2(x)),由于上述原因,该通道已更改为84,错误。

除此之外,我认为您的代码是否有问题。

答案 1 :(得分:1)

我不知道您使用的图像的大小是多少,但似乎正在影响最后一个特征图的大小,因此,这会影响您发送到线性模型的数据量。

尝试通过以下方法检查尺寸:在您的service.Credentials = new WebCredentials("username\\DOMAINNAME","password"); service.Credentials = new WebCredentials("username","password", "DOMAINNAME"); service.Credentials = new WebCredentials("username@mydomain.com","password"); 方法中:

forward

您将遇到类似def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) print (x.shape) 的内容 然后,您可以使用torch.Size([32, 16, 4, 4])

或者,您可以直接从x = x.view(-1, 16 * 4 * 4)获取这些值。

希望对您有帮助。