PyTorch中 tensor.detach() 和 tensor.data 的區別詳解
阿新 • • 發佈:2020-01-09
PyTorch0.4中,.data 仍保留,但建議使用 .detach(),區別在於 .data 返回和 x 的相同資料 tensor,但不會加入到x的計算曆史裡,且require s_grad = False,這樣有些時候是不安全的,因為 x.data 不能被 autograd 追蹤求微分 。
.detach() 返回相同資料的 tensor,且 requires_grad=False,但能通過 in-place 操作報告給 autograd 在進行反向傳播的時候.
舉例:
tensor.data
>>> a = torch.tensor([1,2,3.],requires_grad =True) >>> out = a.sigmoid() >>> c = out.data >>> c.zero_() tensor([ 0.,0.,0.]) >>> out # out的數值被c.zero_()修改 tensor([ 0.,0.]) >>> out.sum().backward() # 反向傳播 >>> a.grad # 這個結果很嚴重的錯誤,因為out已經改變了 tensor([ 0.,0.])
tensor.detach()
>>> a = torch.tensor([1,requires_grad =True) >>> out = a.sigmoid() >>> c = out.detach() >>> c.zero_() tensor([ 0.,0.]) >>> out # out的值被c.zero_()修改 !! tensor([ 0.,0.]) >>> out.sum().backward() # 需要原來out得值,但是已經被c.zero_()覆蓋了,結果報錯 RuntimeError: one of the variables needed for gradient computation has been modified by an
以上這篇PyTorch中 tensor.detach() 和 tensor.data 的區別詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。