日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

简单线性回归预测实现

發布時間:2024/4/15 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 简单线性回归预测实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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

總結

以上是生活随笔為你收集整理的简单线性回归预测实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。