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

来源:weixin_39450145

物联沃分享整理
物联沃-IOTWORD物联网 » IndexError: invalid index of a 0-dim tensor. Use `tensor.item()` in Python or `tensor.item<T>()` in

发表评论