首页 > 解决方案 > 张量(1.0).item()与浮动(张量(1.0))

问题描述

如果是 dtype torch.float的xtorch.Tensor 那么操作是否完全相同?x.item()float(x)

标签: deep-learningpytorch

解决方案


操作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

推荐阅读