python中list array torch相互轉換


一、生成array\list\tensor

1.生成array

import numpy as np
a1 = array([[1,2],[3,4]])

2. 生成list

a2 = list(range(16)) 

3.生成tensor

import torch
a3 = torch.tensor([[1,2],[3,4]])

還有一些生成特定的tensor方法,比如:

torch.zeros(3)   #生成3*3的zero-tensor
torch.zeros_like(tensora) #生成一個與tensora維度相同的zero-tensor

torch.ones(3) #生成3*3的one-tensor
torch.ones_like(tensora) #生成一個與tensora維度相同的one-tensor

torch.full(dims, value) #生成全部是value的dims維tensor

torch.eye(dim) #單元tensor eye只能建立方陣

二、相互轉換

1.list 與 array相互轉換

注意到array是numpy中的。因此導入numpy包。利用np.array()a.tolist()來實現轉換。

a1 = np.array([[1,2],[3,4]])
m = a1.tolist()    # array 2 list
m.remove(m[0])  #進行一些操作
a2 = np.array(m) #list 2 array

2. list 與 tensor 相互轉換

t = torch.Tensor(l)     # list 2 tensor
l = t.numpy().tolist()  # tensor 2 list

3.array 與 tensor 相互轉換

t = torch.from_numpy(n) # numpy 2 tensor
n = t.numpy()           # tensor 2 numpy

三、不同格式數據的類型轉換

t.int() # tensor
n.astype(np.int32) # array
l = [int(i) for i in l] # list
l = list(map(int, l)) # list

ref: csdn_blog


免責聲明!

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



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