问题描述

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

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐