pytorch报错IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python
该错误消息表示您正在尝试索引其中只有一项的数组。例如,
In [10]: aten = torch.tensor(2)
In [11]: aten
Out[11]: tensor(2)
In [12]: aten[0]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-12-5c40f6ab046a> in <module>
----> 1 aten[0]
IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim
tensor to a Python number
在上述情况下,aten
是一个张量,其中只有一个数字。因此,使用索引(或更多索引)检索该数字将引发IndexError
。
从张量中提取数字的正确方法是使用tensor.item()
,aten.item()
如下所示:
In [14]: aten.item()
Out[14]: 2
本文来自博客园,作者:海_纳百川,转载请注明原文链接:https://www.cnblogs.com/chentiao/p/17668904.html,如有侵权联系删除