- 不是一个机器学习算法
- 是一种基于搜索的最优化方法
- 作用:最小化一个损失函数
- 梯度上升法:最大化一个效用函数
dJ/d(theta)
导数代表theta单位变化时,J相应的变化
导数可以代表方向,对应J增大的方向
太小,减慢收敛学习的速度
太大,甚至会导致不收敛
- 梯度下降可能遇到的问题:并不是所有函数都有唯一的极值点
- 解决方法:多次运行
线性回归法的损失函数具有唯一的最优解
模拟实现梯度下降法
In [1]: import numpy as np
In [2]: import matplotlib.pyplot as plt
In [3]: plot_x = np.linspace(-1,6,141)
#假设下列式子是损失函数
In [4]: plot_y = (plot_x-2.5)**2-1
#返回theta这点的导数
In [7]: def dJ(theta):
...: return 2*(plot_x-2.5)
#返回theta这点的损失函数的值
In [8]: def J(theta):
...: return (theta-2.5)**2-1
#梯度下降的过程
In [10]: theta = 0.0
...: eta = 0.1
...: epsilon = 1e-8
...: theta_history = []
...: while True:
...: gradient = dJ(theta)
...: last_theta = theta
...: theta = theta - eta * gradient
...: theta_history.append(theta)
...: if(abs(J(theta) - J(last_theta)) < epsilon):
...: break
#绘制损失函数和梯度下降的过程
In [14]: plt.plot(plot_x,plot_y)
...: plt.plot(np.array(theta_history),J(np.array(theta_history)),color='r',marker='+')
线性回归中的梯度下降法
损失函数 J =
梯度下降中的导数实际是损失函数对每个theta求偏导得到的:
为了使梯度下降的过程与m无关,实际目标公式如下:
在线性回归模型中使用梯度下降法