快捷方式

torch.Tensor.to

Tensor.to(*args, **kwargs) Tensor

執行 Tensor 資料型別 (dtype) 和/或裝置 (device) 轉換。torch.dtype 和 torch.device 會從 self.to(*args, **kwargs) 的引數中推斷出來。

注意

如果 self Tensor 已具有正確的 torch.dtypetorch.device,則返回 self。否則,返回的 Tensor 是 self 的一個副本,具有期望的 torch.dtypetorch.device

以下是呼叫 to 的幾種方式

to(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) Tensor

返回具有指定 dtype 的 Tensor

引數

memory_format (torch.memory_format, 可選): 返回 Tensor 的期望記憶體格式。預設值: torch.preserve_format

torch.to(device=None, dtype=None, non_blocking=False, copy=False, memory_format=torch.preserve_format) Tensor

返回具有指定 device 和 (可選) dtype 的 Tensor。如果 dtypeNone,則將其推斷為 self.dtype。當 non_blocking 設定為 True 時,如果可能,函式會嘗試相對於主機非同步執行轉換。這種非同步行為適用於鎖頁記憶體和可分頁記憶體。然而,建議在使用此功能時謹慎。更多資訊,請參閱 關於良好使用 non_blocking 和 pin_memory 的教程。當 copy 設定時,即使 Tensor 已匹配期望的轉換,也會建立一個新的 Tensor。

引數

memory_format (torch.memory_format, 可選): 返回 Tensor 的期望記憶體格式。預設值: torch.preserve_format

torch.to(other, non_blocking=False, copy=False) Tensor

返回一個與 Tensor other 具有相同 torch.dtypetorch.device 的 Tensor。當 non_blocking 設定為 True 時,如果可能,函式會嘗試相對於主機非同步執行轉換。這種非同步行為適用於鎖頁記憶體和可分頁記憶體。然而,建議在使用此功能時謹慎。更多資訊,請參閱 關於良好使用 non_blocking 和 pin_memory 的教程。當 copy 設定時,即使 Tensor 已匹配期望的轉換,也會建立一個新的 Tensor。

示例

>>> tensor = torch.randn(2, 2)  # Initially dtype=float32, device=cpu
>>> tensor.to(torch.float64)
tensor([[-0.5044,  0.0005],
        [ 0.3310, -0.0584]], dtype=torch.float64)

>>> cuda0 = torch.device('cuda:0')
>>> tensor.to(cuda0)
tensor([[-0.5044,  0.0005],
        [ 0.3310, -0.0584]], device='cuda:0')

>>> tensor.to(cuda0, dtype=torch.float64)
tensor([[-0.5044,  0.0005],
        [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0')

>>> other = torch.randn((), dtype=torch.float64, device=cuda0)
>>> tensor.to(other, non_blocking=True)
tensor([[-0.5044,  0.0005],
        [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0')

文件

訪問 PyTorch 的全面開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源