欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-17 11:24:52
...

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

报错代码

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

报错信息

IndexError                                Traceback (most recent call last)
<ipython-input-8-7f128a52c8c7> in <module>
     19 # Decay LR by a factor of 0.1 every 7 epochs
     20 exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
---> 21 model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=1)
     22 
     23 visualize_model(model_ft)

<ipython-input-6-e165c8ed70ce> in train_model(model, criterion, optimizer, scheduler, num_epochs)
     57 
     58                 # statistics
---> 59                 running_loss += loss.data[0] * inputs.size(0)
     60                 running_corrects += torch.sum(preds == labels.data)
     61 

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

解决办法

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

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