deep-learning - 张量(1.0).item()与浮动(张量(1.0))
问题描述
如果是 dtype torch.float的x
torch.Tensor 那么操作是否完全相同?x.item()
float(x)
解决方案
操作x.item()
和float(x)
不一样。
从 item() 的文档中,它可用于将张量的值作为 Python 数字获取(仅来自包含单个值的张量)。它基本上按原样返回张量的值。它不会对张量进行任何修改。
在可能float()
的情况下,将其输入转换为浮点数。在此处查找文档。
要查看差异,请考虑另一个 dtype int64 的 Tensor y:
import torch
y = torch.tensor(2)
print(y, y.dtype)
>>> tensor(2) torch.int64
print('y.item(): {}, float(y): {}'.format(y.item(), float(y)))
>>> y.item(): 2, float(y): 2.0
print(type(y.item()), type(float(y)))
>>> <class 'int'> <class 'float'>
请注意,float(y)
不会就地转换类型。如果需要更改,则需要分配它。像:
z = float(y)
print('y.dtype: {}, type(z): {}'.format(y.dtype, type(z)))
>>> y.dtype: torch.int64, type(z): <class 'float'>
我们可以看到那z
不是一个torch.Tensor
. 它只是一个浮点数。
该float()
操作不要与self.float()
. 此操作执行 Tensor dtype 转换(不是就地,需要赋值)。
print('y.float(): {},\n y.float().dtype: {},\n y: {},\n y.dtype'.format(y.float(), y.float().dtype, y, y.dtype))
y.float(): 2.0,
y.float().dtype: torch.float32,
y: 2,
y.dtype: torch.int64
推荐阅读
- javascript - 从未调用过 Javascript 函数 onload
- java - 生成的 Android 密钥对没有证书链来证明
- azure-sql-managed-instance - 将大型 SQL 托管实例还原到本地
- assembly - 错误 A2022 指令操作数必须相同大小
- css - 我可以将 CSS 变量分配给另一个变量吗?
- java - Spring Initializr 为 tomcat 创建 WAR?
- c# - 如何处理 Null 值的 ExcuteScalar 异常?
- sql-server - 如何为每组增加一个字母
- python - 求解非线性方程:为 Gibbs 自由能问题添加约束
- r - 使用“匹配”包进行倾向得分匹配,包括可视化和结果表