栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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()` 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/108287251,https://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博客

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1012243.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号