• 文档 >
  • torch >
  • torch.tensor
快捷键

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() 保留 autograd 历史记录,并在可能的情况下避免复制。 torch.from_numpy() 创建一个与 NumPy 数组共享存储的张量。

参数:

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

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

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

  • requires_grad (bool,可选) – 如果 autograd 应记录对返回张量的操作。默认: 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([])

© 版权所有 PyTorch 贡献者。

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

文档

PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源