"""用双井函数观察梯度下降的局部最优。运行:python mmf_nonlinear.py。""" import json # NumPy 求驻点并对数组求值;Matplotlib 同时显示目标剖面与每步目标值。 import matplotlib.pyplot as plt import numpy as np def main(): # tilt 让左谷更深;rate 控制每步走多远。只比较初值时两组都用同一组参数。 tilt = 0.2 rate = 0.05 iterations = 80 def objective(x): return (x**2 - 1)**2 + tilt * x # 手算导数 4x(x^2-1)+tilt。梯度下降取负导数方向。 def gradient(x): return 4 * x * (x**2 - 1) + tilt # 两个分量各代表一次独立运行,同时保留每一步的位置。 # 多留一行容纳第 0 步;列 0 是左起点,列 1 是右起点。 path = np.zeros((iterations + 1, 2)) path[0] = [-1.6, 1.6] for iteration in range(iterations): current = path[iteration] path[iteration + 1] = current - rate * gradient(current) end = path[-1] # 四次项主导远端行为。比较所有实驻点即可为本例确定全局最优值。 # 按降幂写出导数多项式的系数,二次项缺失也需要显式填 0。 roots = np.roots([4, 0, -4, tilt]) # 近零虚部视为求根舍入误差;目标定义在实数域,其他根不参与比较。 critical = np.sort(roots.real[np.abs(roots.imag) < 1e-10]) global_x = critical[np.argmin(objective(critical))] # 终点梯度是局部驻点检查;对比全部实驻点的目标值可核对本题的全局最小值。 result = { "end_x": end.tolist(), "end_f": objective(end).tolist(), "end_gradient": np.abs(gradient(end)).tolist(), "critical_x": critical.tolist(), "global_x": float(global_x), "global_f": float(objective(global_x)), } print("LAB_RESULT " + json.dumps(result)) # 上图的散点显示更新跨过的水平距离,下图显示损失下降何时停滞。 grid = np.linspace(-1.7, 1.7, 400) fig, (landscape, trace) = plt.subplots(2, 1) landscape.plot(grid, objective(grid), color="0.4", label="Objective") for run, label in enumerate(("Start at -1.6", "Start at +1.6")): landscape.plot(path[:12, run], objective(path[:12, run]), "o-", ms=3, label=label) trace.plot(objective(path[:, run]), label=label) landscape.scatter(critical, objective(critical), marker="x", color="black", label="Stationary") landscape.set(xlabel="x", ylabel="f(x)", title="Nonconvex objective and early iterates") # 前 20 步足以看清变化;输出仍使用迭代 80 步后的终点。 trace.set(xlabel="Iteration", ylabel="f(x)", xlim=(0, 20)) landscape.legend(fontsize=8) trace.legend(fontsize=8) fig.tight_layout() if plt.get_backend().lower() == "agg": fig.canvas.draw() else: plt.show() if __name__ == "__main__": main()