pytorch使用 to 進行型別轉換方式
阿新 • • 發佈:2020-01-09
在程式中,有多種方法進行強制型別轉換。
本博文將介紹一個非常常用的方法: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 進行型別轉換方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。