如何用PyTorch的to方法实现数据类型转换?
- 内容介绍
- 文章标签
- 相关推荐
本文共计394个文字,预计阅读时间需要2分钟。
在编程中,有多种方法进行强制类型转换。本文将介绍一种非常实用的方法:`to()`方法。我们通常使用它来进行GPU和CPU的类型转换,但事实上,也可以用它来转换torch的dtype。
常见用法:`to()`方法
在程序中,有多种方法进行强制类型转换。
本博文将介绍一个非常常用的方法:to()方法。
我们通常使用它来进行GPU和CPU的类型转换,但其实也可以用来进行torch的dtype转换。
常见方法:tensor.to(‘cuda:0')
先看官网介绍:
**Performs Tensor dtype and/or device conversion. A torch.dtype and torch.device are inferred from the arguments of self.to(*args, kwargs).
本文举一个例子,将一个tensor转化成与另一个tensor相同的数据类型和相同GPU或CPU类型
import torch device = 'cuda:0' a = torch.zeros(2, 3) print(type(a)) b = torch.ones(3, 4).to(device) print(type(b)) c = torch.matmul(a, b) print(type(c))
我们看到这个代码会出错的。
本文共计394个文字,预计阅读时间需要2分钟。
在编程中,有多种方法进行强制类型转换。本文将介绍一种非常实用的方法:`to()`方法。我们通常使用它来进行GPU和CPU的类型转换,但事实上,也可以用它来转换torch的dtype。
常见用法:`to()`方法
在程序中,有多种方法进行强制类型转换。
本博文将介绍一个非常常用的方法:to()方法。
我们通常使用它来进行GPU和CPU的类型转换,但其实也可以用来进行torch的dtype转换。
常见方法:tensor.to(‘cuda:0')
先看官网介绍:
**Performs Tensor dtype and/or device conversion. A torch.dtype and torch.device are inferred from the arguments of self.to(*args, kwargs).
本文举一个例子,将一个tensor转化成与另一个tensor相同的数据类型和相同GPU或CPU类型
import torch device = 'cuda:0' a = torch.zeros(2, 3) print(type(a)) b = torch.ones(3, 4).to(device) print(type(b)) c = torch.matmul(a, b) print(type(c))
我们看到这个代码会出错的。

