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

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 main
    train(train_loader, model, optimizer, epoch, args.train.loss_weight, tb_logger, count)
  File "main.py", line 304, in train
    losses[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

你可能感兴趣的:(#,DL-报错,#,CV-基础,Python)