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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

sklearn线性回归详解

發布時間:2023/12/4 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 sklearn线性回归详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

圖片若未能正常顯示,點擊下面鏈接:
http://ihoge.cn/2018/Logistic-regression.html

在線性回歸中,我們想要建立一個模型,來擬合一個因變量 y 與一個或多個獨立自變量(預測變量) x 之間的關系。

給定:

數據集

{(x(1),y(1)),...,(x(m),y(m))}{(x(1),y(1)),...,(x(m),y(m))}

xixi是d-維向量Xi=(x(i)1,...,x(i)d)Xi=(x1(i),...,xd(i))

y(i)y(i)是一個目標變量,它是一個標量

線性回歸模型可以理解為一個非常簡單的神經網絡:

它有一個實值加權向量w=(w(i),...,w(d))w=(w(i),...,w(d))
它有一個實值偏置量 b
它使用恒等函數作為其激活函數

線性回歸模型可以使用以下方法進行訓練

a) 梯度下降法

b) 正態方程(封閉形式解)w=(XTX)?1XTyw=(XTX)?1XTy

其中 X 是一個矩陣,其形式為(m,nfeatures)(m,nfeatures),包含所有訓練樣本的維度信息。

而正態方程需要計算(XTX)(XTX)的轉置。這個操作的計算復雜度介于O(n2.4features)O(nfeatures2.4)O(n3features)O(nfeatures3)之間,而這取決于所選擇的實現方法。因此,如果訓練集中數據的特征數量很大,那么使用正態方程訓練的過程將變得非常緩慢。

線性回歸模型的訓練過程有不同的步驟。首先(在步驟 0 中),模型的參數將被初始化。在達到指定訓練次數或參數收斂前,重復以下其他步驟。

第 0 步:

用0 (或小的隨機值)來初始化權重向量和偏置量,或者直接使用正態方程計算模型參數

第 1 步(只有在使用梯度下降法訓練時需要):

計算輸入的特征與權重值的線性組合,這可以通過矢量化和矢量傳播來對所有訓練樣本進行處理:
y˙=X?w+by˙=X?w+b

其中 X 是所有訓練樣本的維度矩陣,其形式為(m,nfeatures)(m,nfeatures);這里我用· 表示

第 2 步(只有在使用梯度下降法訓練時需要):

用均方誤差計算訓練集上的損失:J(w,b)=1mmi=1(y˙(i)?y(i))2J(w,b)=1m∑i=1m(y˙(i)?y(i))2

第 3 步(只有在使用梯度下降法訓練時需要):

對每個參數,計算其對損失函數的偏導數:

?J?wj=2mmi=1(y˙(i)?y(i))x(i)j?J?wj=2m∑i=1m(y˙(i)?y(i))xj(i)

?J?b=2mmi=1(y˙(i)?y(i))?J?b=2m∑i=1m(y˙(i)?y(i))

所有偏導數的梯度計算如下:

ΔwJ=2mXT(y˙?y)ΔwJ=2mXT(y˙?y)

ΔbJ=2m(y˙?y)ΔbJ=2m(y˙?y)

第 4 步(只有在使用梯度下降法訓練時需要):

更新權重向量和偏置量:

w=w?ηΔwJw=w?ηΔwJ

ΔbJ=2m(y˙?y)ΔbJ=2m(y˙?y)

其中η表示學習率

代碼實現

數據集

import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split np.random.seed(123)X = 2 * np.random.rand(500, 1) y = 5 + 3 * X + np.random.randn(500, 1) fig = plt.figure(figsize=(8,6)) plt.scatter(X, y) plt.title("Dataset") plt.xlabel("First feature") plt.ylabel("Second feature") plt.show()

X_train, X_test, y_train, y_test = train_test_split(X, y) print(f'Shape X_train: {X_train.shape}') print(f'Shape y_train: {y_train.shape}') print(f'Shape X_test: {X_test.shape}') print(f'Shape y_test: {y_test.shape}') Shape X_train: (375, 1) Shape y_train: (375, 1) Shape X_test: (125, 1) Shape y_test: (125, 1)

線性回歸分類 源碼編譯

class LinearRegression:def __init__(self):passdef train_gradient_descent(self, X, y, learning_rate=0.01, n_iters=100):"""Trains a linear regression model using gradient descent"""# Step 0: Initialize the parametersn_samples, n_features = X.shapeself.weights = np.zeros(shape=(n_features,1))self.bias = 0costs = []for i in range(n_iters):# Step 1: Compute a linear combination of the input features and weightsy_predict = np.dot(X, self.weights) + self.bias# Step 2: Compute cost over training setcost = (1 / n_samples) * np.sum((y_predict - y)**2)costs.append(cost)if i % 100 == 0:print(f"Cost at iteration {i}: {cost}")# Step 3: Compute the gradientsdJ_dw = (2 / n_samples) * np.dot(X.T, (y_predict - y))dJ_db = (2 / n_samples) * np.sum((y_predict - y)) # Step 4: Update the parametersself.weights = self.weights - learning_rate * dJ_dwself.bias = self.bias - learning_rate * dJ_dbreturn self.weights, self.bias, costsdef train_normal_equation(self, X, y):"""Trains a linear regression model using the normal equation"""self.weights = np.dot(np.dot(np.linalg.inv(np.dot(X.T, X)), X.T), y)self.bias = 0return self.weights, self.biasdef predict(self, X):return np.dot(X, self.weights) + self.bias

使用梯度下降進行訓練

regressor = LinearRegression() w_trained, b_trained, costs = regressor.train_gradient_descent(X_train, y_train, learning_rate=0.005, n_iters=600) fig = plt.figure(figsize=(8,6)) plt.plot(np.arange(600), costs) plt.title("Development of cost during training") plt.xlabel("Number of iterations") plt.ylabel("Cost") plt.show() Cost at iteration 0: 66.45256981003433 Cost at iteration 100: 2.208434614609594 Cost at iteration 200: 1.2797812854182806 Cost at iteration 300: 1.2042189195356685 Cost at iteration 400: 1.1564867816573 Cost at iteration 500: 1.121391041394467Text(0,0.5,'Cost')

測試(梯度下降模型)

n_samples, _ = X_train.shape n_samples_test, _ = X_test.shapey_p_train = regressor.predict(X_train) y_p_test = regressor.predict(X_test)error_train = (1 / n_samples) * np.sum((y_p_train - y_train) ** 2) error_test = (1 / n_samples_test) * np.sum((y_p_test - y_test) ** 2)print(f"Error on training set: {np.round(error_train, 4)}") print(f"Error on test set: {np.round(error_test)}") Error on training set: 1.0955 Error on test set: 1.0

使用正規方程(normal equation)訓練

X_b_train = np.c_[np.ones((n_samples)), X_train] X_b_test = np.c_[np.ones((n_samples_test)), X_test]reg_normal = LinearRegression() w_trained = reg_normal.train_normal_equation(X_b_train, y_train)

測試(正規方程模型)

y_p_train = reg_normal.predict(X_b_train) y_p_test = reg_normal.predict(X_b_test)error_train = (1 / n_samples) * np.sum((y_p_train - y_train) ** 2) error_test = (1 / n_samples_test) * np.sum((y_p_test - y_test) ** 2)print(f"Error on training set: {np.round(error_train, 4)}") print(f"Error on test set: {np.round(error_test, 4)}") Error on training set: 1.0228 Error on test set: 1.0432

可視化測試預測

fig = plt.figure(figsize=(8,6)) plt.scatter(X_train, y_train) plt.scatter(X_test, y_p_test) plt.xlabel("First feature") plt.ylabel("Second feature") plt.show() Text(0,0.5,'Second feature')

轉載注明出處:
http://ihoge.cn/2018/Logistic-regression.html

總結

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

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