IndexError: invalid index of a 0-dim tensor. Use `tensor.item()` in Python or `tensor.item<T>()` in

1.问题:IndexError: invalid index of a 0-dim tensor. Use `tensor.item()` in Python or `tensor.item<T>()` in C++ to convert a 0-dim tensor to a number

2.解决:

主要是因为torch版本不同,用法发生了改变。

参考他人博客的解决方法,把prec1[0]改为prec1.item()、或者 把prec1[0]改为prec1.data,第二种方式把[0]改为.data成功解决了我的问题。

对于我的问题:

把 cutoff_value = abs_tensor.view(-1).cpu().kthvalue(cutoff_rank)[0][0] 

更改为:

cutoff_value = abs_tensor.view(-1).cpu().kthvalue(cutoff_rank)[0].data ,即可成功解决。

 def pruning_mask(self, weights, previous_mask, layer_idx):
        """Ranks weights by magnitude. Sets all below kth to 0.
           Returns pruned mask.
        """
        # Select all prunable weights, ie. belonging to current dataset.
        previous_mask = previous_mask.cuda()
        tensor = weights[previous_mask.eq(self.current_dataset_idx)]
        abs_tensor = tensor.abs()
        cutoff_rank = round(self.prune_perc * tensor.numel())

        #cutoff_value = abs_tensor.view(-1).cpu().kthvalue(cutoff_rank)[0][0]  这行代码报错
        ##### 把上面这行代码,改为下面这行代码即可:
        cutoff_value = abs_tensor.view(-1).cpu().kthvalue(cutoff_rank)[0].data

3.参考:

1)https://blog.csdn.net/qq_42255269/article/details/108287251https://blog.csdn.net/qq_35523233/article/details/88046064,网上的解决方法大都是把loss.data[0]修改为loss.item(),照着这个形式修改代码,并不能解决我的问题。

2)从下面这个博客得到答案,把prec1[0]改为prec1.item()、或者 把prec1[0]改为prec1.data,第二种方式把[0]改为.data解决了我的问题。

IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python_JY丫丫的博客-CSDN博客

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_39450145

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值