torch.autograd 包提供Tensor所有操作的自動求導方法。
數據結構介紹
autograd.Variable 這是這個包中最核心的類。 它包裝了一個Tensor,並且幾乎支持所有的定義在其上的操作。一旦完成了你的運算,你可以調用 .backward()來自動計算出所有的梯度,Variable有三個屬性:
訪問原始的tensor使用屬性.data;
關於這一Variable的梯度則集中於 .grad;
.creator反映了創建者,標識了是否由用戶使用.Variable直接創建(None)。
1 import torch 2 from torch.autograd import Variable 3 4 5 '''求導數''' 6 7 x = Variable(torch.ones(2,2),requires_grad=True) 8 y = x + 2 9 print(x.creator) # None,用戶直接創建沒有creater屬性 10 print(y.creator) # <torch.autograd._functions.basic_ops.AddConstant object at 0x7fb9b4d4b208>
返回:
None
<torch.autograd._functions.basic_ops.AddConstant object at 0x7fb9b4d4b208>
求導運算
如果你想要進行求導計算,你可以在Variable上調用.backward()。
-
如果Variable是一個標量(例如它包含一個單元素數據),你無需對backward()指定任何參數
1 z = y*y*3 2 out = z.mean() 3 4 out.backward() 5 6 print(x,y,z) 7 print(x.grad) # 輸出對out對x求倒結果 8 print(y.grad) # y不是自動求導變量
Variable containing: 1 1 1 1 [torch.FloatTensor of size 2x2] Variable containing: 3 3 3 3 [torch.FloatTensor of size 2x2] Variable containing: 27 27 27 27 [torch.FloatTensor of size 2x2] Variable containing: 4.5000 4.5000 4.5000 4.5000 [torch.FloatTensor of size 2x2] None
最終得出的結果應該是一個全是4.5的矩陣。設置輸出的變量為o。我們通過這一公式來計算:
,
,
,因此,
,最后有
-
如果它有更多的元素(矢量),你需要指定一個和tensor的形狀匹配的grad_output參數(y在指定方向投影對x的導數)
1 x = torch.randn(3) 2 x = Variable(x, requires_grad = True) 3 y = x * 2 4 while y.data.norm() < 1000: 5 y = y * 2 6 gradients = torch.FloatTensor([0.1, 1.0, 0.0001]) 7 y.backward(gradients) 8 x.grad
Variable containing: -0.8143 -1.5852 -0.8598 [torch.FloatTensor of size 3] Variable containing: -1.6286 -3.1704 -1.7195 [torch.FloatTensor of size 3] 3.9573325720437613 Variable containing: 51.2000 512.0000 0.0512 [torch.FloatTensor of size 3]
測試傳入向量的意義:
1 x = torch.randn(3) 2 x = Variable(x,requires_grad=True) 3 y = x*2 4 5 gradients = torch.FloatTensor([0.5,0.5,1]) 6 y.backward(gradients) # 沿着某方向的梯度 7 print(x.grad) 8 9 # Variable containing: 10 # 1 11 # 1 12 # 2 13 # [torch.FloatTensor of size 3]
1 x = torch.randn(3) 2 x = Variable(x,requires_grad=True) 3 y = x*2 4 5 gradients = torch.FloatTensor([1,1,1]) 6 y.backward(gradients) # 沿着某方向的梯度 7 print(x.grad) 8 9 # Variable containing: 10 # 2 11 # 2 12 # 2 13 # [torch.FloatTensor of size 3]