ValueError:only one element tensors can be converted to Python scalars解决办法

ValueError:only one element tensors can be converted to Python scalars解决办法,第1张

ValueError:only one element tensors can be converted to Python scalars解决办法
  • 问题描述
  • 解决办法
  • 补充
    • 1.torch.Tensor 转 numpy
    • 2.numpy 转 torch.Tensor
    • 3.torch.Tensor 转 list
    • 4.list 转 numpy
    • 5.numpy 转 list


问题描述

深度学习初学者的我在使用pytorch debug深度神经网络模型的时候,list,tensor,array之间的转化太复杂了,总是傻傻分不清。这次又遇到问题:ValueError:only one element tensors can be converted to Python scalars。

解决办法

原因:要转换的list里面的元素包含多维的tensor。
一般list 转 torch.tensor只需要

tensor=torch.tensor(list)

但是要转换的list里面的元素包含多维的tensor,应该使用

val= torch.tensor([item.cpu().detach().numpy() for item in val]).cuda()

这是由于 gpu上的 tensor 不能直接转为 numpy; 须要先在 cpu 上完成 *** 做,再回到 gpu 上。

补充 1.torch.Tensor 转 numpy

ndarray = tensor.numpy()
若是是在 gpu,命令以下

ndarray = tensor.cpu().numpy() 

这是由于 gpu上的 tensor 不能直接转为 numpy

2.numpy 转 torch.Tensor
tensor = torch.from_numpy(ndarray) 
3.torch.Tensor 转 list
list = tensor.numpy().tolist()  

先转 numpy,后转 list

4.list 转 numpy
ndarray = np.array(list)
5.numpy 转 list
list = ndarray.tolist()

参考链接:https://www.shangmayuan.com/a/fc6aaa7ff67443c68dbf3966.html

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/943561.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-18
下一篇 2022-05-18

发表评论

登录后才能评论

评论列表(0条)

保存