每一年都奔走在自己热爱里

没有人是一座孤岛,总有谁爱着你

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

问题描述

深度学习初学者的我在使用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

posted @   关逍遥  阅读(1688)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示