Python中 list, numpy.array, torch.Tensor 格式相互轉化


1.1 list 轉 numpy

ndarray = np.array(list)

 

1.2 numpy 轉 list

list = ndarray.tolist()

 

2.1 list 轉 torch.Tensor

tensor=torch.Tensor(list)

 

2.2 torch.Tensor 轉 list

先轉numpy,后轉list

list = tensor.numpy().tolist()

 

3.1 torch.Tensor 轉 numpy

ndarray = tensor.numpy()

*gpu上的tensor不能直接轉為numpy

ndarray = tensor.cpu().numpy()

 

3.2 numpy 轉 torch.Tensor

tensor = torch.from_numpy(ndarray) 

 


免責聲明!

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



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