简单线性回归 Python实现

简单线性回归中,数据只有一个特征。

import numpy as np

class SimpleLinearRegression:
  def __init__(self):
    '''初始化模型'''
    self.a_ = None
    self.b_ = None

  def fit(self,x_train,y_train):
    '''根据训练数据集训练模型'''
    assert x_train.ndim == 1,'Simple Linear Regression can only solve single feature training data'
    assert len(x_train) == len(y_train),'the size of x_train must equal to the size of y_train'

    x_mean = np.mean(x_train)
    y_mean = np.mean(y_train)
 
    num = (x_train - x_mean).dot(y_train - y_mean)
    d = (x_train - x_mean).dot(x_train - x_mean)
    self.a_ = num / d
    self.b_ = y_mean - self.a_ * x_mean

    return self

  def predict(self,x_predict):
    '''给定待预测数据集,返回预测结果向量'''
    assert x_predict.ndim == 1,'Simlpe Linear Regression can only solve single feature training data'
    assert self.a_ is not None and self.b_ is not None,'must fit before predict'
    
    return np.array([self._predict(x) for x in x_predict])

  def _predict(self,x_single):
    '''对单个待预测数据进行预测并返回结果'''
    return  self.a_ * x_single + self.b_

  def __repr__(self):
    return 'SimpleLinearRegression()'
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值