线性回归实现——梯度下降

线性回归实现

y = a x + b y = ax + b y=ax+b

x,y 是向量,a,b是标量

梯度下降法:

a = a − α ∂ c o s t ∂ a a = a - \alpha \frac{\partial cost}{\partial a} a=aαacost

c o s t = 1 2 m ∑ i = 1 m ( y i − y ‘ i ) 2 cost= \frac{1}{2m}\sum^m_{i=1}(y_i - y`_i)^2 cost=2m1i=1m(yiyi)2

cost :代价函数

实验数据:

在这里插入图片描述

实现结果:

在这里插入图片描述

算法流程:

在这里插入图片描述

代码实现:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


# 线性回归实现 梯度下降方法
# y = ax + b
# a, b 是标量
# x, y 是向量


# 模型 y = ax + b, 需要训练出 a 和 b 的值
def model(a, b, x):
    # numpy的广播特征
    # print(a, b, x)
    ret = a*x+b
    # print("ret :  ", ret)
    # ret = [a*i+b for i in x]
    # print(ret)
    return ret


# 代价|损失函数
def cost_function(a, b, x, y, n=5):
    # 1/(2n) * sum( square(yi -yi`) )
    return 0.5 / n * (np.square(y - a * x - b)).sum()


# 梯度下降方法 对a,b进行优化
def optimize(a, b, x, y, n=5):
    # a = a-alpha*(损失函数对a求偏导)
    alpha = 1e-1
    y_hat = model(a, b, x)
    da_t = y_hat - y
    da = (1.0 / n) * ((y_hat - y) * x).sum()
    db = (1.0 / n) * (y_hat - y).sum()
    a = a - alpha * da
    b = b - alpha * db
    return a, b


# 使用x, y 向量训练出 a, b两个标量
def train(x, y, cost=10000):
    # 初始化 a=b=0
    a = b = 0.0
    # 进入循环 直到到达循环结束条件
    # 循环结束条件:损失函数最小值   #这儿我是用控制循环次数来结束循环
    while True:
        # 优化方法 使用梯度下降的算法,对a,b进行优化
        a, b=optimize(a, b, x, y)
        cost = cost - 1
        if cost == 0:
            break
    return a, b


if __name__ == "__main__":
    # 数据提取 使用pandas
    # ds 的类型:<class 'pandas.core.frame.DataFrame'>
    ds = pd.read_csv("LinearRegression.csv")

    print(type(np.array(ds.iloc[:, [1]])),np.array(ds.iloc[:, [1]]))
    # 将数据变成一维
    # np.array(ds.iloc[:, [1]])
    # 将 <class 'pandas.core.frame.DataFrame'> 转换为 <class 'numpy.ndarray'>
    # narray.reshape(-1) 将 numpy.narray 的多维转换为一维
    x = np.array(ds.iloc[:, [1]]).reshape(-1)
    print(type(x), x)
    y = np.array(ds.iloc[:, [2]]).reshape(-1)
    # x = [float(i) for i in x]
    # y = [float(i) for i in y]
    # print(type(np.array(ds.iloc[:, [1]]).reshape(-1)),np.array(ds.iloc[:, [1]]).reshape(-1) )
    # print(type(x), x)
    # print(type(y), y)
    # 使用 6 张图片显示
    count = 1
    for i in range(1, 7):
        plt.subplot(3, 2, i)
        a, b = train(x, y, count)
        plt.plot(x, y, "bo")
        plt.plot(x, model(a, b, x))
        count = count * 3
    plt.show()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值