import numpy as npclassSimpleLinearRegression2:def__init__(self):"""初始化Single Linear Regression模型""" self.a_ =None self.b_ =Nonedeffit(self,x_train,y_train):"""根据训练数据集X_train, y_train训练Single Linear Regression模型"""assert x_train.ndim ==1,"Simple Linear Regressor can only solve single feature training data"assertlen(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 = (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_meandefpredict(self,x_predict):"""给定待测数据集X_predict,返回表示x_predict的结果向量"""assert x_predict.ndim ==1,"Simple Linear Regressor can only solve single feature training data"assert self.a_ isnotNoneand self.b_ isnotNone,"must fit before predict"return [self._predict(x)for x in x_predict]def_predict(self,x_single):"""给定单个待预测数据s_single,返回x_single的预测结果"""return self.a_ * x_single + self.b_def__repr__(self):return"SimpleLinearRegression2()"