Pytorch 學習筆記

資源

這裡補充一些 Variable 的小東西

1
2
3
4
5
6
7
a = Variable(torch.Tensor([3]), requires_grad = True)
b = Variable(torch.Tensor([4]), requires_grad = True)
print(a,b)
d = a.pow(2) + b # a^2 + b

可以透過 算出 梯度

1
2
3
d.backward()
print(a.grad)
print(b.grad)

輸出是

1
2
3
4
5
6
7
Variable containing:
6
[torch.FloatTensor of size 1]
Variable containing:
1
[torch.FloatTensor of size 1]

透過 grad_fn 可以看出計算圖(Computation Graph)長成甚麼樣子

1
2
print(d.grad_fn)
print(d.grad_fn.next_functions)

輸出

1
2
<AddBackward1 object at 0x7f73196e5eb8>
((<PowBackward0 object at 0x7f73196e5ba8>, 0), (<AccumulateGrad object at 0x7f73196e5b38>, 0))
Donate comment here