IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

参考:http://www.seotest.cn/jishu/57263.html

问题背景:两个不一样的神经网络,读取数据和训练模型等代码一样,只是两个模型不一样。经过分析问题一定出在模型上

原代码

   def forward(self, input):
        x = self.feature(input)
        x = x.squeeze()
        fc = torch.nn.Linear(512, 2).cuda()
        x = fc(x)
        x = F.softmax(x, dim=1)
        return x

报错

D:\APP\Anaconda3\envs\pytorch\python.exe "D:/Workspace/Pycharm/Dog vs. Cat/main.py"
train:   0%|          | 0/20000 [00:00<?, ?it/s]Epoch 1/20
----------
Training...

Traceback (most recent call last):
  File "D:/Workspace/Pycharm/Dog vs. Cat/main.py", line 65, in <module>
    main(epoch_n)
  File "D:/Workspace/Pycharm/Dog vs. Cat/main.py", line 22, in main
    model_trained = train.train_model(model, epoch_n, criterion, optimizer)
  File "D:\Workspace\Pycharm\Dog vs. Cat\train.py", line 60, in train_model
    y_pred = model(batch)
  File "D:\APP\Anaconda3\envs\pytorch\lib\site-packages\torch\nn\modules\module.py", line 493, in __call__
    result = self.forward(*input, **kwargs)
  File "D:\Workspace\Pycharm\Dog vs. Cat\model_GAP2.py", line 67, in forward
    x = F.softmax(x, dim=1)
  File "D:\APP\Anaconda3\envs\pytorch\lib\site-packages\torch\nn\functional.py", line 1263, in softmax
    ret = input.softmax(dim)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)

Process finished with exit code 1

错误分析:维度错误,想要得到二维的,但是得到的是一维的,对于维度的操作代码可能出现错误; x = x.squeeze()可能错误,换一个方式

改正后代码

    def forward(self, input):
        x = self.feature(input)
        # x = x.squeeze()
        x = x.view(-1, 512)
        fc = torch.nn.Linear(512, 2).cuda()
        x = fc(x)
        x = F.softmax(x, dim=1)
        return x

经过改正,错误完美解决

你可能感兴趣的:(报错汇总)