网络编程
位置:首页>> 网络编程>> Python编程>> pytorch使用 to 进行类型转换方式

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

作者:月下花弄影  发布时间:2022-10-05 23:28:27 

标签:pytorch,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))

我们看到这个代码会出错的。因为a和b是不同的device,一个是CPU,一个是GPU,不能运行。

修改如下:


a = a.to(b)
d = torch.matmul(a, b)
print(type(d))

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

可以看到to还是很好用的,尤其是不确定我们的数据类型和device时。

其实pytorch中还有很多其他方法可以这么做,以后会继续介绍。

来源:https://blog.csdn.net/qq_27261889/article/details/100175612

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com