梯度下降法求解方程图像
时间: 2025-05-31 21:07:33 浏览: 25
### 使用梯度下降法求解方程并生成图像
#### 方法概述
梯度下降是一种优化算法,用于寻找目标函数的最小值。通过不断调整参数的方向来减少误差,最终收敛到最优解或局部最优解。以下是使用 Python 和 NumPy 实现梯度下降法求解方程 \( y = (x - 2)^2 \) 的极值点,并绘制其变化过程。
---
#### 示例代码实现
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义原函数及其导数
def function(x):
"""定义目标函数"""
return (x - 2)**2 # 函数表达式 y = (x - 2)^2
def derivative(x):
"""定义目标函数的一阶导数"""
return 2 * (x - 2) # 导数 dy/dx = 2*(x-2)
# 初始化参数
initial_x = 16 # 初始猜测值 x0
learning_rate = 0.1 # 学习率 α
threshold = 1e-5 # 收敛条件(阈值)
max_iterations = 1000 # 最大迭代次数以防无限循环
# 记录每次迭代的结果
x_values, y_values = [], []
current_x = initial_x
iteration_count = 0
while True:
current_y = function(current_x)
# 将当前 x 和对应的 y 添加到列表中以便后续绘图
x_values.append(current_x)
y_values.append(current_y)
iteration_count += 1
# 更新 x 值
next_x = current_x - learning_rate * derivative(current_x)
# 如果两次连续更新之间的差异小于阈值,则认为已收敛
if abs(next_x - current_x) < threshold or iteration_count >= max_iterations:
break
current_x = next_x
print(f'迭代次数: {iteration_count}')
print(f'找到的极值点为 ({current_x}, {function(current_x)})')
# 绘制函数曲线以及梯度下降路径
plt.figure(figsize=(8, 6))
x_range = np.linspace(-5, 20, 400) # 设置 x 轴范围
y_range = function(x_range) # 对应的目标函数值
plt.plot(x_range, y_range, label='Function $y = (x - 2)^2$', color='blue')
plt.scatter(x_values, y_values, c=np.arange(len(x_values)), cmap='viridis', edgecolor='black', s=100, label='Gradient Descent Path')
plt.title('Gradient Descent Optimization Process', fontsize=16)
plt.xlabel('$x$ Value', fontsize=14)
plt.ylabel('$y$ Value', fontsize=14)
plt.legend(fontsize=12)
plt.grid(True)
plt.show()
```
---
#### 代码解释
1. **目标函数与导数**
- `function` 是原始目标函数 \( y = (x - 2)^2 \)[^3]。
- `derivative` 是该函数的一阶导数 \( \frac{dy}{dx} = 2(x - 2) \),表示斜率方向[^3]。
2. **初始化参数**
- `initial_x`: 设定初始猜测值 \( x_0 \)。
- `learning_rate`: 控制每一步移动的距离大小。
- `threshold`: 当相邻两步间的差距小于此值时,视为已经接近极值点。
- `max_iterations`: 防止程序陷入死循环的最大允许迭代次数。
3. **核心逻辑**
- 每次迭代根据公式 \( x_{n+1} = x_n - \alpha \cdot f'(x_n) \) 更新 \( x \) 值。
- 迭代终止条件:满足精度要求或者达到最大迭代次数。
4. **可视化部分**
- 使用 Matplotlib 库绘制目标函数曲线和梯度下降过程中经过的点。
- 散点颜色随迭代次数渐变,直观展示优化轨迹。
---
#### 输出结果说明
运行上述代码后会打印出:
- 总共进行了多少次迭代;
- 找到了哪个位置作为近似极值点及其对应的目标函数值。
同时还会显示一张图表,其中蓝色线条代表目标函数形状,彩色散点则展示了梯度下降逐步逼近的过程。
---
阅读全文
相关推荐



















