python3 list, np.array, torch.tensor相互转换
ndarray = np.array(list)# list 转 numpy数组list = ndarray.tolist()# numpy 转 listtensor=torch.Tensor(list)# list 转 torch.Tensorlist = tensor.numpy().tolist()# torch.Tensor 转 list先转numpy,后转listndarray = te
·
- 单个变量的转化
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])

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)