上一篇博文用的是手动求导,更新权重和截距,本篇博文主要是借助Pytorch自动自动求导引擎。
计算图(Computation Graph)是PyTorch的核心,其为高效自动求导算法——反向传播(Back Propogation)提供了理论支持。其中torch.autograd是一套自动求导引擎,它能够根据输入和前向传播过程自动构建计算图,并执行反向传播。
#在创建tensor的时候指定requires_grad,三种方式
#(1)
a = t.randn(3,4, requires_grad=True)
#(2)
a = t.randn(3,4).requires_grad_()
#(3)
a = t.randn(3,4)
a.requires_grad=True
#原函数
def f(x):
'''计算y'''
y = x**2 * t.exp(x)
return y
#手动求导函数
def gradf(x):
'''手动求导函数'''
dx = 2*x*t.exp(x) + x**2*t.exp(x)
return dx
x = t.randn(3,4, requires_grad = True)
y = f(x)
y
#两者的对比,效果一样
y.backward(t.ones(y.s