torch.Tensor.to
- to(*args, **kwargs) → Tensor
-
执行张量的数据类型和/或设备的转换。从
self.to(*args, **kwargs)
的参数中推断出torch.dtype
和torch.device
。注意
如果
self
张量已经具有正确的torch.dtype
和torch.device
,则直接返回self
。否则,会返回一个新的张量,它是self
的副本,并且具有所需的torch.dtype
和torch.device
。以下是调用
to
的方式:- 转换为(dtype, non_blocking=False, copy=False, memory_format=torch.preserve_format) → Tensor
-
返回一个具有指定
dtype
的张量- 参数:
-
memory_format (
torch.memory_format
, 可选): 指定返回张量的内存格式。默认值: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
设置时,如果可能的话,尝试异步地将 Tensor 转换到目标设备上,例如将具有固定内存的 CPU Tensor 转换为 CUDA Tensor。当copy
设置时,即使 Tensor 已经匹配所需的转换条件,也会创建一个新的 Tensor。- 参数:
-
memory_format (
torch.memory_format
, 可选): 指定返回张量的内存格式。默认值:torch.preserve_format
。
- torch.to(other, non_blocking=False, copy=False) → Tensor
-
返回一个与 Tensor
other
具有相同torch.dtype
和torch.device
的 Tensor。当non_blocking
为真时,如果可能的话,尝试异步地在主机上进行转换(例如将具有固定内存的 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')