python问题一览
最近敲代码,发现好多bug都是曾经出现过的,自己有很多记不住,就做个记录,方便找
- Object of type method is not JSON serializable
json.dumps(your_data, default=str) - Json不能输出nd、dict
dict: str(k): a[k] for k in a
nd: nd.tolist() - RuntimeError: result type Float can‘t be cast to the desired output type Long
output和target的数据类型应一致,原本target为long类型,output为float,但是无法将output转为long,只能将target转为float
y = y.float() - ValueError:only one element tensors can be converted to Python scalars
原因是:要转换的list里面的元素包含多维的tensor。
gpu :
val= torch.tensor([item.cpu().detach().numpy() for item in val]).cuda()
这是因为 gpu上的 tensor 不能直接转为 numpy; 需要先在 cpu 上完成操作,再回到 gpu 上
cpu:.cpu() 和 .cuda() 可以省略