本文共 1688 字,大约阅读时间需要 5 分钟。
这一篇博客主要想要实现一下之前推导的简单的线性回归算法。
下面我们对上述过程进行封装:
import numpy as npclass SimpleLinearRegression1: def __init__(self): """初始化 Simple Linear Regression 模型""" self.a_ = None self.b_ = None def fit(self, x_train, y_train): """根据训练数据集 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 be equal to the size of y_train" x_mean = np.mean(x_train) y_mean = np.mean(y_train) num = 0.0 d = 0.0 for x, y in zip(x_train, y_train): num += (x - x_mean) * (y - y_mean) d += (x - x_mean) ** 2 self.a_ = num / d self.b_ = y_mean - self.a_ * x_mean return self def predict(self, x_predict): # x_predict 为一个向量 """给定预测数据集x_predict, 返回表示x_predict的结果向量""" assert x_predict.ndim == 1, \ "Simple 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): # x_single 为一个数 """给定单个预测数据x_single, 返回x_single的预测结果值""" return self.a_ * x_single + self.b_ def __repr__(self): return "SimpleLinearRegression1()"
接下来,我们就开始使用我们自己的 SimpleLinearRegression。
到此,我们就实现了一个简单的线性回归算法,不过,我在上一篇博客中曾提到过,在推导 a 和 b 的时候,我最后是将 a 进一步做了一个简化,我说经过这样的一个变化之后,我们在具体实现的时候,会有一个技巧让它更加的快一些,其实这个技巧就是使用向量化的运算方式,那么在后一篇博客中我将会介绍如何将我们现在的这个 Simple Linear Regression 的计算进行向量化,同时比较这二者之间的性能差距。
具体代码见
转载地址:http://ctoi.baihongyu.com/