sar*_*nns 2 python python-3.x pytorch
我有一个带有张量键和张量值的字典。我想通过键访问值。
from torch import tensor
x = {tensor(0): [tensor(1)], tensor(1): [tensor(0)]}
for i in x.keys():
print(i, x[i])
Run Code Online (Sandbox Code Playgroud)
返回:
tensor(0) [tensor(1)]
tensor(1) [tensor(0)]
Run Code Online (Sandbox Code Playgroud)
但是当我尝试访问值而不遍历键时,
try:
print(x[tensor(0)])
except:
print(Exception)
print(x[0])
Run Code Online (Sandbox Code Playgroud)
抛出异常:
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
Run Code Online (Sandbox Code Playgroud)
在 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
Run Code Online (Sandbox Code Playgroud)
为了实现你想要的,你可以使用普通的 Python 整数作为键,或者使用一个Embedding
对象作为x
.
归档时间: |
|
查看次数: |
2922 次 |
最近记录: |