From c700fefad87d98d3bc4532caaa1283663d18b367 Mon Sep 17 00:00:00 2001 From: p4w2aybsf <2363061197@qq.com> Date: Thu, 29 Apr 2021 17:16:13 +0800 Subject: [PATCH] Add 'gradient.py' --- gradient.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 gradient.py diff --git a/gradient.py b/gradient.py new file mode 100644 index 0000000..fd283c6 --- /dev/null +++ b/gradient.py @@ -0,0 +1,53 @@ +# coding: utf-8 +import numpy as np + +def _numerical_gradient_1d(f, x): + h = 1e-4 # 0.0001 + grad = np.zeros_like(x) + + for idx in range(x.size): + tmp_val = x[idx] + x[idx] = float(tmp_val) + h + fxh1 = f(x) # f(x+h) + + x[idx] = tmp_val - h + fxh2 = f(x) # f(x-h) + grad[idx] = (fxh1 - fxh2) / (2*h) + + x[idx] = tmp_val # 还原值 + + return grad + + +def numerical_gradient_2d(f, X): + if X.ndim == 1: + return _numerical_gradient_1d(f, X) + else: + grad = np.zeros_like(X) + + for idx, x in enumerate(X): + grad[idx] = _numerical_gradient_1d(f, x) + + return grad + + +def numerical_gradient(f, x): + h = 1e-4 # 0.0001 + grad = np.zeros_like(x) + + # 多维迭代 + it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite']) + while not it.finished: + idx = it.multi_index + tmp_val = x[idx] + x[idx] = float(tmp_val) + h + fxh1 = f(x) # f(x+h) + + x[idx] = tmp_val - h + fxh2 = f(x) # f(x-h) + grad[idx] = (fxh1 - fxh2) / (2*h) + + x[idx] = tmp_val # 还原值 + it.iternext() + + return grad \ No newline at end of file