首页 > 解决方案 > Pytorch:如何通过python字典中的张量(键)访问张量(值)

问题描述

我有一本带有张量键和张量值的字典。我想通过键访问值。

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

标签: pythonpython-3.xpytorch

解决方案


在 PyTorch 中,张量的哈希值是它们的函数id,而不是实际值。因为 Python 字典使用哈希值进行查找,所以查找失败。请参阅此 Github 讨论

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.


推荐阅读