下面的代碼會依次x的每個維度根據(jù)定義進行計算玷禽。
ix :(0,0,0...) (0,0,0...1)....
下面的代碼寫法可以兼容x為任意維數(shù)的情況收恢。
# 參數(shù)df表示 cost函數(shù)對df求導
def eval_numerical_gradient_array(f, x, df, h=1e-5):
"""
Evaluate a numeric gradient for a function that accepts a numpy
array and returns a numpy array.
"""
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
ix = it.multi_index
oldval = x[ix]
x[ix] = oldval + h
pos = f(x).copy()
x[ix] = oldval - h
neg = f(x).copy()
x[ix] = oldval
grad[ix] = np.sum((pos - neg) * df) / (2 * h)
it.iternext()
return grad