2

python v 3.7.3, pytorch v 0.4.1, 使用 jupyter

我正在使用以 ResNet50 作为基础模型的迁移学习创建图像分类器。我遇到了一个我不明白如何调试的错误,即使在网上搜索了解决方案之后也是如此。我不知道为什么我的尺寸这么偏。任何有关做什么的帮助将不胜感激。此外,任何关于使用 Pytorch 进行深度学习的书都很棒:)

ResNet 最后一层的代码:

fc_inputs = model.fc.in_features

model.fc = nn.Sequential(OrderedDict([
            ('fc1', nn.Linear(fc_inputs, 256)), 
            ('relu', nn.ReLU()),
            ('dropout', nn.Dropout(0.2)),
            ('fc2', nn.Linear(256, 25)),
            ('output', nn.LogSoftmax(dim=1))
]))

model.classifier = classifier

print(model)
print(model.classifier[0])
print(model.classifier[3])

optimizer = torch.optim.Adam(model.classifier.parameters(), lr = 0.001) 
criterion = nn.CrossEntropyLoss()
scheduler = lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)

训练代码:

epochs = 1
steps = 0
running_loss = 0
print_every = 10


for epoch in range(epochs):

    for images, labels in dataloaders['train']:

        images = images.view(images.shape[0], -1)  #this flattens it?
        steps += 1

        images, labels = images.to(device), labels.to(device)

        optimizer.zero_grad()

        logps = model(images)

        loss = criterion(logps, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()

        if step % print_every == 0:
            model.eval()
            test_loss = 0
            accuracy = 0

            for images, labels in dataloader:
                images, labels = images.to(device), labels.to(device)

                logps = model(images)
                loss = criterion(logps, labels)
                test_loss += loss.item()

                ps = torch.exp(logps)

                top_ps, top_class = ps.topk(1, dim=1)
                equality = top_class == labels.view(*top_class.shape)
                accuracy += torch.mean(equality.type(torch.FloatTensor)).item()

            train_losses.append(running_loss / len(dataloader['train']))
            test_losses.append(test_loss / len(dataloader['test']))

            print(f"Epoch {epoch + 1}/{epochs}.."
                  f"Train loss: {running_loss / print_every:.3f}.."
                  f"Test loss: {test_loss/len(dataloader['test']):.3f}.."
                  f"Test accuracy: {accuracy/len(dataloader['test']):.3f}")


            running_loss = 0
            model.train()            

错误:

RuntimeError                              Traceback (most recent call last)
<ipython-input-47-8f88694d7909> in <module>
     16         optimizer.zero_grad()
     17 
---> 18         logps = model(images)
     19 
     20         loss = criterion(logps, labels)

~\Anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
    475             result = self._slow_forward(*input, **kwargs)
    476         else:
--> 477             result = self.forward(*input, **kwargs)
    478         for hook in self._forward_hooks.values():
    479             hook_result = hook(self, input, result)

~\Anaconda3\lib\site-packages\torchvision\models\resnet.py in forward(self, x)
    137 
    138     def forward(self, x):
--> 139         x = self.conv1(x)
    140         x = self.bn1(x)
    141         x = self.relu(x)

~\Anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
    475             result = self._slow_forward(*input, **kwargs)
    476         else:
--> 477             result = self.forward(*input, **kwargs)
    478         for hook in self._forward_hooks.values():
    479             hook_result = hook(self, input, result)

~\Anaconda3\lib\site-packages\torch\nn\modules\conv.py in forward(self, input)
    299     def forward(self, input):
    300         return F.conv2d(input, self.weight, self.bias, self.stride,
--> 301                         self.padding, self.dilation, self.groups)
    302 
    303 

RuntimeError: Expected 4-dimensional input for 4-dimensional weight [64, 3, 7, 7], but got input of size [8, 196608] instead

编辑:我删除了images = images.view.shape[0], -1,它正在将我的张量转换为[8, 196608]. 但现在我收到一个新错误:

RuntimeError: size mismatch, m1: [8 x 8192], m2: [2048 x 256] at c:\programdata\miniconda3\conda-bld\pytorch_1532509700152\work\aten\src\th\generic/THTensorMath.cpp:2070

4

1 回答 1

0

是什么classifierclassifier为什么要在模型之后添加另一层( ) output

我的猜测是您不需要classifier,因为您已经从该fc层获得了 softmax 输出。尝试:

fc_inputs = model.fc.in_features

model.fc = nn.Sequential(OrderedDict([
            ('fc1', nn.Linear(fc_inputs, 256)), 
            ('relu', nn.ReLU()),
            ('dropout', nn.Dropout(0.2)),
            ('fc2', nn.Linear(256, 25)),
            ('output', nn.LogSoftmax(dim=1))
]))

optimizer = torch.optim.Adam(model.fc.parameters(), lr = 0.001) 
criterion = nn.CrossEntropyLoss()
scheduler = lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)
于 2019-12-21T07:36:03.140 回答