Pytorch: list, numpy. Tensor 格式转化 (附 only one element tensors can be converted to Python scalars 解决)

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

同时解决 ValueError:only one element tensors can be converted to Python scalars 问题

 

torch.Tensor 转 numpypython

ndarray = tensor.numpy()spa

若是是在 gpu,命令以下scala

ndarray = tensor.cpu().numpy()  # 这是由于 gpu上的 tensor 不能直接转为 numpycode

 

numpy 转 torch.Tensorelement

tensor = torch.from_numpy(ndarray) it

 

list 转 torch.Tensorclass

tensor=torch.Tensor(list)numpy

注意:有时,上面操做会出现报错:ValueError:only one element tensors can be converted to Python scalars方法

缘由是:要转换的list里面的元素包含多维的tensor。cpu

在 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()

相关文章
相关标签/搜索