梯度下降法(Gradient Descent)
它不是一个机器学习算法,是一种基于搜索的最优化的方法,既不能解决分类问题也不能解决回归问题,他的作用是,最小化一个损失函数,梯度上升法:最大化一个效用函数。
- 1.求损失函数的导数 def DJ(theta)
- 2.确定theta对应的损失函数 def J(theta)
- 3.梯度下降算法 求每一次减小后的theta的对应的y值和减小之前的 theta对应的y值得差距是不是小于我们设定的最小 限度,如果是我们就默认找到了最小值。
import numpy as np
import matplotlib.pyplot as plt
def dJ(x):
return 2*(x-2.5)
def J(x):
return (x-2.5)**2-1
def gradient_descent(theta,theta_h,iter,eta,epsilon=1e-8):
x_theta=theta
theta_h.append(theta)
n_iter=0
while n_iter<iter:
last_theta=x_theta
gradient=dJ(x_theta)
x_theta=x_theta-gradient*eta
theta_h.append(x_theta)
if abs(J(x_theta)-J(last_theta))<epsilon:
break
n_iter+=1
def plot_theta_hostory(x,theta_his):
plt.plot(x,J(x),c='r')
plt.plot(np.array(theta_his),J(np.array(theta_his)),'b*')
plt.show()
x=np.linspace(-1,6,141)
theta_h=[];
iter=50
eta=0.1
gradient_descent(0.0,theta_h,iter,eta)
plot_theta_hostory(x,theta_h)
在上面的代码中,有一个参数eta称为学习率,简单来说可以理解为每一次下降的步长。
eta称为学习率
eta的取值影响获得最优解的速度
eta的取值不合适,甚至得不到最优解
eta是梯度下降法的一个超参数
eta太小,会降低学习速度
eta太大,甚至导致不收敛
并不是所有函数都有唯一值的极值点,那怎么解决?
解决方案,多次运行 ,随机化初始点
梯度下降法的初始点也是一个超参数
线性回归法的损失函数具有唯一的最优解