马春杰杰 Exit Reader Mode

[mcj]RuntimeError: Trying to backward through the graph a second time, but the buffers have….

pytorch 进行反向传播有时会报错:

RuntimeError                              Traceback (most recent call last)
<ipython-input-52-049eeb1d9b54> in <module>
----> 1 v_out.backward()
      2 print(variable.grad)

~/.conda/envs/pytorch/lib/python3.6/site-packages/torch/tensor.py in backward(self, gradient, retain_graph, create_graph)
    100                 products. Defaults to ``False``.
    101         """
--> 102         torch.autograd.backward(self, gradient, retain_graph, create_graph)
    103 
    104     def register_hook(self, hook):

~/.conda/envs/pytorch/lib/python3.6/site-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)
     88     Variable._execution_engine.run_backward(
     89         tensors, grad_tensors, retain_graph, create_graph,
---> 90         allow_unreachable=True)  # allow_unreachable flag
     91 
     92 

RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.

这是因为第一次反向传播之后,这个计算图的内存就会被释放掉,这样的话再次进行反向传播就不行了,解决方法就是添加retain_graph=True这个参数。

添加方法:

温馨提示: 此处内容需要 评论本文刷新本页 才能查看!
本文最后更新于2019年5月26日,已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!