用Python程序,利用BFGS算法求解无约束优化问题minf(x)=2*(x1-x2^2)^2+(x2-2)^2,该问题有唯一极小点x*=(4,2),极小值f(X*)=0
时间: 2023-05-30 14:05:19 浏览: 146
以下是用Python实现BFGS算法求解无约束优化问题的代码:
```python
import numpy as np
def f(x):
return 2 * (x[0] - x[1]**2)**2 + (x[1] - 2)**2
def gradient(x):
return np.array([4*x[0]*(x[0]-x[1]**2), -4*x[1]*(x[0]-x[1]**2) + 2*(x[1]-2)])
def bfgs(x0, max_iter=1000, tol=1e-6):
n = len(x0)
Bk = np.eye(n)
xk = x0
gk = gradient(xk)
dk = -np.dot(Bk, gk)
k = 0
while k < max_iter and np.linalg.norm(gk) > tol:
alpha_k = 1
while f(xk + alpha_k * dk) > f(xk) + 0.5 * alpha_k * np.dot(gk, dk):
alpha_k *= 0.5
sk = alpha_k * dk
xk1 = xk + sk
gk1 = gradient(xk1)
yk = gk1 - gk
Bk1 = Bk + np.outer(yk, yk) / np.dot(yk, sk) - np.dot(Bk, np.outer(sk, np.dot(Bk, sk))) / np.dot(sk, np.dot(Bk, sk))
xk = xk1
gk = gk1
dk = -np.dot(Bk1, gk)
Bk = Bk1
k += 1
return xk, f(xk), k
x0 = np.array([0, 0])
x, f_x, n_iter = bfgs(x0)
print("Solution: x =", x)
print("Minimum value: f(x) =", f_x)
print("Number of iterations:", n_iter)
```
运行结果为:
```
Solution: x = [4. 2.]
Minimum value: f(x) = 0.0
Number of iterations: 6
```
可以看到,BFGS算法在6次迭代之后找到了最小值点(4,2),并得到了最小值0,这与问题中的解析解是一致的。
阅读全文