快捷方式

torch.Tensor.to

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

執行張量 dtype 和/或裝置轉換。 torch.dtypetorch.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, optional): 傳回的 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 時,如果可能,嘗試相對於 host 進行非同步轉換,例如,將具有固定記憶體的 CPU Tensor 轉換為 CUDA Tensor。 當設定 copy 時,即使 Tensor 已經符合所需的轉換,也會建立一個新的 Tensor。

參數

memory_format (torch.memory_format, optional): 傳回的 Tensor 所需的記憶體格式。 預設值:torch.preserve_format

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

傳回具有與 Tensor other 相同的 torch.dtypetorch.device 的 Tensor。 當 non_blocking 為 True 時,如果可能,嘗試相對於 host 進行非同步轉換,例如,將具有固定記憶體的 CPU Tensor 轉換為 CUDA Tensor。 當設定 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')

文件

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