2017-05-30 113 views
3

我試圖在pytorch中實現向後的漸變函數。pytorch中的向後漸變函數

但是,我不知道爲什麼這個值返回。

這是我的代碼。

x = Variable(torch.FloatTensor([[1,2],[3,4]]), requires_grad=True) 
y = x + 2 
z = y * y 

gradient = torch.ones(2, 2) 
z.backward(gradient) 
print(x.grad) 

我認爲結果值應爲[[6,8],[10,12]]

因爲DZ/DX = 2 *(X + 2)和x = 1,2的,3,4

但返回的值是[7,9],[11,13]

這是爲什麼發生的事情。我想知道如何梯度,研究生功能在做什麼。

幫我請..

回答

2

上pytorch v0.12.1下面的代碼

import torch 
from torch.autograd import Variable 
x = Variable(torch.FloatTensor([[1,2],[3,4]]), requires_grad=True) 
y = x + 2 
z = y * y 
gradient = torch.ones(2, 2) 
z.backward(gradient) 
print(x.grad) 

回報

Variable containing: 
    6 8 
10 12 
[torch.FloatTensor of size 2x2] 

更新您的pytorch安裝。 This解釋了autograd的工作,它處理pytorch的梯度計算。