线性回归——梯度下降法

机器学习之线性回归:算法兑现为python代码

步骤

  1. 采取线性回归模型
  2. 求出代价函数(cost),求出梯度(gradient),求偏导
  3. 设定一个学习率迭代参数
  4. 当前的代价函数与当前的代价函数的差小于阈值,计算结束

参数定义

  • model: 线性回归模型
  • cost: 代价函数
  • gradient: 梯度公式
  • theta_update: 参数更新公式
  • stop_stratege: 迭代停止策略,代价函数小于阈值法

代码参考(python3)

import numpy as np

def model(theta, X):
    return X.dot(theta)

def cost(m, theta, X, y):
    ele = y - model(theta, X)
    item = ele ** 2
    item_sum = np.sum(item)
    return item_sum / 2 / m

def gradient(m, theta, X, y, cols):
    grad_theta = []
    for j in range(cols):
        grad = (y - model(theta, X)).dot(X[:, j])
        grad_sum = np.sum(grad)
        grad_theta.append(- grad_sum / m)
    return np.array(grad_theta)

def theta_update(grad_theta, theta, sigma):
    return theta - sigma * grad_theta

def stop_stratege(cost, cost_update, threshold):
    return cost - cost_update < threshold

def OLS(X, y, threshold):
    # 样本个数
    m
    # 设置权重参数初始值
    theta = np.array()
    # 迭代步数
    iters = 0
    # 记录代价函数的值
    cost_record = []
    # 学习率
    sigma = 0.0001
    cost_val = cost(m, theta, X, y)
    while True:
        grad = gradient(m, theta, X, y)
        theta = theta_update(grad, theta, sigma)
        cost_update = cost(m, theta, X, y)
        if stop_stratege(cost_val, cost_update, threshold):
            break
        iters += 1
        cost_val = cost_update
        cost_record.append(cost_val)
    print("OLS convergence duration: %f s" % (end - start))
    return cost_record, iters, theta
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值