pytorch使用 to 进行类型转换方式
时间:2021-01-28 10:26:27|栏目:Python代码|点击: 次
在程序中,有多种方法进行强制类型转换。
本博文将介绍一个非常常用的方法: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))
我们看到这个代码会出错的。因为a和b是不同的device,一个是CPU,一个是GPU,不能运行。
修改如下:
a = a.to(b) d = torch.matmul(a, b) print(type(d))

可以看到to还是很好用的,尤其是不确定我们的数据类型和device时。
其实pytorch中还有很多其他方法可以这么做,以后会继续介绍。
上一篇:python访问mysql数据库的实现方法(2则示例)
栏 目:Python代码
下一篇:解决PyCharm import torch包失败的问题
本文地址:http://www.codeinn.net/misctech/52888.html






