引自免费微信小程序:皆我百晓生
为了实现坐标下降法最小化给定的二次函数,并绘制相应的等值线图,我们可以分为以下几个步骤:
- 定义二次函数。
- 实现坐标下降算法。
- 初始化参数和设置等值线间隔。
- 迭代计算并记录结果。
- 绘制等值线图。
首先,定义二次函数 f(x, y):
import numpy as np
def f(x, y):
return 7 * x**2 + 6 * x * y + 8 * y**2
接下来,实现坐标下降算法。这里我们使用两种不同的步长 a=1 和 a=0.1:
def coordinate_descent(f, initial_point, step_size, max_iterations):
x, y = initial_point
history = [(x, y)]
for _ in range(max_iterations):
gradient_x = 2 * (7 * x + 3 * y)
gradient_y = 2 * (6 * x + 8 * y)
x -= step_size * gradient_x
y -= step_size * gradient_y
history.append((x, y))
return history
现在初始化参数和设置等值线间隔:
initial_point = (8, -6)
step_sizes = [1, 0.1]
max_iterations = 100
contour_interval = 25 # 等值线之间的间隔
然后对每种步长进行迭代计算并记录结果:
histories = []
for step_size in step_sizes:
histories.append(coordinate_descent(f, initial_point, step_size, max_iterations))
最后,我们将使用matplotlib库绘制等值线图。首先,我们需要创建一个网格来计算整个区域内的函数值,然后将这些值转换为等值线:
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
# 创建一个网格
x_min, x_max = -10, 10
y_min, y_max = -10, 10
x_grid, y_grid = np.meshgrid(np.linspace(x_min, x_max, 100),
np.linspace(y_min, y_max, 100))
# 计算网格上的函数值
z_grid = f(x_grid, y_grid)
# 设置等值线图
fig, ax = plt.subplots(1, 2, figsize=(12, 6))
# 设置等值线间隔
levels = np.arange(min(z_grid.min(), 0), z_grid.max(), contour_interval)
# 绘制等值线
ax[0].contour(x_grid, y_grid, z_grid, levels=levels, cmap=cm.Blues)
ax[0].scatter(*zip(*histories[0]), color='red', marker='o', label=f'step_size={step_sizes[0]}')
ax[0].set_title(f'Coordinate Descent with step_size={step_sizes[0]}')
ax[1].contour(x_grid, y_grid, z_grid, levels=levels, cmap=cm.Blues)
ax[1].scatter(*zip(*histories[1]), color='red', marker='o', label=f'step_size={step_sizes[1]}')
ax[1].set_title(f'Coordinate Descent with step_size={step_sizes[1]}')
# 添加等值线标签
for axi in ax:
axi.set_xlabel('X')
axi.set_ylabel('Y')
axi.set_xlim(x_min, x_max)
axi.set_ylim(y_min, y_max)
axi.xaxis.set_major_locator(LinearLocator())
axi.yaxis.set_major_locator(LinearLocator())
# 显示图像
plt.legend()
plt.show()
这段代码将会生成两个等值线图,分别对应于步长 a=1 和 a=0.1 的坐标下降过程。每个图上都会显示迭代路径,红色圆点表示每次迭代的位置。等值线的颜色深浅代表函数值的高低。
