Pytorch 自動求導
深度學習的算法本質上是通過反向傳播求導數,而Pytorch的autograd模塊實現了此功能。在Tensor上的所有操作,autograd均能爲它們提供自動微分
# 在創建張量的時候,可以通過指定requires_grad=True標識,進行自動求導,Pytorch會記錄該張量的每一步操作歷史,並自動計算
import torch
x = torch.rand(3, 3, requires_grad=True)
x
tensor([[0.0803, 0.9218, 0.3219],
[0.8003, 0.1912, 0.9332],
[0.6010, 0.2762, 0.0237]], requires_grad=True)
y = torch.rand(3, 3, requires_grad=True)
y
tensor([[0.1794, 0.3274, 0.1144],
[0.5815, 0.3099, 0.3854],
[0.0383, 0.7856, 0.2387]], requires_grad=True)
z = torch.sum(x + y)
z
tensor(7.1100, grad_fn=<SumBackward0>)
# 簡單的自動求導
z.backward()
print(x.grad, y.grad)
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]) tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
# 複雜的自動求導
x = torch.rand(3, 3, requires_grad=True)
y = torch.rand(3, 3, requires_grad=True)
z = y**2 + x**3
z
tensor([[0.2509, 1.5016, 0.7266],
[0.1246, 0.9339, 0.3272],
[1.0595, 0.4782, 0.0501]], grad_fn=<AddBackward0>)
z.backward(torch.ones_like(x))
x.grad
tensor([[0.8078, 2.2859, 2.1076],
[0.4714, 2.6892, 0.8068],
[2.2977, 0.2319, 0.0336]])
使用with torch.no_grad()禁止對已設置requires_grad=True的張量進行自動求導,一般應用在計算測試集準確率時
with torch.no_grad():
print((x + y * 2).requires_grad)
False