欢迎光临散文网 会员登陆 & 注册

在运行反向传播函数之后,立即再次运行它,看看会发生什么

2021-12-01 14:21 作者:如果我是泡橘子  | 我要投稿

正常运行反向传播函数

输出结果如下:
tensor([  0.,   4.,   8.,  12.,  16.,  20.,  24.,  28.,  32.,  36.,  40.,  44.,         48.,  52.,  56.,  60.,  64.,  68.,  72.,  76.,  80.,  84.,  88.,  92.,         96., 100., 104., 108., 112., 116., 120., 124., 128., 132., 136., 140.,        144., 148., 152., 156.])


如果再次运行反向传播

输出结果如下:

RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.

大概的意思好像是说在调用backward()进行第二次反向传播时,计算图中保存的中间值(这里我的理解是第一次求导后的值)已经被释放掉了,所以报错


上面也对二次反向传播提出了解决的方案:在backward()函数中设置参数retain_graph=True

设置了参数后的输出如下:

tensor([  0.,   4.,   8.,  12.,  16.,  20.,  24.,  28.,  32.,  36.,  40.,  44.,         48.,  52.,  56.,  60.,  64.,  68.,  72.,  76.,  80.,  84.,  88.,  92.,         96., 100., 104., 108., 112., 116., 120., 124., 128., 132., 136., 140.,        144., 148., 152., 156.])


尝试进行二次反向传播

输出结果如下:

tensor([  0.,   8.,  16.,  24.,  32.,  40.,  48.,  56.,  64.,  72.,  80.,  88.,         96., 104., 112., 120., 128., 136., 144., 152., 160., 168., 176., 184.,        192., 200., 208., 216., 224., 232., 240., 248., 256., 264., 272., 280.,        288., 296., 304., 312.])


成功完成了二次反向传播!





----end----

在运行反向传播函数之后,立即再次运行它,看看会发生什么的评论 (共 条)

分享到微博请遵守国家法律