评价此页

torch.tensor#

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

通过复制 data 构造一个没有自动求导历史的张量(也称为“叶张量”,参见 自动求导机制)。

警告

在使用张量时,为了可读性,最好使用 torch.Tensor.clone()torch.Tensor.detach()torch.Tensor.requires_grad_()。令 t 为一个张量,torch.tensor(t) 等价于 t.detach().clone(),而 torch.tensor(t, requires_grad=True) 等价于 t.detach().clone().requires_grad_(True)

另请参阅

torch.as_tensor() 保留自动求导历史,并尽可能避免复制。torch.from_numpy() 创建一个与 NumPy 数组共享存储的张量。

参数

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

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

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

  • requires_grad (bool, 可选) – 如果自动求导应该记录返回张量上的操作。默认值:False

  • pin_memory (bool, 可选) – 如果设置,返回的张量将分配到固定内存中。仅适用于 CPU 张量。默认值: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([])