# -*- coding: utf-8 -*- import numpy as np import warnings warnings.filterwarnings("ignore") def gradient_descent(initial_theta,eta=0.05,n_iters=1000,epslion=1e-8): ''' 梯度下降 :param initial_theta: 参数初始值,类型为float :param eta: 学习率,类型为float :param n_iters: 训练轮数,类型为int :param epslion: 容忍误差范围,类型为float :return: 训练后得到的参数 ''' # 请在此添加实现代码 # #********** Begin *********# #********** End **********#
时间: 2025-05-20 15:19:51 浏览: 27
### 梯度下降算法的实现
以下是基于 NumPy 的梯度下降算法实现代码,其中参数 `initial_theta` 表示初始值,`eta` 是学习率,`n_iters` 是最大迭代次数,`epsilon` 是收敛条件阈值。
```python
import numpy as np
def dJ(theta):
"""计算目标函数的一阶导数"""
return 2 * (theta - 2.5)
def J(theta):
"""定义目标函数"""
return (theta - 2.5) ** 2 - 1
def gradient_descent(initial_theta, eta=0.1, n_iters=1000, epsilon=1e-8):
"""
使用梯度下降法优化目标函数
参数:
initial_theta: 初始参数值
eta: 学习率
n_iters: 最大迭代次数
epsilon: 收敛精度
返回:
theta 值的历史记录以及最终找到的最佳 theta
"""
theta = initial_theta
theta_history = [theta]
for i in range(n_iters):
gradient = dJ(theta)
last_theta = theta
theta = theta - eta * gradient
theta_history.append(theta)
if abs(J(theta) - J(last_theta)) < epsilon:
break
return theta, theta_history
# 调用函数并打印结果
initial_theta = 0.
eta = 0.1
final_theta, history = gradient_descent(initial_theta, eta=eta, n_iters=1000, epsilon=1e-8)
print(f"Final Theta Value: {final_theta}")
print(f"Iterations Taken: {len(history)}")
# 可视化历史数据
plot_x = np.linspace(-1, 6, 141)
plot_y = (plot_x - 2.5) ** 2 - 1
plt.plot(plot_x, plot_y)
plt.scatter(np.array(history), J(np.array(history)), color='red', s=10)
plt.title('Gradient Descent Path')
plt.xlabel('Theta')
plt.ylabel('Cost Function Value')
plt.show()
```
上述代码实现了梯度下降的核心逻辑,并通过可视化展示了每次更新后的参数变化路径[^3]。该方法能够自动调整参数直到满足收敛条件或者达到最大迭代次数为止。
#### 关键点说明:
- 函数 `dJ` 计算了目标函数关于变量 θ 的一阶导数。
- 函数 `J` 定义了实际的目标函数形式。
- 主体部分中的循环结构负责逐步更新 θ 并检查是否达到了指定的停止标准。
问题
阅读全文
相关推荐




