简单线性回归预测实现
生活随笔
收集整理的這篇文章主要介紹了
简单线性回归预测实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import numpy as np
from .metrics import r2_scoreclass SimpleLinearRegression:def __init__(self):"""初始化Simple Linear Regression模型"""self.a_ = Noneself.b_ = Nonedef fit(self, x_train, y_train):"""根據訓練數據集x_train, y_train訓練Simple Linear Regression模型"""assert x_train.ndim == 1, \"Simple Linear Regressor 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)self.a_ = (x_train - x_mean).dot(y_train - y_mean) / (x_train - x_mean).dot(x_train - x_mean)#向量化 點乘運算self.b_ = y_mean - self.a_ * x_meanreturn selfdef predict(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_ 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,返回x的預測結果值"""return self.a_ * x_single + self.b_def score(self, x_test, y_test):"""根據測試數據集 x_test 和 y_test 確定當前模型的準確度"""y_predict = self.predict(x_test)return r2_score(y_test, y_predict)def __repr__(self):return "SimpleLinearRegression()"
?
衡量線性回歸模型誤差的三種方式
def mean_squared_error(y_true, y_predict):"""計算y_true和y_predict之間的MSE"""assert len(y_true) == len(y_predict), \"the size of y_true must be equal to the size of y_predict"return np.sum((y_true - y_predict)**2) / len(y_true)def root_mean_squared_error(y_true, y_predict):"""計算y_true和y_predict之間的RMSE"""return sqrt(mean_squared_error(y_true, y_predict))def mean_absolute_error(y_true, y_predict):"""計算y_true和y_predict之間的RMSE"""assert len(y_true) == len(y_predict), \"the size of y_true must be equal to the size of y_predict"return np.sum(np.absolute(y_true - y_predict)) / len(y_true)?
計算最終模型預測準確度R方
def r2_score(y_true, y_predict):"""計算y_true和y_predict之間的R Square"""return 1 - mean_squared_error(y_true, y_predict)/np.var(y_true)?
轉載于:https://www.cnblogs.com/Erick-L/p/9031064.html
總結
以上是生活随笔為你收集整理的简单线性回归预测实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hiveServer2 和 metast
- 下一篇: ORACLE中的MERGE语法使用记录