Shortcuts

torch.Tensor.to

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

执行张量的数据类型和/或设备转换。torch.dtypetorch.device 是从 self.to(*args, **kwargs) 的参数推断出来的。

注意

如果 self 张量已经具有正确的 torch.dtypetorch.device,则返回 self。 否则,返回的张量是 self 的副本,具有所需的 torch.dtypetorch.device

以下是调用 to 的方法:

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

返回一个具有指定dtype的张量

Args:

memory_format (torch.memory_format, 可选): 返回的张量所需的内存格式。默认值: torch.preserve_format

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

返回一个具有指定设备和(可选) 数据类型的张量。如果数据类型None,则推断为self.dtype。 当non_blocking时,尝试在可能的情况下异步转换,例如将具有固定内存的CPU张量转换为CUDA张量。 当copy被设置时,即使张量已经匹配所需的转换,也会创建一个新的张量。

Args:

memory_format (torch.memory_format, 可选): 返回的张量所需的内存格式。默认值: torch.preserve_format

torch.to(other, non_blocking=False, copy=False) 张量

返回一个与张量 other 具有相同 torch.dtypetorch.device 的张量。当 non_blocking 时,如果可能,尝试异步转换,例如将具有固定内存的 CPU 张量转换为 CUDA 张量。当 copy 被设置时,即使张量已经匹配所需的转换,也会创建一个新的张量。

示例:

>>> tensor = torch.randn(2, 2)  # 最初 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')
优云智算