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

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

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.

"""

        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].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博客

Original: https://blog.csdn.net/weixin_39450145/article/details/125752513
Author: weixin_39450145
Title: IndexError: invalid index of a 0-dim tensor. Use tensor.item() in Python or tensor.item<T>() in

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/670424/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球