python - 如何使用tensor.item()? IndexError : invalid index of a 0-dim tensor. 使用tensor.item()将0维张量转换为Python数字

标签 python pytorch google-colaboratory tensor index-error

我对暹罗神经网络很陌生,最近发现 this exampleColab notebook .

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

IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

上线:

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))

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

最佳答案

此错误消息表示您正在尝试对一个只有一项的数组进行索引。例如,

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

从张量中提取数字(item)的正确方法是使用tensor.item(),这里aten.item()如下:

In [14]: aten.item()
Out[14]: 2

关于python - 如何使用tensor.item()? IndexError : invalid index of a 0-dim tensor. 使用tensor.item()将0维张量转换为Python数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57993899/

相关文章:

python - 具有不同维度索引数组的索引pytorch张量

python - 模块 'keras.api._v2.keras.experimental' 没有属性 'PeepholeLSTMCell'

python - Google Colab - 选择特定的 Python 版本

python - 如何在 Google Colab 上安装 nvidia apex

python - pip install MySql-python==1.2.4 在 Ubuntu 12.04 上失败

python - 替代 python 替换

pytorch - 为什么即使我将可见 CUDA 设置为 2,DDP 中的 `local_rank` 仍为零?

python - 如何有效地计算 Pytorch 中的张量?

在 Swift 中编码时出现 Python 错误 : unexpected indent (Xcode 11)

python - simplely __ double underscore as a variable name 是什么意思? Just __ not follow another chars