在程序中,有多種方法進行強制類型轉換。
本博文將介紹一個非常常用的方法: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類型
1
2
3
4
5
6
7
8
9
10
11
12
|
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,不能運行。
修改如下:
1
2
3
|
a = a.to(b) d = torch.matmul(a, b) print ( type (d)) |
可以看到to還是很好用的,尤其是不確定我們的數據類型和device時。
其實pytorch中還有很多其他方法可以這么做,以后會繼續介紹。
以上這篇pytorch使用 to 進行類型轉換方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/qq_27261889/article/details/100175612