一、自动求导机制
torch框架可以自动进行求导,这在搭建网络过程中提供了很大的便利。需要求导的话就在创建tensor时,将求导参数设置为True
import torch
import numpy as np
x = torch.randn(5, 5, requires_grad=True)
这个参数默认为False,因此需要求导时,就将其设置为True。
利用这个机制进行求导:
import torch
import numpy as np
x = torch.randn(5, 5, requires_grad=True)
w = torch.randn(5, 5, requires_grad=True)
c = x*w
a = c.sum()
a.backward()
print(x.grad, w.grad)
上面的流程其实就是神经网络常见的 表达式:
F = w ∗ x + b F = w*x + b F=w∗x+b
在这里b = 0。根据链式求导法则容易得到,对于上述式子,x的梯度就是w, 同样的w的梯度就是x。
在反向梯度传播时,torch会保留上一次运算得到的梯度,并且将梯度进行一次累加操作:
import torch
import numpy