天天看點

Python中 list, numpy.array, torch.Tensor 格式互相轉化

Python中 list, numpy.array, torch.Tensor 格式互相轉化

1.1 list 轉 numpy

ndarray = np.array(list)

1.2 numpy 轉 list

list = ndarray.tolist()

2.1 list 轉 torch.Tensor

tensor=torch.Tensor(list)

2.2 torch.Tensor 轉 list

先轉numpy,後轉list

list = tensor.numpy().tolist()

3.1 torch.Tensor 轉 numpy

ndarray = tensor.numpy()

*gpu上的tensor不能直接轉為numpy

ndarray = tensor.cpu().numpy()

3.2 numpy 轉 torch.Tensor

tensor = torch.from_numpy(ndarray)