python - 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
解决方案
在 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
.
推荐阅读
- python - 如何使用 python-binance 获取历史买入价和卖出价
- javascript - 如何在 Sequelize 中更新外键(belongsTo)
- python - if 语句继续追加数据
- c++ - 如何将浮点值从数组转换为相应的计时时间以进行比较
- android - 如何在 Android 7.1 的设置中的设备管理员菜单中列出我的应用程序
- reactjs - 我应该如何组织 React 项目以避免 react-hooks/exhaustive-deps
- angular - 角 HttpErrorResponse
- google-cloud-storage - 与用户合作时如何计划谷歌云存储桶的创建
- r-markdown - 使用 officedown::rdocx_document 时,Rmd 报告不会从模板导入边距、页眉或页脚:
- r - 如何在 R Studio 中将字符转换为整数?