我使用下面的方程式来计算梯度误差在计算梯度使用Python
gradient = [f(x+h) - f(x-h)]/2h
和我用线性函数测试,但什么是错。 的代码是在这里:
import numpy as np
def evla_numerical_gradient(f, x):
gradient = np.zeros(x.shape, dtype=np.float64)
delta_x = 0.00001
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
index = it.multi_index
x_old = x[index]
x[index] = x_old + delta_x
fx_addh = f(x)
print(fx_addh)
x[index] = x_old - delta_x
fx_minush = f(x)
print(fx_minush)
x[index] = x_old
print((fx_addh - fx_minush)/(2 * delta_x))
gradient[index] = (fx_addh - fx_minush)/(2. * delta_x)
it.iternext()
return gradient
def lin(x):
return x
if __name__ == '__main__':
x = np.array([0.001])
grad = evla_numerical_gradient(lin, x)
print(grad)
其结果是在这里:
[ 0.00101]
[ 0.00099]
[ 0.]
[ 0.]
为什么在X坡度为0?