在運(yùn)行反向傳播函數(shù)之后,立即再次運(yùn)行它,看看會發(fā)生什么
正常運(yùn)行反向傳播函數(shù)
輸出結(jié)果如下:
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.])
如果再次運(yùn)行反向傳播
輸出結(jié)果如下:
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.
大概的意思好像是說在調(diào)用backward()進(jìn)行第二次反向傳播時(shí),計(jì)算圖中保存的中間值(這里我的理解是第一次求導(dǎo)后的值)已經(jīng)被釋放掉了,所以報(bào)錯(cuò)
上面也對二次反向傳播提出了解決的方案:在backward()函數(shù)中設(shè)置參數(shù)retain_graph=True
設(shè)置了參數(shù)后的輸出如下:
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.])
嘗試進(jìn)行二次反向傳播
輸出結(jié)果如下:
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----