python3 list, np.array, torch.tensor相互转换
- 单个变量的转化
ndarray = np.array(list) # list 转 numpy数组
list = ndarray.tolist() # numpy 转 list
tensor=torch.tensor(list) # list 转 torch.Tensor
list = tensor.numpy().tolist() # torch.Tensor 转 list 先转numpy,后转list
ndarray = tensor.cpu().numpy() # torch.Tensor 转 numpy *gpu上的tensor不能直接转为numpy
tensor = torch.from_numpy(ndarray) # numpy 转 torch.Tensor
- 如果一个列表包含很多tensor,需要使用stack来实现
torch_tensor = torch.stack(torch_list)
- 或者多个tensor合并成一个高维tensor,需要使用torch.cat((A,B),axis)来实现
简单理解:aix=0表示增加行,aix=1表示增加列
import torch
# 初始化三个 tensor
A=torch.ones(2,3) #2x3的张量(矩阵)
# tensor([[ 1., 1., 1.],
# [ 1., 1., 1.]])
B=2*torch.ones(4,3) #4x3的张量(矩阵)
# tensor([[ 2., 2., 2.],
# [ 2., 2., 2.],
# [ 2., 2., 2.],
# [ 2., 2., 2.]])
D=2*torch.ones(2,4) # 2x4的张量(矩阵)
# tensor([[ 2., 2., 2., 2.],
# [ 2., 2., 2., 2.],
# 按维数0(行)拼接 A 和 B
C=torch.cat((A,B),0)
# tensor([[ 1., 1., 1.],
# [ 1., 1., 1.],
# [ 2., 2., 2.],
# [ 2., 2., 2.],
# [ 2., 2., 2.],
# [ 2., 2., 2.]])
print(C.shape)
# torch.Size([6, 3])
# 按维数1(列)拼接 A 和 D
C=torch.cat((A,D),1)
# tensor([[ 1., 1., 1., 2., 2., 2., 2.],
# [ 1., 1., 1., 2., 2., 2., 2.]])
print(C.shape)
# torch.Size([2, 7])