Pytorch中的Tensor常用的型別轉換函式

2021-10-25 22:30:44 字數 1083 閱讀 2008

pytorch中的tensor常用的型別轉換函式(inplace操作):

(1)資料型別轉換

在tensor後加.long(),.int(),.float(),.double()等即可,也可以用.to()函式進行轉換,所有的tensor型別可參考

(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(),但現在不推薦使用了)

pytorch中tensor型別轉換

tensor轉numpy tensor.numpy numpy轉tensor torch.from numpy 2 tensor與list tensor轉list tensor.tolist list轉tensor torch.tensor 3 tensor型別轉換 tensor torch.ten...

pytorch中tensor的型別轉換

1 資料型別轉換 在tensor後加 long int float double 等即可,也可以用.to 函式進行轉換,所有的tensor型別可參考 2 資料儲存位置轉換 cpu張量 gpu張量,使用data.cuda gpu張量 cpu張量,使用data.cpu 3 與numpy資料型別轉換 te...

pytorch中的Tensor使用入門

1.3 級聯操作cat 1.4 常用tensor 1.5 tensor在cnn中的形式 1.6 element wise 直接建立 t torch.rand 3,4 把numpy轉為tensor t np.random.rand 3,4 torch.tensor是呼叫乙個類,會預設把data轉為fl...