torch.Tensor.new_tensor¶
- Tensor.new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) 张量¶
返回一个新的 Tensor,其
data作为张量数据。 默认情况下,返回的 Tensor 具有与此张量相同的torch.dtype和torch.device。警告
new_tensor()总是复制data。如果你有一个 Tensordata并且想要避免复制,使用torch.Tensor.requires_grad_()或者torch.Tensor.detach()。 如果你有一个 numpy 数组并且想要避免复制,使用torch.from_numpy()。警告
当数据是一个张量 x 时,
new_tensor()从传递的任何内容中读取“数据”,并构造一个叶子变量。因此tensor.new_tensor(x)等价于x.clone().detach()并且tensor.new_tensor(x, requires_grad=True)等价于x.clone().detach().requires_grad_(True)。 推荐使用clone()和detach()的等价方法。- Parameters
数据 (类似数组) – 返回的张量复制了
数据。- Keyword Arguments
dtype (
torch.dtype, 可选) – 返回张量的所需类型。 默认值:如果为 None,则与该张量的torch.dtype相同。设备 (
torch.device, 可选) – 返回张量所需的设备。 默认值:如果为 None,则与该张量相同的torch.device。requires_grad (布尔值, 可选) – 如果 autograd 应该记录对返回张量的操作。默认值:
False。布局 (
torch.layout, 可选) – 返回张量的所需布局。 默认值:torch.strided。pin_memory (bool, 可选) – 如果设置,返回的张量将分配在固定内存中。仅适用于CPU张量。默认值:
False。
示例:
>>> tensor = torch.ones((2,), dtype=torch.int8) >>> data = [[0, 1], [2, 3]] >>> tensor.new_tensor(data) tensor([[ 0, 1], [ 2, 3]], dtype=torch.int8)