计算梯度的三种方法: 数值法,解析法,反向传播法
Python:
# coding=gbk
"""
function : f(x,y,z) = (x+y)z
"""
# first method 解析法
def grad1(x,y,z):
dx = z
dy = z
dz = (x+y)
return (dx,dy,dz)
# second method 数值法
def grad2(x,y,z,epi):
# dx
fx1 = (x+epi+y)*z
fx2 = (x-epi+y)*z
dx = (fx1-fx2)/(2*epi)
# dy
fy1 = (x+y+epi)*z
fy2 = (x+y-epi)*z
dy = (fy1-fy2)/(2*epi)
# dz
fz1 = (x+y)*(z+epi)
fz2 = (x+y)*(z-epi)
dz = (fz1-fz2)/(2*epi)
return (dx,dy,dz)
# third method 反向传播法
def grad3(x,y,z):
# forward
p = x+y;
f = p*z;
# backward
dp = z
dz = p
dx = 1 * dp
dy = 1 * dp
return (dx,dy,dz)
print (": %.2f %.2f %.2f" %(grad1(1,2,3)))
print (": %.2f %.2f %.2f" %(grad2(1,2,3,1e-5)))
print (": %.2f %.2f %.2f" %(grad3(1,2,3)))
结果:
<df/dx,df/dy,df/dz>: 3.00 3.00 3.00
<df/dx,df/dy,df/dz>: 3.00 3.00 3.00
<df/dx,df/dy,df/dz>: 3.00 3.00 3.00
以Sigmoid 为例:
上面的Sigmoid 函数是输入二维的情况。 x=[x0x1]T
, w=[w0,w1]T , w2=b
显然函数是一个复合函数,是简单函数: f(x)=1x,f(x)=ex,f(x)=ax,f(x)=c+x 复合而成。
因此,我们可以写成: 波兰表达式树的形式。
这里我们只关心关于 w 的梯度,我们将函数写为:
Matlab:
clc;
%% 下面向量书写的格式不采用统一规范形式。例如全部采用列向量的形式等。
w = [2,-3,-3];
x = [-1,-2];
% 一般形式的反向传播
[dw0,dw1,dw2] = grad1(w(1),w(2),w(3),x(1),x(2));
fprintf('%.8f,%.8f,%.8f \n',dw0,dw1,dw2);
% 数值法
[dw0,dw1,dw2] = grad2(w(1),w(2),w(3),x(1),x(2),1e-5);
fprintf('%.8f,%.8f,%.8f \n',dw0,dw1,dw2);
% 技巧形式的反向传播
dw = grad3(w,x);
fprintf('%.8f,%.8f,%.8f \n',dw(1),dw(2),dw(3));
% 解析法
dw = grad4(w,x);
fprintf('%.8f,%.8f,%.8f \n',dw(1),dw(2),dw(3));
% 一般形式的反向传播
function [dw0,dw1,dw2] = grad1(w0,w1,w2,x0,x1)
% forward
p0 = -1*(w0*x0+w1*x1+w2);
p1 = exp(p0);
p2 = 1+p1;
p3 = 1/p2;
% backward
dp2 = (-1)*(p2^(-2));
dp1 = 1*dp2;
dp0 = dp1*exp(p0);
dw0 = dp0*(-x0);
dw1 = dp0*(-x1);
dw2 = dp0 *(-1);
end
% 数值法
function [dw0,dw1,dw2] = grad2(w0,w1,w2,x0,x1,epi)
% dw0
f1w0 = 1.0/(1+exp(-1*((w0+epi)*x0+w1*x1+w2)));
f2w0 = 1.0/(1+exp(-1*((w0-epi)*x0+w1*x1+w2)));
dw0 = (f1w0 - f2w0)/(2*epi);
% dw1
f1w1 = 1.0/(1+exp(-1*(w0*x0+(w1+epi)*x1+w2)));
f2w1 = 1.0/(1+exp(-1*(w0*x0+(w1-epi)*x1+w2)));
dw1 = (f1w1 - f2w1)/(2*epi);
% dw2
f1w2 = 1.0/(1+exp(-1*(w0*x0+w1*x1+(w2+epi))));
f2w2 = 1.0/(1+exp(-1*(w0*x0+w1*x1+(w2-epi))));
dw2 = (f1w2 - f2w2)/(2*epi);
end
% 技巧形式的反向传播
% 利用sigmoid 函数的技巧: sigma(x)' = (1-sigma(x))*sigma(x)
function dw = grad3(w,x)
% forward
dot = w(1)*x(1) + w(2)*x(2) + w(3);
f = 1.0/(1+exp(-dot));
% backward
ddot = (1-f)*f;
dx = [w(1)*ddot,w(2)*ddot]; % 不输出
dw = [x(1)*ddot,x(2)*ddot,1.0*ddot];
end
% 解析法
% f(w)' = 1/(1+e^()) * e^() * (-x0)
function dw = grad4(w,x)
x = [x 1];
dw = (-1)*(1+exp(- w*x'))^(-2)*exp(- w*x').*(-x);
end
结果:
-0.19661193,-0.39322387,0.19661193
-0.19661193,-0.39322387,0.19661193
-0.19661193,-0.39322387,0.19661193
-0.19661193,-0.39322387,0.19661193
如下函数:
上述公式写出解析形式的表达式,似乎吃力。
略… 请参考[参考文献].
参考文献: