【Pytorch】tensor、ndarray、list互相转换方法

import numpy as np
import torch


ndarray = np.array(list)  # list 转 numpy数组
list = ndarray.tolist()  # ndarray 转 list
tensor=torch.Tensor(list)  # list 转 torch.Tensor
list = tensor.numpy().tolist()  # torch.Tensor 转 list 先转ndarray,后转list
ndarray = tensor.cpu().numpy()  # torch.Tensor 转 ndarray (gpu上的tensor需要先copy到CPU中才可以转为numpy数组)
tensor = torch.from_numpy(ndarray)  # ndarray 转 torch.Tensor

你可能感兴趣的:(Pytorch,python,pytorch,计算机视觉,人工智能,深度学习)