随机梯度下降法优化beale函数代码
时间: 2024-05-15 20:12:18 浏览: 16
以下是使用随机梯度下降法优化Beale函数的Python代码:
```python
import numpy as np
def beale(x):
"""
Beale函数:f(x, y) = (1.5 - x + x*y)**2 + (2.25 - x + x*y**2)**2 + (2.625 - x + x*y**3)**2
"""
return (1.5 - x[0] + x[0]*x[1])**2 + (2.25 - x[0] + x[0]*x[1]**2)**2 + (2.625 - x[0] + x[0]*x[1]**3)**2
def beale_gradient(x):
"""
Beale函数的梯度向量
"""
grad = np.zeros_like(x)
grad[0] = 2*(x[0]*x[1] - x[0] + 1.5)*(x[1]**3) + 2*(x[0]*x[1]**2 - x[0] + 2.25)*(x[1]**2) + 2*(x[0]*x[1]**3 - x[0] + 2.625)*x[1]
grad[1] = 2*(x[0]*x[1] - x[0] + 1.5)*(x[0]) + 2*(x[0]*x[1]**2 - x[0] + 2.25)*(2*x[0]*x[1]) + 2*(x[0]*x[1]**3 - x[0] + 2.625)*(3*x[0]*x[1]**2)
return grad
def sgd_beale(x0, learning_rate=0.001, max_iter=10000, tol=1e-6):
"""
使用随机梯度下降法优化Beale函数
"""
x = x0.copy()
for i in range(max_iter):
# 随机选择一个方向
direction = np.random.randn(2)
# 计算梯度
grad = beale_gradient(x)
# 更新参数
x -= learning_rate * grad * direction
# 检查收敛性
if np.linalg.norm(grad) < tol:
print("SGD converged in {} iterations.".format(i+1))
break
return x
# 测试
np.random.seed(0)
x0 = np.array([1.0, 1.0])
x_opt = sgd_beale(x0)
print("Optimized solution: x = {:.6f}, y = {:.6f}, f(x, y) = {:.6f}".format(x_opt[0], x_opt[1], beale(x_opt)))
```
在上面的代码中,我们定义了Beale函数及其梯度向量,然后使用随机梯度下降法优化这个函数。在每次迭代中,我们随机选择一个方向(即随机生成一个二维向量),计算梯度,并更新参数。我们使用欧几里得范数来检查梯度是否已经足够小,如果是,则认为算法已经收敛。最后,我们输出优化后的解及其函数值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![](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)