【发布时间】:2021-11-13 19:48:07
【问题描述】:
在此页面上学习 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 页面上的内容完全匹配
- 我的错误发生在第二线性层,而不是第一个,并且前一层的列与当前层的行匹配,所以我觉得为什么会发生这个错误令人困惑。李>
【问题讨论】:
标签: python conv-neural-network pytorch