我有一本带有张量键和张量值的字典。我想通过键访问值。
from torch import tensor
x = {tensor(0): [tensor(1)], tensor(1): [tensor(0)]}
for i in x.keys():
print(i, x[i])
返回:
tensor(0) [tensor(1)]
tensor(1) [tensor(0)]
但是当我尝试在不循环键的情况下访问值时,
try:
print(x[tensor(0)])
except:
print(Exception)
print(x[0])
抛出异常:
KeyError Traceback (most recent call last)
<ipython-input-34-746d28dcd450> in <module>()
6 try:
----> 7 print(x[tensor(0)])
8
KeyError: tensor(0)
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-34-746d28dcd450> in <module>()
9 except:
10 print(Exception)
---> 11 print(x[0])
12 continue
KeyError: 0
最佳答案
在 PyTorch 中,张量的哈希值是其 id
的函数,而不是实际值。因为 Python 字典使用哈希值进行查找,所以查找失败。见 this Github discussion .
In [4]: hash(tensor(0)) == hash(tensor(0))
Out[4]: False
In [5]: hash(tensor(0))
Out[5]: 4364730928
In [6]: hash(tensor(0))
Out[6]: 4362187312
In [7]: hash(tensor(0))
Out[7]: 4364733808
为了实现你想要的,你可以使用纯 Python 整数作为键,或者使用 Embedding
对象作为 x
。
关于python - Pytorch:如何通过python字典中的张量(键)访问张量(值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60870008/