在实际工作中,有时候sklearn库的标准API不能满足业务需求,这时候需要自定义算法,下面是我自定义的标准线性回归函数,如果有需要,可以在此基础上进行扩展,比如局部加权线性回归的定义
class self_linear_model(): def __init__(self): self.w = None def fit(self, X, y): # Insert constant ones for bias weights print (X.shape) X = np.insert(X, 0, 1, axis=1) print (X.shape) X_ = np.linalg.inv(X.T.dot(X)) self.w = X_.dot(X.T).dot(y) def predict(self, X): # Insert constant ones for bias weights X = np.insert(X, 0, 1, axis=1) y_pred = X.dot(self.w) return y_pred def mean_squared_error(y_true, y_pred): mse = np.mean(np.power(y_true - y_pred, 2)) return mse