美文网首页
计算梯度:解析解和数值解

计算梯度:解析解和数值解

作者: 升不上三段的大鱼 | 来源:发表于2020-09-14 08:38 被阅读0次

    计算梯度有两种方法:一种是计算方便但是很慢的数值解(numerical gradient),一种是通过公式运算、较快、准确但是可能出错的解析解(analytic gradient)

    数值解有限元法、数值逼近、插值法等。数值解只能根据给定的数字求出对应的梯度。

    梯度的数值解

    解析解则是根据公式来计算的,也就是方程求解,对于任意自变量都能得到结果。对于求不出来解析解的方程,就只能算数值解了。

    举个栗子🌰
    求函数x^3+2x^2在[0,5]范围内的梯度,解析解求导的答案是3x^2+4x在[0,5]范围内的值,数值解里步长h=0.1,可以对比以下结果。稍微有点差别,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()
    
    解析解和数值解

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

    参考:
    解析解与数值解
    neural network

    相关文章

      网友评论

          本文标题:计算梯度:解析解和数值解

          本文链接:https://www.haomeiwen.com/subject/wleaektx.html