python 实现最速下降法
时间: 2024-01-01 15:50:05 浏览: 57
最速下降法是一种求解无约束优化问题的基本方法,它是一种迭代算法,每一步迭代都沿着当前位置的梯度方向进行。下面是使用 Python 实现最速下降法的示例代码:
```python
import numpy as np
# 定义目标函数f和它的梯度g
def f(x):
return x[0]**2 + x[1]**2
def g(x):
return np.array([2*x[0], 2*x[1]])
# 最速下降法迭代函数
def steepest_descent(f, g, x0, alpha=0.1, eps=1e-6, max_iter=1000):
x = x0
i = 0
while i < max_iter:
grad = g(x)
if np.linalg.norm(grad) < eps:
break
x = x - alpha * grad
i += 1
return x, f(x), i
# 测试
x0 = np.array([1.0, 1.0])
x, fx, i = steepest_descent(f, g, x0)
print("最优解:", x)
print("最优值:", fx)
print("迭代次数:", i)
```
在上述代码中,`f` 和 `g` 分别是目标函数和它的梯度,`steepest_descent` 函数是最速下降法的主函数,其中 `alpha` 是步长,`eps` 是精度要求,`max_iter` 是最大迭代次数。最后通过调用 `steepest_descent` 函数并传入初始点 `x0` 来求解最优解和最优值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)