动量梯度下降算法迭代绘图代码
时间: 2023-09-21 08:10:58 浏览: 59
以下是使用动量梯度下降算法迭代绘制函数图像的 Python 代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义目标函数
def target_function(x):
return x ** 2 + 10 * np.sin(x)
# 定义目标函数的一阶导数
def first_derivative(x):
return 2 * x + 10 * np.cos(x)
# 定义动量梯度下降算法
def momentum_gradient_descent(x_start, learning_rate, momentum, epoch):
x = x_start
v = 0
x_history = [x]
for i in range(epoch):
v = momentum * v - learning_rate * first_derivative(x)
x += v
x_history.append(x)
return x_history
# 设定参数
x_start = -5
learning_rate = 0.1
momentum = 0.9
epoch = 50
# 运行动量梯度下降算法
x_history = momentum_gradient_descent(x_start, learning_rate, momentum, epoch)
# 绘制函数图像
x = np.arange(-5.0, 5.0, 0.1)
y = target_function(x)
plt.plot(x, y)
plt.plot(x_history, target_function(np.array(x_history)), 'r')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
```
在代码中,我们首先定义了目标函数及其一阶导数,然后定义了动量梯度下降算法。接着,我们设定了参数并运行了算法,得到了每次迭代后的 $x$ 值,并将其绘制在函数图像上。最后,我们使用 `plt.show()` 显示绘制的图像。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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_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)