torch.Tensor.to¶
- Tensor.to(*args, **kwargs) Tensor¶
執行 Tensor 資料型別 (dtype) 和/或裝置 (device) 轉換。torch.dtype 和 torch.device 會從
self.to(*args, **kwargs)的引數中推斷出來。注意
如果
selfTensor 已具有正確的torch.dtype和torch.device,則返回self。否則,返回的 Tensor 是self的一個副本,具有期望的torch.dtype和torch.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。如果dtype為None,則將其推斷為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.dtype和torch.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')