捷徑

torch.Tensor.new_tensor

Tensor.new_tensor(data, *, dtype=None, device=None, requires_grad=False, layout=torch.strided, pin_memory=False) Tensor

返回一個新的 Tensor,其張量資料為 data。預設情況下,返回的 Tensor 具有與此張量相同的 torch.dtypetorch.device

警告

new_tensor() 總是複製 data。如果您有一個 Tensor data 並且想要避免複製,請使用 torch.Tensor.requires_grad_()torch.Tensor.detach()。如果您有一個 numpy 陣列並且想要避免複製,請使用 torch.from_numpy()

警告

當 data 是一個張量 x 時,new_tensor() 會從傳入的任何內容中讀取「資料」,並建構一個葉節點變數。因此,tensor.new_tensor(x) 等同於 x.clone().detach(),而 tensor.new_tensor(x, requires_grad=True) 等同於 x.clone().detach().requires_grad_(True)。建議使用 clone()detach() 的等效寫法。

參數

data (array_like) – 返回的 Tensor 會複製 data

關鍵字參數
  • dtype (torch.dtype, optional) – 返回的張量所需的資料型別。預設值:如果為 None,則與此張量的 torch.dtype 相同。

  • device (torch.device, optional) – 返回的張量所需的裝置。預設值:如果為 None,則與此張量的 torch.device 相同。

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

  • layout (torch.layout, optional) – 返回的 Tensor 所需的 layout。預設值:torch.strided

  • pin_memory (bool, optional) – 如果設定,返回的張量將分配在鎖頁記憶體中。僅適用於 CPU 張量。預設值:False

範例

>>> tensor = torch.ones((2,), dtype=torch.int8)
>>> data = [[0, 1], [2, 3]]
>>> tensor.new_tensor(data)
tensor([[ 0,  1],
        [ 2,  3]], dtype=torch.int8)

文件

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