import torch
import numpy as np
print('##########建立 a-list;; b-numpy;; c- tensor##########')
a = [1,2,3,4,5]
b = np.array([1,2,3,4,5])
c = torch.arange(1,6)
print('a-list:',a,'\n',
'b-ndarray:',b,'\n',
'c-tensor:',c,c.type())
print('\n########list轉numpy 和 tensor ###############')
list_numpy = np.array(a)
list_tensor = torch.tensor(a)
print(list_numpy,list_tensor)
print('\n##########numpy轉 list 和 tensor ##########')
numpy_list = b.tolist()
numpy_tensor = torch.from_numpy(b)
print(numpy_list,numpy_tensor)
print('\n##############tensor 轉 list (先轉numpy,後轉list) 和 numpy ##########')
tensor_list = c.numpy().tolist()
tensor_numpy = c.numpy()
print(tensor_list,tensor_numpy)
# 如果tensor是GPU上的tensor,先轉成CPU,再轉爲numpy
ndarray = tensor.cpu().numpy()
#輸出#
E:\Anconda\python.exe "C:/Users/MR-LI/Desktop/program practice/TRY/train.py"
##########建立 a-list;; b-numpy;; c- tensor##########
a-list: [1, 2, 3, 4, 5]
b-ndarray: [1 2 3 4 5]
c-tensor: tensor([1, 2, 3, 4, 5]) torch.LongTensor
########list轉numpy 和 tensor ###############
[1 2 3 4 5] tensor([1, 2, 3, 4, 5])
##########numpy轉 list 和 tensor ##########
[1, 2, 3, 4, 5] tensor([1, 2, 3, 4, 5], dtype=torch.int32)
##############tensor 轉 list 和 numpy ##########
[1, 2, 3, 4, 5] [1 2 3 4 5]
python 中 list,numpy,tensor的互相轉換
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.