torch.Tensor.new_tensor#
- Tensor.new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) Tensor#
返回一个具有
data作为张量数据的张量。默认情况下,返回的张量具有与此张量相同的torch.dtype和torch.device。警告
new_tensor()总是会复制data。如果您有一个张量data并想避免复制,请使用torch.Tensor.requires_grad_()或torch.Tensor.detach()。如果您有一个 numpy 数组并想避免复制,请使用torch.from_numpy()。警告
当 data 是张量 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) – 返回的张量会复制
data。- 关键字参数
dtype (
torch.dtype, 可选) – 所需的返回 tensor 的类型。默认值:如果为 None,则与此 tensor 相同torch.dtype。device (
torch.device, 可选) – 所需的返回 tensor 的设备。默认值:如果为 None,则与此 tensor 相同torch.device。requires_grad (bool, optional) – 如果 autograd 应记录在返回的张量上的操作。默认值:
False。layout (
torch.layout, 可选) – 返回张量的所需布局。默认:torch.strided。pin_memory (bool, optional) – 如果设置为 True,则返回的张量将被分配到固定内存中。仅适用于 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)