Python構建簡單線性回歸模型
前言:
本文介紹如何構建簡單線性回歸模型及計算其準確率,最后介紹如何持久化模型。
線性回歸模型
線性回歸表示發(fā)現(xiàn)函數(shù)使用線性組合表示輸入變量。簡單線性回歸很容易理解,使用了基本的回歸技術,一旦理解了這些基本概念,可以更好地學習其他類型的回歸模型。
回歸用于發(fā)現(xiàn)輸入變量和輸出變量之間的關系,一般變量為實數(shù)。我們的目標是估計映射從輸入到輸出的映射核函數(shù)。
下面從一個簡單示例開始:
1 --> 2 3 --> 6 4.3 --> 8.6 1.1 --> 14.2
看到上面數(shù)據(jù),估計你已經(jīng)看出它們之間的關系:f(x) = 2x
但是現(xiàn)實數(shù)據(jù)不會這么直接。下面示例數(shù)據(jù)來自Vehicles.txt文件。每行數(shù)據(jù)使用逗號分割,第一個數(shù)據(jù)為輸入數(shù)據(jù),第二個為輸出數(shù)據(jù),我們的目標是發(fā)現(xiàn)線性回歸關系:基于汽車登記量估計省份人口數(shù)量。
示例數(shù)據(jù)如下:
145263, 127329
204477, 312027
361034, 573694
616716, 891181
885665, 1059114
773600, 1221218
850513, 1326513
996733, 1543752
827967, 1571053
1011436,1658138
1222738,1970521
2404651,3744398
2259795,4077166
2844588,4404246
2774071,4448146
3011089,4915123
3169307,5074261
3346791,5850850
3702114,5888472
5923476,10008349
1.加載數(shù)據(jù)
import numpy as np from sklearn import linear_model import matplotlib.pyplot as plt import sklearn.metrics as sm import pickle filename = "data/vehicles.txt" x = [] y = [] with open(filename, 'r') as lines: for line in lines: xt, yt = [float(i) for i in line.split(',')] x.append(xt) y.append(yt)
上面代碼加載文件至x,y變量中,x是自變量,y是響應變量。在循環(huán)內(nèi)讀取每一行,然后基于逗號分裂為兩個變量并轉為浮點型。
2.劃分訓練集和測試集
構建機器學習模型,需要劃分訓練集和測試集,訓練集用于構建模型,測試集用于驗證模型并檢查模型是否滿足要求。
num_training = int(0.8 * len(x)) num_test = len(x) - num_training # 訓練數(shù)據(jù)占80% x_train = np.array(x[: num_training]).reshape((num_training, 1)) y_train = np.array(y[: num_training]) # 測試數(shù)據(jù)占20% x_test = np.array(x[num_training:]).reshape((num_test, 1)) y_test = np.array(y[num_training:])
首先取80%數(shù)據(jù)作為訓練集,剩余的作為測試集。這時我們構造了四個數(shù)組:x_train,x_test,y_train,y_test。
3.訓練模型
現(xiàn)在準備訓練模型,需要使用regressor對象。
# Create linear regression object linear_regressor = linear_model.LinearRegression() # Train the model using the training sets linear_regressor.fit(x_train, y_train)
首先從sklearn庫中導入linear_model方法,用于實現(xiàn)線性回歸,里面包括目標值:輸入變量的線性組合。然后使用LinearRegression() 函數(shù)執(zhí)行最小二乘法執(zhí)行線性回歸。最后fit函數(shù)用于擬合線性模型,需要傳入兩個參數(shù):x_train,y_train。
4.預測數(shù)據(jù)
上面基于訓練集擬合線性模型,使用fit方法接收訓練數(shù)據(jù)訓練模型。為了查看擬合程度,我們可以使用訓練數(shù)據(jù)進行預測:
y_train_pred = linear_regressor.predict(X_train)
5.畫圖展示線性擬合情況
plt.figure() plt.scatter(x_train, y_train, color='green') plt.plot(x_train, y_train_pred, color='black', linewidth=4) plt.title('Training data') plt.show()
生成圖示如下:
前面使用訓練模型預測訓練數(shù)據(jù)。對于未知數(shù)據(jù)不能確定模型性能,我們需要基于測試數(shù)據(jù)進行測試。
6.預測數(shù)據(jù)測試
下面基于測試數(shù)據(jù)進行預測并畫圖展示:
y_test_pred = linear_regressor.predict(x_test) plt.figure() plt.scatter(x_test, y_test, color='green') plt.plot(x_test, y_test_pred, color='black', linewidth=4) plt.title('Test data') plt.show()
與我們預想的一致,省人口與汽車注冊量成正相關。
評估模型精度
上面構建了回歸模型,但我們需要評估模型的質(zhì)量。這里我們定義錯誤為實際值與預測值之間的差異,下面我們看如何計算回歸模型的精度。
1.計算回歸模型精度
print("MAE =", round(sm.mean_absolute_error(y_test, y_test_pred), 2)) print("MSE =", round(sm.mean_squared_error(y_test, y_test_pred), 2)) print("Median absolute error =", round(sm.median_absolute_error(y_test, y_test_pred), 2)) print("Explain variance score =", round(sm.explained_variance_score(y_test, y_test_pred), 2)) print("R2 score =", round(sm.r2_score(y_test, y_test_pred), 2))
輸出結果:
MAE = 241907.27
MSE = 81974851872.13
Median absolute error = 240861.94
Explain variance score = 0.98
R2 score = 0.98
R2得分接近1表示模型預測效果非常好。計算每個指標會很麻煩,一般選擇一兩個指標來評估模型。一個好的做法是MSE較低,解釋方差得分較高。
- Mean absolute error: 所有數(shù)據(jù)集的平均絕對值誤差
- Mean squared error: 所有數(shù)據(jù)集的平均誤差平方,是最常用的指標之一。
- Median absolute error: 所有數(shù)據(jù)集的誤差中位數(shù),該指標主要用于消除異常值影響
- Explained variance score: 模型在多大程度上能夠解釋數(shù)據(jù)集中的變化。1.0的分數(shù)表明我們的模型是完美的。
- R2 score: 這被讀作r²,是決定系數(shù)。表示模型對未知樣本的預測程度。最好的分數(shù)是1.0,但也可以是負值。
模型持久化
訓練完模型,可以保存至文件中,下次需要模型預測可直接從文件加載。
下面看如何持久化模型。需要使用pickle模塊,實現(xiàn)存儲Python對象,它是Python標準庫的一部分。
# 寫入文件 output_model_file = "3_model_linear_regr.pkl" with open(output_model_file, ' wb') as f: pickle.dump(linear_regressor, f) # 加載使用 with open(output_model_file, ' rb') as f: model_linregr = pickle.load(f) y_test_pred_new = model_linregr.predict(x_test) print("New mean absolute error =", round(sm.mean_absolute_error(y_test, y_test_pred_new), 2))
輸出結果:
New mean absolute error = 241907.27
這里從文件加載數(shù)據(jù)至model_linregr變量,預測結果與上面一致。
到此這篇關于Python構建簡單線性回歸模型的文章就介紹到這了,更多相關Python線性回歸內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python基礎第三方模塊requests openpyxl
這篇文章主要為大家介紹了Python基礎第三方模塊requests openpyxl使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11Python生成器深度解析如何構建強大的數(shù)據(jù)處理管道
這篇文章主要為大家介紹了Python生成器深度解析如何構建強大的數(shù)據(jù)處理管道,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06python實現(xiàn)人人對戰(zhàn)的五子棋游戲
這篇文章主要為大家詳細介紹了python實現(xiàn)人人對戰(zhàn)的五子棋游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-05-05