梯度下降法--python实现

梯度下降是迭代法的一种,可以用于求解最小二乘问题,不是一个机器学习算法,而是一种基于搜索的最优化方法。在求解无约束优化问题时,梯度下降法是最常用的一种方法之一,最小二乘法也是一种。

在这里插入图片描述

在直线方程中,导数代表斜率。在曲线方程中,导数代表切线斜率。切线斜率∇wJ的正负,也代表函数增大的方向。设-η∇wJ,η称为学习率,影响获得最优解的速度,当取值不适当时,得不到相应的值。它是一个超参数。
η太小时,降低收敛的速度,η太大时,可能导致不收敛。

def J(theta):
    return (theta-2.5)**2 -1

def dJ(theta):
    return 2*(theta-2.5)

theta_history = []

def grandient_descent(inital_theta,eta,esplison):
    
    theta = inital_theta
    theta_history.append(inital_theta)
   
    while True:
        last_theta = theta
        theta = theta - eta*dJ(theta)
        theta_history.append(theta)
        if abs(J(theta)-J(last_theta)) < 0.0008:
            break
            
def plot_theta_history():
    plt.plot(plot_x,J(plot_x))
    plt.plot(np.array(theta_history),J(np.array(theta_history)),color="r",marker="+")
    plt.show()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值