当前位置:实例文章 » Python实例» [文章]ValueError: only one element tensors can be converted to Python scalars

ValueError: only one element tensors can be converted to Python scalars

发布人:shili8 发布时间:2023-03-22 08:34 阅读次数:39

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

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

相关标签:

免责声明

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱290110527@qq.com删除。

其他信息

其他资源

Top