tft每日頭條

 > 圖文

 > python線性回歸預測教程

python線性回歸預測教程

圖文 更新时间:2025-03-14 06:53:28
專欄推薦線性回歸的算法的代碼實現

import matplotlib.pyplot as plt import numpy as npfrom sklearn import datasets#sklearn是機器學習的庫,提供了很多數據集

python線性回歸預測教程(線性回歸算法的正則方程的解法實現)1

class LinearRegression():

def __init__(self):

self.w = None

def fit(self, X, y):

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

python線性回歸預測教程(線性回歸算法的正則方程的解法實現)2

def mean_squared_error(y_true, y_pred):

mse = np.mean(np.power(y_true - y_pred, 2))

return mse

python線性回歸預測教程(線性回歸算法的正則方程的解法實現)3

def main():# Load the diabetes datasetdiabetes = datasets.load_diabetes()# Use only one featureX = diabetes.data[:, np.newaxis, 2]print (X.shape)# Split the data into training/testing setsx_train, x_test = X[:-20], X[-20:]# Split the targets into training/testing setsy_train, y_test = diabetes.target[:-20], diabetes.target[-20:]clf = LinearRegression()clf.fit(x_train, y_train)y_pred = clf.predict(x_test)# Print the mean squared errorprint ("Mean Squared Error:", mean_squared_error(y_test, y_pred))# Plot the resultsplt.scatter(x_test[:,0], y_test, color='black')plt.plot(x_test[:,0], y_pred, color='blue', linewidth=3)plt.show()

python線性回歸預測教程(線性回歸算法的正則方程的解法實現)4

main()

在main方法中加載了diabetes dataset

然後對這個數據進行進行變換賦值x,變化的x.shape為:

(422,1)

就是說這個數據隻有一維的,就是說這個數據有422個樣本,每個樣本隻有一個特征數據

x_train, x_test = X[:-20], X[-20:]

為測試集和訓練集的劃分


上面還有一個類LinearRegression

這個類有兩個方法:

def fit(self, X, y):這個方法是當我們有了數據和label(标注y),進行數據進行訓練,這個方法就是通過正規方程的方式來求出theta值,求出theta值之後,代價函數就有了,以後隻要帶入x,就可以求出代價函數的值了。

X = np.insert(X, 0, 1, axis=1)

這句代碼應該這樣理解,對應的公式是下面的

python線性回歸預測教程(線性回歸算法的正則方程的解法實現)5

然後給假設函數theta0配置了一個x0,x0=1

假設函數=theta0x0 theta1x1 theta2x2(x0=1)

此時x是一個列向量,(x0,x1,x2)應該是列向量這裡橫着寫的,要注意

python線性回歸預測教程(線性回歸算法的正則方程的解法實現)6

我們根據最終公式知道最後的seta的值為上面對這個,那麼放在代碼中是如何實現的呢?

X_ = np.linalg.inv(X.T.dot(X))self.w = X_.dot(X.T).dot(y)首先dot表示矩陣中的乘法,X.T表示x的轉秩X.T.dot(X)表示x的轉秩乘以x,np.linalg.inv()表示對矩陣求逆X_.dot(X.T).dot(y)然後再乘以x的轉秩和y最後得出了theta,就是說公式完全被代碼實現了,而代碼實現的是直接的公式結論就ok,沒必要從頭開始

def predict(self, X):有了上面方法的theta之後就可以使用該方法進行測試了

def predict(self, X):X = np.insert(X, 0, 1, axis=1)y_pred = X.dot(self.w)return y_pred

我們現在有了theta也就是當前程序中類的變量w,現在我們要預測x,隻需要按照公式

python線性回歸預測教程(線性回歸算法的正則方程的解法實現)7

用想要求的x乘以theta的轉秩就可以得出最終的h(x)值,就是我們想要的那個,預測結果

python線性回歸預測教程(線性回歸算法的正則方程的解法實現)8

如果我們最終用可視化工具畫出來的話,那麼就是上面的感覺

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关圖文资讯推荐

热门圖文资讯推荐

网友关注

Copyright 2023-2025 - www.tftnews.com All Rights Reserved