定义函数,存在多个局部极小值,建议在局部优化之前进行全局优化,缩小范围
def fm(p):
x, y = p
return (np.sin(x) + 0.05 * x ** 2
+ np.sin(y) + 0.05 * y ** 2)
x = np.linspace(-10, 10, 50)
y = np.linspace(-10, 10, 50)
X, Y = np.meshgrid(x, y)
Z = fm((X, Y))
fig = plt.figure(figsize=(10, 6))
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=2, cstride=2,
cmap='coolwarm', linewidth=0.5,
antialiased=True)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('f(x, y)')
fig.colorbar(surf, shrink=0.5, aspect=5)
全局优化
给定x,y的范围(-10,-5,0,5,10),最优化参数值是x=,0y=0