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

问题

----------one epoch begin----------
the compression rate now is 0.700000
pruning_cifar10_resnet.py:302: UserWarning: volatile was removed and now has no effect. Use `with torch.no_grad():` instead.
  input_var = torch.autograd.Variable(input, volatile=True)
pruning_cifar10_resnet.py:303: UserWarning: volatile was removed and now has no effect. Use `with torch.no_grad():` instead.
  target_var = torch.autograd.Variable(target, volatile=True)
Traceback (most recent call last):
  File "pruning_cifar10_resnet.py", line 460, in <module>
    main()
  File "pruning_cifar10_resnet.py", line 176, in main
    val_acc_1,   val_los_1   = validate(test_loader, net, criterion, log)
  File "pruning_cifar10_resnet.py", line 313, in validate
    top1.update(prec1[0], input.size(0))
IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number
root@633634ef4702:/home/xjr_directory/py/rethinking-network-pruning/cifar/soft-filter-pruning# 

原因

报错原因:版本升级,用法发生改变

解决方式

方式一:

top1.update(prec1[0], input.size(0))
# 更改为
top1.update(prec1.item(), input.size(0))

方式二:

top1.update(prec1[0], input.size(0))
# 更改为
top1.update(prec1.data , input.size(0))

常见的还有

total_loss += loss_val.data[0]
# 需要修改为以下

total_loss += loss_val.data
# 或者
total_loss += loss_val.item()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值