快捷方式

torch.tensor

torch.tensor(data, *, dtype=None, device=None, requires_grad=False, pin_memory=False) Tensor

通过复制 data,构造一个没有 autograd 历史的 tensor(也称为“叶子 tensor”,参见 Autograd 机制)。

警告

使用 tensor 时,为提高可读性,优先使用 torch.Tensor.clone()torch.Tensor.detach()torch.Tensor.requires_grad_()。假设 t 是一个 tensor,则 torch.tensor(t) 等价于 t.detach().clone(),而 torch.tensor(t, requires_grad=True) 等价于 t.detach().clone().requires_grad_(True)

另请参见

torch.as_tensor() 会保留 autograd 历史,并尽可能避免复制。torch.from_numpy() 会创建一个与 NumPy 数组共享存储的 tensor。

参数

data (array_like) – tensor 的初始数据。可以是列表、元组、NumPy ndarray、标量或其他类型。

关键字参数
  • dtype (torch.dtype, 可选) – 返回 tensor 期望的数据类型。默认值:如果为 None,则从 data 推断数据类型。

  • device (torch.device, 可选) – 构造的 tensor 所在的设备。如果为 None 且 data 是 tensor,则使用 data 的设备。如果为 None 且 data 不是 tensor,则在当前设备上构造结果 tensor。

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

  • pin_memory (bool, 可选) – 如果设置为 True,返回的 tensor 将分配在 pinned memory 中。仅适用于 CPU tensor。默认值:False

示例

>>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])
tensor([[ 0.1000,  1.2000],
        [ 2.2000,  3.1000],
        [ 4.9000,  5.2000]])

>>> torch.tensor([0, 1])  # Type inference on data
tensor([ 0,  1])

>>> torch.tensor([[0.11111, 0.222222, 0.3333333]],
...              dtype=torch.float64,
...              device=torch.device('cuda:0'))  # creates a double tensor on a CUDA device
tensor([[ 0.1111,  0.2222,  0.3333]], dtype=torch.float64, device='cuda:0')

>>> torch.tensor(3.14159)  # Create a zero-dimensional (scalar) tensor
tensor(3.1416)

>>> torch.tensor([])  # Create an empty tensor (of size (0,))
tensor([])

文档

查阅 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深度教程

查看教程

资源

查找开发资源并获得问题解答

查看资源