NumPy 函数梯度计算 实例
import numpy as np
def my_function(x_value, y_value):
"""定义函数z=x**2+y"""
return x_value**2 + y_value
def cal_gradient(x):
"""计算函数的偏导"""
h = 1e-4 # 0.0001作为增值
f_gradient = np.zeros_like(x, dtype='float32') # 保存梯度值
x_values = x[:, 0] # 函数的x值
y_values = x[:, 1] # 函数的y值
for i in range(len(x[:, 0])):
f_values = my_function(x_values[i], y_values[i])
f_values_h1 = my_function(x_values[i]+h, y_values[i])
f_gradient_x = (f_values_h1 - f_values) / h
f_gradient[:, 0][i] = f_gradient_x
f_values_h2 = my_function(x_values[i], y_values[i]+h)
f_gradient_y = (f_values_h2 - f_values) / h
f_gradient[:, 1][i] = f_gradient_y
return f_gradient
if __name__ == '__main__':
x = np.array([[1, 2], [2, 3], [3, 4], [4, 5]])
print(cal_gradient(x))
运行结果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c8f7ad8cb4fc9ff153e0b5ba7ad7a84a.png)