python 线性回归 梯度下降法

公式:
在这里插入图片描述

代码:

# -*- coding:utf-8 -*-


def gradient_descent(xi, yi):
    theta0, theta1 = 0, 0  # 初始化
    m = len(xi)
    alpha = 0.01  # 学习率
    max_step = 20000  # 学习次数
    count = 0
    epsilon = 0.1  # 误差临界值
    while True:
        num1, num2 = 0, 0
        for i in range(m):
            num1 += theta0 + theta1 * xi[i] - yi[i]
            num2 += (theta0 + theta1 * xi[i] - yi[i]) * xi[i]

        # update theta
        theta0 = theta0 - alpha * num1 / m
        theta1 = theta1 - alpha * num2 / m
        # print('theta0', theta0)
        # print('theta1', theta1)

        error = 0
        for i in range(m):
            error += (theta0 + theta1 * xi[i] - yi[i]) ** 2
        if error <= epsilon:
            break

        count += 1
        if count > max_step:
            break

    return theta1, theta0, error


if __name__ == '__main__':
    xi = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    yi = [10, 11.5, 12, 13, 14.5, 15.5, 16.8, 17.3, 18, 18.7]
    a, b, error = gradient_descent(xi, yi)
    print("y = %10.5fx + %10.5f" % (a, b))
    print("error: ", error)

Reference:
https://blog.csdn.net/troysps/article/details/80247320
https://blog.csdn.net/fenghuibian/article/details/52670806

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值