您的位置:首页 > 其它

pytorch使用 to 进行类型转换方式

2020-03-20 12:04 821 查看

在程序中,有多种方法进行强制类型转换。

本博文将介绍一个非常常用的方法: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中还有很多其他方法可以这么做,以后会继续介绍。

以上这篇pytorch使用 to 进行类型转换方式就是小编分享给大家的全部内容了,希望能给大家一个参考

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pytorch to 类型转换
相关文章推荐