torch.Tensor.to¶
- Tensor.to(*args, **kwargs) Tensor ¶
执行 Tensor 数据类型 (dtype) 和/或设备 (device) 转换。torch.dtype 和 torch.device 会从
self.to(*args, **kwargs)
的参数中推断出来。注意
如果
self
Tensor 已具有正确的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')