cod*_*ino 0 python numpy list tensor
我有一个变量losses_all = []想要转换为 np.array。我尝试使用代码执行此操作并收到以下错误:
# convert to numpy array
losses = np.array(losses_all)
# ERROR MESSAGE
RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.
Run Code Online (Sandbox Code Playgroud)
我也尝试过这个,但出现以下错误:
# using code from error message above
losses=losses_all.detach().numpy()
# NEW ERROR MESSAGE
AttributeError: 'list' object has no attribute 'detach'
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以将此变量转换为数组吗?
小智 5
您正在列表变量上调用 numpy 数组。如果你的列表loss_all有不同的张量值,那么
像这样调用:
losses= [ loss.detach().numpy() for loss in losses_all]
Run Code Online (Sandbox Code Playgroud)