快捷键

torch.Tensor.new_tensor

Tensor.new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) Tensor

返回一个新的 Tensor,其数据为 data 。默认情况下,返回的 Tensor 具有与该 Tensor 相同的 torch.dtypetorch.device

警告

new_tensor() 总是复制 data 。如果你有一个 Tensor data 并且想避免复制,请使用 torch.Tensor.requires_grad_()torch.Tensor.detach() 。如果你有一个 numpy 数组并且想避免复制,请使用 torch.from_numpy()

警告

当数据是张量 x 时, new_tensor() 从传递给它的任何地方读取‘数据’,并构建一个叶子变量。因此 tensor.new_tensor(x) 等价于 x.detach().clone()tensor.new_tensor(x, requires_grad=True) 等价于 x.detach().clone().requires_grad_(True) 。推荐使用 detach()clone() 的等价方法。

参数:

data (array_like) – 返回的 Tensor 会复制 data

关键字参数:
  • dtype( torch.dtype ,可选)- 返回张量的期望类型。默认:如果为 None,则与该张量相同 torch.dtype

  • device( torch.device ,可选)- 返回张量的期望设备。默认:如果为 None,则与该张量相同 torch.device

  • requires_grad (bool,可选) – 如果 autograd 应记录对返回张量的操作。默认: False

  • layout ( torch.layout ,可选) – 返回 Tensor 的期望布局。默认: 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)

© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源