踩坑 ValueError:only one element tensors can be converted to Python scalarsC
list 转 torch.Tensor
tensor=torch.Tensor(list)
注意:有时,上面操作会出现报错:ValueError:only one element tensors can be converted to Python scalars
原因是:要转换的list里面的元素包含多维的tensor。
就像这个样子 [tensor,tensor…]
在 gpu 上的解决方法是:
val= torch.tensor([item.cpu().detach().numpy() for item in val]).cuda()
这是因为 gpu上的 tensor 不能直接转为 numpy; 需要先在 cpu 上完成操作,再回到 gpu 上。
如果是在 cpu 上,上面的 .cpu() 和 .cuda() 可以省略