評價此頁

torch.Tensor.new_tensor#

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

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

警告

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

警告

當 data 是張量 x 時,new_tensor() 會讀取傳入的任何內容中的“資料”,並構建一個葉子變數。因此 tensor.new_tensor(x) 等同於 x.detach().clone(),而 tensor.new_tensor(x, requires_grad=True) 等同於 x.detach().clone().requires_grad_(True)。推薦使用 detach()clone() 的等價用法。

引數

data (array_like) – 返回的張量會複製 data

關鍵字引數
  • dtype (torch.dtype, 可選) – 所需的返回 tensor 的型別。預設值:如果為 None,則與此 tensor 相同 torch.dtype

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

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

  • layout (torch.layout, 可選) – 返回張量的所需佈局。預設:torch.strided

  • pin_memory (bool, optional) – 如果設定為 True,則返回的張量將被分配到固定記憶體中。僅適用於 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)