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

16 篇文章 0 订阅
15 篇文章 1 订阅

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

 

 

  • 7
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值