捷徑

torch.tensor

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

透過複製 data 來建構一個沒有 autograd 歷史記錄的 tensor (也稱為 "leaf tensor",請參閱 Autograd 機制)。

警告

在使用 tensors 時,為了可讀性,建議使用 torch.Tensor.clone(), torch.Tensor.detach(), 和 torch.Tensor.requires_grad_()。假設 t 是一個 tensor,則 torch.tensor(t) 等同於 t.clone().detach(),且 torch.tensor(t, requires_grad=True) 等同於 t.clone().detach().requires_grad_(True)

另請參閱

torch.as_tensor() 保留 autograd 歷史記錄,並在可能的情況下避免複製。 torch.from_numpy() 創建一個與 NumPy 陣列共享儲存空間的 tensor。

參數

data (array_like) – tensor 的初始資料。 可以是 list、tuple、NumPy ndarray、純量和其他類型。

關鍵字參數
  • dtype (torch.dtype, optional) – 返回 tensor 的所需資料類型。預設值:如果 None,則從 data 推斷資料類型。

  • device (torch.device, optional) – 建構的 tensor 的裝置。 如果為 None 且 data 是一個 tensor,則使用 data 的裝置。 如果為 None 且 data 不是一個 tensor,則結果 tensor 會在目前的裝置上建構。

  • requires_grad (bool, optional) – 如果 autograd 應該記錄返回的 tensor 上的操作。 預設值:False

  • pin_memory (bool, optional) – 如果設定,返回的 tensor 將會在釘選記憶體 (pinned memory) 中分配。 僅適用於 CPU tensors。預設值: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([])

文件

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources