快捷键

torch.Tensor.to

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

执行 Tensor 数据类型和/或设备转换。 torch.dtypetorch.deviceself.to(*args, **kwargs) 的参数中推断。

注意

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

下面是调用 to 的方法:

to(数据类型, non_blocking=False, copy=False, memory_format=torch.preserve_format) → 张量

返回具有指定 dtype 的张量

Args:

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。如果 dtypeNone ,则推断为 self.dtype 。当 non_blocking 设置为 True 时,如果可能,函数尝试异步执行与主机相关的转换。这种异步行为适用于固定和可分页内存。但是,在使用此功能时请谨慎。有关更多信息,请参阅有关非阻塞和 pin_memory 的良好使用教程。当 copy 设置时,即使 Tensor 已经匹配所需的转换,也会创建一个新的 Tensor。

Args:

memory_format ( torch.memory_format ,可选):返回 Tensor 所期望的内存格式。默认: torch.preserve_format

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

返回一个与 Tensor other 具有相同 torch.dtypetorch.device 的 Tensor。当 non_blocking 设置为 True 时,如果可能,函数尝试异步执行与主机相关的转换。这种异步行为适用于固定和可分页内存。但是,在使用此功能时请谨慎。有关更多信息,请参阅关于非阻塞和固定内存的良好使用教程。当 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')

© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源