解决IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Pyth

灰太狼 2022-12-31 12:21 234阅读 0赞

解决IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

报错代码

  1. running_loss += loss.data[0] * inputs.size(0)

报错信息

  1. IndexError Traceback (most recent call last)
  2. <ipython-input-8-7f128a52c8c7> in <module>
  3. 19 # Decay LR by a factor of 0.1 every 7 epochs
  4. 20 exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
  5. ---> 21 model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=1)
  6. 22
  7. 23 visualize_model(model_ft)
  8. <ipython-input-6-e165c8ed70ce> in train_model(model, criterion, optimizer, scheduler, num_epochs)
  9. 57
  10. 58 # statistics
  11. ---> 59 running_loss += loss.data[0] * inputs.size(0)
  12. 60 running_corrects += torch.sum(preds == labels.data)
  13. 61
  14. IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

解决办法

  1. running_loss += loss.item() * inputs.size(0)

欢迎大家交流学习,任何问题都可以留言

发表评论

表情:
评论列表 (有 0 条评论,234人围观)

还没有评论,来说两句吧...

相关阅读