当前位置: 代码迷 >> 综合 >> pytorch IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to
  详细解决方案

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

热度:18   发布时间:2023-12-15 16:51:41.0

pytorch 1.1.0
报错:

$ sh experiments/webface/res50-bs64-sz224-ep35/train.sh
Creating model on [4] gpus: 0,1,2,3
Origin Size: 493456     Aligned Size: 493568
/home/user1/miniconda3/lib/python3.7/site-packages/torch/nn/parallel/_functions.py:61: UserWarning: Was asked to gather along dimension 0, but all input tensors were scalars; will instead unsqueeze and return a vector.warnings.warn('Was asked to gather along dimension 0, but all '
Traceback (most recent call last):File "main.py", line 458, in <module>main()File "main.py", line 242, in maintrain(train_loader, model, optimizer, epoch, args.train.loss_weight, tb_logger, count)File "main.py", line 304, in trainlosses[k].update(loss[k].mean().data[0])
IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

解决:把代码中所有涉及到loss、包含 “.data[0]” 的改成 “.item()”。如:

# 304 losses[k].update(loss[k].mean().data[0])
losses[k].update(loss[k].mean().item()) 
...
# 370 losses[k].update(loss[k].data[0]) 
losses[k].update(loss[k].item())

感谢:https://blog.csdn.net/LYKXHTP/article/details/81565453

  相关解决方案