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([])