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