Pytorch中Tensor的類型轉換


Pytorch中的Tensor常用的類型轉換函數(inplace操作):

(1)數據類型轉換

  在Tensor后加 .long(), .int(), .float(), .double()等即可,也可以用.to()函數進行轉換,所有的Tensor類型可參考https://pytorch.org/docs/stable/tensors.html

(2)數據存儲位置轉換

  CPU張量 ---->  GPU張量,使用data.cuda()

  GPU張量 ----> CPU張量,使用data.cpu()

(3)與numpy數據類型轉換

  Tensor---->Numpy  使用 data.numpy(),data為Tensor變量

  Numpy ----> Tensor 使用 torch.from_numpy(data),data為numpy變量

(4)與Python數據類型轉換

  Tensor ----> 單個Python數據,使用data.item(),data為Tensor變量且只能為包含單個數據

  Tensor ----> Python list,使用data.tolist(),data為Tensor變量,返回shape相同的可嵌套的list

(5)剝離出一個tensor參與計算,但不參與求導

  Tensor后加 .detach()

  官方解釋為:

  Returns a new Tensor, detached from the current graph. The result will never require gradient. Returned Tensor shares the same storage with the original one. In-place modifications on either of them will be seen, and may trigger errors in correctness checks. 

  (以前這個功能用過.data(),但現在不推薦使用了)

 

 

參考:

https://blog.csdn.net/hustchenze/article/details/79154139

https://pytorch.org/docs/stable/tensors.html#torch.Tensor.to


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM