`Pytorch :list, numpy.array, torch.Tensor` 格式相互转化
Pytorch :list, numpy.array, torch.Tensor
格式相互转化
同时解决 ValueError:only one element tensors can be converted to Python scalars
问题
- torch.Tensor
转 numpy
ndarray = tensor.numpy()
如果是在 gpu
,命令如下
ndarray = tensor.cpu().numpy()
# 这是因为 gpu
上的 tensor
不能直接转为 numpy
- numpy
转 torch.Tensor
tensor = torch.from_numpy(ndarray)
- list
转 torch.Tensor
tensor=torch.Tensor(list)
注意:有时,上面操作会出现报错:ValueError:only one element tensors can be converted to Python scalars
原因是:要转换的list
里面的元素包含多维的tensor
。
在 gpu
上的解决方法是:
val= torch.tensor([item.cpu().detach().numpy() for item in val]).cuda()
这是因为 gpu
上的 tensor
不能直接转为 numpy
; 需要先在 cpu
上完成操作,再回到 gpu
上
如果是在 cpu
上,上面的 .cpu()
和 .cuda()
可以省略
torch.Tensor
转 list
list = tensor.numpy().tolist() # 先转 numpy,后转 list
list
转 numpy
ndarray = np.array(list)
numpy
转 list
list = ndarray.tolist()