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
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> 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. , 0. ]) >>> out. sum ().backward() # 反向傳播 >>> a.grad # 這個結果很嚴重的錯誤,因為out已經改變了 tensor([ 0. , 0. , 0. ]) |
tensor.detach()
1
2
3
4
5
6
7
8
9
10
11
12
|
>>> a = torch.tensor([ 1 , 2 , 3. ], requires_grad = True ) >>> out = a.sigmoid() >>> c = out.detach() >>> c.zero_() tensor([ 0. , 0. , 0. ]) >>> out # out的值被c.zero_()修改 !! tensor([ 0. , 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 的區別詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/DreamHome_S/article/details/85259533