python 中 list,numpy,tensor的互相转换

    技术2022-07-20  76

    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]
    Processed: 0.018, SQL: 9