日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Python構(gòu)建簡單線性回歸模型_python

作者:夢想畫家 ? 更新時間: 2022-10-22 編程語言

前言:

本文介紹如何構(gòu)建簡單線性回歸模型及計算其準(zhǔn)確率,最后介紹如何持久化模型。

線性回歸模型

線性回歸表示發(fā)現(xiàn)函數(shù)使用線性組合表示輸入變量。簡單線性回歸很容易理解,使用了基本的回歸技術(shù),一旦理解了這些基本概念,可以更好地學(xué)習(xí)其他類型的回歸模型。

回歸用于發(fā)現(xiàn)輸入變量和輸出變量之間的關(guān)系,一般變量為實數(shù)。我們的目標(biāo)是估計映射從輸入到輸出的映射核函數(shù)。

下面從一個簡單示例開始:

1 --> 2
3 --> 6
4.3 --> 8.6
1.1 --> 14.2

看到上面數(shù)據(jù),估計你已經(jīng)看出它們之間的關(guān)系:f(x) = 2x

但是現(xiàn)實數(shù)據(jù)不會這么直接。下面示例數(shù)據(jù)來自Vehicles.txt文件。每行數(shù)據(jù)使用逗號分割,第一個數(shù)據(jù)為輸入數(shù)據(jù),第二個為輸出數(shù)據(jù),我們的目標(biāo)是發(fā)現(xiàn)線性回歸關(guā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是響應(yīng)變量。在循環(huán)內(nèi)讀取每一行,然后基于逗號分裂為兩個變量并轉(zhuǎn)為浮點(diǎn)型。

2.劃分訓(xùn)練集和測試集

構(gòu)建機(jī)器學(xué)習(xí)模型,需要劃分訓(xùn)練集和測試集,訓(xùn)練集用于構(gòu)建模型,測試集用于驗證模型并檢查模型是否滿足要求。

num_training = int(0.8 * len(x))
num_test = len(x) - num_training

# 訓(xùn)練數(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ù)作為訓(xùn)練集,剩余的作為測試集。這時我們構(gòu)造了四個數(shù)組:x_train,x_test,y_train,y_test。

3.訓(xùn)練模型

現(xiàn)在準(zhǔn)備訓(xù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庫中導(dǎo)入linear_model方法,用于實現(xiàn)線性回歸,里面包括目標(biāo)值:輸入變量的線性組合。然后使用LinearRegression() 函數(shù)執(zhí)行最小二乘法執(zhí)行線性回歸。最后fit函數(shù)用于擬合線性模型,需要傳入兩個參數(shù):x_train,y_train。

4.預(yù)測數(shù)據(jù)

上面基于訓(xùn)練集擬合線性模型,使用fit方法接收訓(xùn)練數(shù)據(jù)訓(xùn)練模型。為了查看擬合程度,我們可以使用訓(xùn)練數(shù)據(jù)進(jìn)行預(yù)測:

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()

生成圖示如下:

前面使用訓(xùn)練模型預(yù)測訓(xùn)練數(shù)據(jù)。對于未知數(shù)據(jù)不能確定模型性能,我們需要基于測試數(shù)據(jù)進(jìn)行測試。

6.預(yù)測數(shù)據(jù)測試

下面基于測試數(shù)據(jù)進(jìn)行預(yù)測并畫圖展示:

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()

與我們預(yù)想的一致,省人口與汽車注冊量成正相關(guān)。

評估模型精度

上面構(gòu)建了回歸模型,但我們需要評估模型的質(zhì)量。這里我們定義錯誤為實際值與預(yù)測值之間的差異,下面我們看如何計算回歸模型的精度。

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))

輸出結(jié)果:

MAE = 241907.27
MSE = 81974851872.13
Median absolute error = 240861.94
Explain variance score = 0.98
R2 score = 0.98

R2得分接近1表示模型預(yù)測效果非常好。計算每個指標(biāo)會很麻煩,一般選擇一兩個指標(biāo)來評估模型。一個好的做法是MSE較低,解釋方差得分較高。

  • Mean absolute error: 所有數(shù)據(jù)集的平均絕對值誤差
  • Mean squared error: 所有數(shù)據(jù)集的平均誤差平方,是最常用的指標(biāo)之一。
  • Median absolute error: 所有數(shù)據(jù)集的誤差中位數(shù),該指標(biāo)主要用于消除異常值影響
  • Explained variance score: 模型在多大程度上能夠解釋數(shù)據(jù)集中的變化。1.0的分?jǐn)?shù)表明我們的模型是完美的。
  • R2 score: 這被讀作r2,是決定系數(shù)。表示模型對未知樣本的預(yù)測程度。最好的分?jǐn)?shù)是1.0,但也可以是負(fù)值。

模型持久化

訓(xùn)練完模型,可以保存至文件中,下次需要模型預(yù)測可直接從文件加載。
下面看如何持久化模型。需要使用pickle模塊,實現(xiàn)存儲Python對象,它是Python標(biāo)準(zhǔn)庫的一部分。

# 寫入文件
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))

輸出結(jié)果:

New mean absolute error = 241907.27

這里從文件加載數(shù)據(jù)至model_linregr變量,預(yù)測結(jié)果與上面一致。

原文鏈接:https://blog.csdn.net/neweastsun/article/details/126507917

欄目分類
最近更新