线性回归python代码实现

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签

input_x = [0.50,0.75,1.00,1.25,1.50,1.75,1.75,2.00,2.25,2.50,2.75,3.00,3.25,3.50,4.00,4.25,4.50,4.75,5.00,5.50]
input_y = [10,  26,  23,  43,  20,  22,  43,  50,  62, 50,  55,  75,  62,  78,  87,  76,  64,  85,  90,  98]
input_x = np.array(input_x, dtype=float)
input_y = np.array(input_y, dtype=float)

a = 0
b = 0

class linear_regression:
    '''线性回归类'''

    def __init__(self, a_init, b_init, x, y):
        self.a = a_init     #初始化参数a
        self.b = b_init     #初始化参数b
        self.x = x          #数据x
        self.y = y          #标签y
        # self.epochs = int(epochs)       #迭代的轮数
        self.shape = self.x.shape[0]    #数据的个数

    def model(self):
        '''计算预测值'''
        return self.a*self.x + self.b

    def cost_function(self):
        '''损失函数'''
        return 0.5/self.shape * (np.square(self.y-self.a*self.x-self.b)).sum()

    def optimize(self):
        '''梯度下降更新参数a和b'''
        alpha = 1e-1
        y_hat = self.model()

        da = (1.0/self.shape) * ((y_hat-self.y)*self.x).sum()  #a的梯度
        db = (1.0/self.shape) * (y_hat-self.y).sum()         #b的梯度

        self.a = self.a - alpha*da      #梯度下降
        self.b = self.b - alpha*db      #梯度下降

        return self.a, self.b

    def iterate(self):
        '''迭代更新'''
        i = 0
        loss_list=[]
        while(True):
            self.a, self.b = self.optimize()
            print("a:",self.a, " b:",self.b)
            print("loss:",self.cost_function())
            loss_list.append(self.cost_function())

            if i>=1 and np.abs(loss_list[i]-loss_list[i-1]) < 1e-8:
                break
            i = i+1

        y_hat = self.model()
        loss = self.cost_function()
        plt.scatter(self.x,self.y,color='red')
        plt.plot(self.x, y_hat,color="blue")
        plt.xlabel('x')
        plt.ylabel('y')
        plt.show()


if __name__ == '__main__':
    # print("请输入迭代轮数:")
    # epochs = input()

    result = linear_regression(a, b, input_x, input_y)
    result.iterate()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫咪钓鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值