gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:21 26 4
gpt4 key购买 nike

我对孪生神经网络还很陌生,最近发现了 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

从张量中提取数字(项目)的正确方法是使用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-dim 张量转换为 Python 数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57993899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com