六、自动微分
自动微分:求导 - 梯度缩放 - 停止计算
自动微分能够计算可导函数在某点处的导数值,是反向传播算法的一般化
自动微分主要解决的问题是将一个复杂的数学运算分解为一系列简单的基本运算,该功能对用户屏蔽了大量的求导细节和过程,大大降低了框架的使用门槛
MindSpore使用ops.GradOperation计算一阶导数,ops.GradOperation属性如下
get_all:是否对输入参数进行求导,默认值为False
get_by_list:是否对权重参数进行求导,默认值为False
sens_param:是否对网络的输出值做缩放以改变最终梯度,默认值为False
1. 对输入求一阶导
对输入求导前需要先定义公式:
下面示例代码是上述公式的表达,由于MindSpore采用函数式编程,因此所有计算公式表达都采用函数进行表示
import numpy as np
import mindspore.nn as nn
from mindspore import Parameter, Tensor
class Net(nn.Cell):
def __init__(self):
super(Net, self).__init__()
self.w = Parameter(np.array([6.0]), name='w')
self.b = Parameter(np.array([1.0]), name='b')
def construct(self, x):
f = self.w * x + self.b
return f
然后定义求导类GradNet,类的_init_函数中定义需要求导的网络,self.net和ops.GradOperation操作,类的construct函数中对self.net的输入进行求导,其对应MindSpore内部会产生公式:
from mindspore import dtype as mstype
import mindspore.ops as ops
class GradNet(nn.Cell):
def __init__(self, net):
super(GradNet, self).__init__()
self.net = net
self.grad_op = ops.GradOperation()
def construct(self, x):
gradient_function = self.grad_op(self.net)
return gradient_function(x)
最后定义权重参数为w,并对输入公式(1)中的输入参数x求一阶导数,从运行结果来看,公式(1)中的输入为6,即:
对上式进行求导,有:
x = Tensor([100], dtype=mstype.float32)
output = GradNet(Net())(x)
print(output) # [6.]
MindSpore计算一阶导数方法ops.GradOperation(get_all=False, get_by_list=False, sens_param=False),其中get_all为False时,只会对第一个输入求导,为True时,会对所有输入求导
2. 对权重求一阶导
对权重参数求一阶导,需要将ops.GradOperation中的get_by_list设置为True
from mindspore import ParameterTuple
class GradNet(nn.Cell):
def __init__(self, net):
super(GradNet, self).__init__()
self.net = net
self.params = ParameterTuple(net.trainable_params())
self.grad_op = ops.GradOperation(get_by_list=True) # 设置对权重参数进行一阶求导
def construct(self, x):
gradient_function = self.grad_op(self.