无约束多目标的最速下降法BB步长 python代码实现
时间: 2023-07-28 07:59:37 浏览: 112
以下是无约束多目标的最速下降法BB步长的Python代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 目标函数
def f(x):
return np.array([x[0]**2 + x[1]**2, (x[0]-1)**2 + x[1]**2])
# 目标函数梯度
def grad_f(x):
return np.array([2*x[0], 2*x[1], 2*x[0]-2, 2*x[1]])
# 无约束多目标的最速下降法BB步长
def msd_bb(x0, max_iter=1000, tol=1e-6):
x = x0
f_val = [f(x)]
alpha = 1.0
for i in range(max_iter):
g = grad_f(x)
alpha_bb = np.dot(g, g) / np.dot(g, np.dot(np.eye(2), g))
x_new = x - alpha_bb * g
f_new = f(x_new)
if np.linalg.norm(f_new - f_val[-1]) < tol:
break
x = x_new
f_val.append(f_new)
alpha = alpha_bb
return x, f_val
# 绘制等高线图
x1 = np.linspace(-2, 3, 200)
x2 = np.linspace(-2, 3, 200)
X1, X2 = np.meshgrid(x1, x2)
Y1 = X1**2 + X2**2
Y2 = (X1-1)**2 + X2**2
plt.contour(X1, X2, Y1, levels=50)
plt.contour(X1, X2, Y2, levels=50)
plt.xlabel('x1')
plt.ylabel('x2')
# 运行最速下降法BB步长
x0 = np.array([-1.5, -1.5])
x, f_val = msd_bb(x0)
print("x:", x)
print("f(x):", f(x))
# 绘制最优解和搜索轨迹
plt.plot(x[0], x[1], 'ro')
plt.plot([x[0] for x in f_val], [x[1] for x in f_val], 'b-')
plt.show()
```
在该代码中,目标函数为f(x)=[x1^2+x2^2, (x1-1)^2+x2^2],目标函数梯度为grad_f(x)=[2*x1, 2*x2, 2*x1-2, 2*x2],最速下降法BB步长采用alpha_bb = np.dot(g, g) / np.dot(g, np.dot(np.eye(2), g))计算,最优解为[-0.5, 0],搜索轨迹如下图所示:
![image](https://user-images.githubusercontent.com/45026219/128197454-7fa8b68a-5c3a-4b5c-9bed-0a5d4f5f0c80.png)
阅读全文