计算梯度有两种方法:一种是计算方便但是很慢的数值解(numerical gradient),一种是通过公式运算、较快、准确但是可能出错的解析解(analytic gradient)。
数值解有限元法、数值逼近、插值法等。数值解只能根据给定的数字求出对应的梯度。

解析解则是根据公式来计算的,也就是方程求解,对于任意自变量都能得到结果。对于求不出来解析解的方程,就只能算数值解了。
举个栗子🌰
求函数在[0,5]范围内的梯度,解析解求导的答案是
在[0,5]范围内的值,数值解里步长
,可以对比以下结果。稍微有点差别,0.1作为步长有点大。
def analytic_gradient():
x= np.linspace(0,5,500)
y = 3*np.square(x)+4*x
plt.plot(x,y,label='a')
def numerical_gradient(f, x):
h = 0.1
input = []
gradient = []
while x< 5:
xh = x + h
fxh = f(xh)
fx = f(x)
grad = (fxh-fx)/h
x = xh
input.append(xh)
gradient.append(grad)
plt.plot(input,gradient,'--',label='n')
def foo(x):
return x*x*x + 2*x*x
plt.figure()
numerical_gradient(foo,0)
analytic_gradient()
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('numerical vs. analytic')
plt.show()

在神经网络里计算的应该是解析解,因为每一层基本上都是可微的。
网友评论