【问题标题】:How to use tensor.item() ? IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number如何使用 tensor.item() ? IndexError:0-dim 张量的无效索引。使用 tensor.item() 将 0-dim 张量转换为 Python 数字
【发布时间】:2020-01-19 11:28:13
【问题描述】:

我对 Siamese Neural Networks 很陌生,最近发现了 this exampleColab notebook

运行代码时出现以下错误:

IndexError: 0-dim 张量的无效索引。使用 tensor.item() 来 将 0-dim 张量转换为 Python 数字

上线:

result=torch.max(res,1)[1][0][0][0].data[0].tolist()

我发现了一些关于tensor.item() 的东西,但我真的不知道如何在这里使用它。

编辑:

test_dataloader = DataLoader(test_dataset,num_workers=6,batch_size=1,shuffle=True)
accuracy=0
counter=0
correct=0
for i, data in enumerate(test_dataloader,0): 
x0, x1 , label = data
# onehsot applies in the output of 128 dense vectors which is then  converted to 2 dense vectors
output1,output2 = model(x0.to(device),x1.to(device))
res=torch.abs(output1.cuda() - output2.cuda())
label=label[0].tolist()
label=int(label[0])
result=torch.max(res,1)[1][0][0][0].data.item().tolist()
if label == result:
correct=correct+1
counter=counter+1
#   if counter ==20:
#      break

accuracy=(correct/len(test_dataloader))*100
print("Accuracy:{}%".format(accuracy))

这就是我得到错误的代码。

【问题讨论】:

  • 请描述函数调用的上下文,在您的情况下可能是res 的维度和内容。即使(或者特别是因为)它是 Colab 笔记本,minimal reproducible example 的 Stackoverflow 策略仍然适用,因为这些外部资源最终可能会被停用,然后指向死角,使问题的上下文更难理解。

标签: python pytorch google-colaboratory tensor index-error


【解决方案1】:

这个错误信息的意思是你试图索引一个数组,其中只有一个项目。例如,

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

【讨论】:

  • 在某些时候 item() 可能是slow
  • 当我添加 .item() 时,我在同一行出现另一个错误:result=torch.max(res.item(),1)[1][0][0][0 ].data[0].tolist() ValueError: 只有一个元素张量可以转换为 Python 标量
猜你喜欢
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
相关资源
最近更新 更多