Loading

`Pytorch :list, numpy.array, torch.Tensor` 格式相互转化

Pytorch :list, numpy.array, torch.Tensor 格式相互转化
同时解决 ValueError:only one element tensors can be converted to Python scalars 问题
- torch.Tensornumpy
ndarray = tensor.numpy()
如果是在 gpu,命令如下
ndarray = tensor.cpu().numpy() # 这是因为 gpu上的 tensor 不能直接转为 numpy

- numpytorch.Tensor
tensor = torch.from_numpy(ndarray)

- listtorch.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.Tensorlist
list = tensor.numpy().tolist() # 先转 numpy,后转 list

listnumpy
ndarray = np.array(list)

numpylist
list = ndarray.tolist()

文章转自:https://my.oschina.net/u/4267117/blog/4810042(侵删!)

posted @ 2021-03-17 19:43  Guang'Jun  阅读(1082)  评论(0)    收藏  举报