溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么用Python神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)汽車保險(xiǎn)支出

發(fā)布時(shí)間:2021-10-19 11:25:18 來(lái)源:億速云 閱讀:114 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容主要講解“怎么用Python神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)汽車保險(xiǎn)支出”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“怎么用Python神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)汽車保險(xiǎn)支出”吧!

為新數(shù)據(jù)集開(kāi)發(fā)神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)模型可能具有挑戰(zhàn)性。

一種方法是首先檢查數(shù)據(jù)集并為可能使用的模型開(kāi)發(fā)思路,然后探索數(shù)據(jù)集上簡(jiǎn)單模型的學(xué)習(xí)動(dòng)態(tài),然后最后使用健壯的測(cè)試工具為數(shù)據(jù)集開(kāi)發(fā)和調(diào)整模型。此過(guò)程可用于為分類和回歸預(yù)測(cè)建模問(wèn)題開(kāi)發(fā)有效的神經(jīng)網(wǎng)絡(luò)模型。

在本教程中,您將發(fā)現(xiàn)如何為瑞典汽車保險(xiǎn)回歸數(shù)據(jù)集開(kāi)發(fā)多層Perceptron神經(jīng)網(wǎng)絡(luò)模型。完成本教程后,您將知道:

  •  如何加載和匯總?cè)鸬淦嚤kU(xiǎn)數(shù)據(jù)集,以及如何使用結(jié)果建議要使用的數(shù)據(jù)準(zhǔn)備和模型配置。

  •  如何探索簡(jiǎn)單的MLP模型的學(xué)習(xí)動(dòng)態(tài)以及數(shù)據(jù)集上的數(shù)據(jù)轉(zhuǎn)換。

  •  如何開(kāi)發(fā)出對(duì)模型性能的可靠估計(jì),調(diào)整模型性能以及對(duì)新數(shù)據(jù)進(jìn)行預(yù)測(cè)。

教程概述

本教程分為四個(gè)部分。他們是:

  •  汽車保險(xiǎn)回歸數(shù)據(jù)集

  •  首個(gè)MLP和學(xué)習(xí)動(dòng)力

  •  評(píng)估和調(diào)整MLP模型

  •  最終模型和做出預(yù)測(cè)

汽車保險(xiǎn)回歸數(shù)據(jù)集

第一步是定義和探索數(shù)據(jù)集。我們將使用“汽車保險(xiǎn)”標(biāo)準(zhǔn)回歸數(shù)據(jù)集。該數(shù)據(jù)集描述了瑞典的汽車保險(xiǎn)。只有一個(gè)輸入變量,即索賠的數(shù)量,目標(biāo)變量是以數(shù)千瑞典克朗為單位的索賠總額。目的是在給定索賠數(shù)量的情況下預(yù)測(cè)總付款額。

您可以在此處了解有關(guān)數(shù)據(jù)集的更多信息:

  •  汽車保險(xiǎn)數(shù)據(jù)集(auto-insurance.csv)

  •  汽車保險(xiǎn)數(shù)據(jù)集詳細(xì)信息(auto-insurance.names)

您可以在下面看到數(shù)據(jù)集的前幾行。

108,392.5  19,46.2  13,15.7  124,422.2  40,119.4

我們可以看到這些值是數(shù)字的,范圍從幾十到幾百。這表明在使用神經(jīng)網(wǎng)絡(luò)進(jìn)行建模時(shí),某種類型的縮放比例適合于數(shù)據(jù)。

我們可以直接從URL將數(shù)據(jù)集作為pandas DataFrame加載;例如:

# load the dataset and summarize the shape  from pandas import read_csv  # define the location of the dataset  url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  # load the dataset  df = read_csv(url, header=None)  # summarize shape  print(df.shape)

運(yùn)行示例將直接從URL加載數(shù)據(jù)集并報(bào)告數(shù)據(jù)集的形狀。

在這種情況下,我們可以確認(rèn)該數(shù)據(jù)集具有兩個(gè)變量(一個(gè)輸入和一個(gè)輸出),并且該數(shù)據(jù)集具有63行數(shù)據(jù)。

對(duì)于神經(jīng)網(wǎng)絡(luò)來(lái)說(shuō),這不是很多數(shù)據(jù)行,這表明一個(gè)小型的網(wǎng)絡(luò)(可能帶有正則化)將是合適的。

這也表明使用k倍交叉驗(yàn)證是一個(gè)好主意,因?yàn)榕c火車/測(cè)試拆分相比,它可以提供更可靠的模型性能估算值,并且因?yàn)閱蝹€(gè)模型可以在數(shù)秒而不是數(shù)小時(shí)或數(shù)天的時(shí)間內(nèi)完成擬合。最大的數(shù)據(jù)集。

(63, 2)

接下來(lái),我們可以通過(guò)查看摘要統(tǒng)計(jì)信息和數(shù)據(jù)圖來(lái)了解有關(guān)數(shù)據(jù)集的更多信息。

# show summary statistics and plots of the dataset  from pandas import read_csv  from matplotlib import pyplot  # define the location of the dataset  url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  # load the dataset  df = read_csv(url, header=None)  # show summary statistics  print(df.describe())  # plot histograms  df.hist()  pyplot.show()

運(yùn)行示例之前,先加載數(shù)據(jù),然后輸出每個(gè)變量的摘要統(tǒng)計(jì)信息

我們可以看到每個(gè)變量的平均值在十個(gè)以內(nèi),范圍從0到數(shù)百。這證實(shí)了縮放數(shù)據(jù)可能是一個(gè)好主意。

              0           1  count   63.000000   63.000000  mean    22.904762   98.187302  std     23.351946   87.327553  min      0.000000    0.000000  25%      7.500000   38.850000  50%     14.000000   73.400000  75%     29.000000  140.000000  max    124.000000  422.200000

然后為每個(gè)變量創(chuàng)建一個(gè)直方圖。

我們可以看到每個(gè)變量都有相似的分布。它看起來(lái)像偏態(tài)的高斯分布或指數(shù)分布。

我們可以在每個(gè)變量上使用冪變換來(lái)降低概率分布的偏斜度,這可能會(huì)提高模型性能。

怎么用Python神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)汽車保險(xiǎn)支出

現(xiàn)在我們已經(jīng)熟悉了數(shù)據(jù)集,讓我們探討如何開(kāi)發(fā)神經(jīng)網(wǎng)絡(luò)模型。

首個(gè)MLP和學(xué)習(xí)動(dòng)力

我們將使用TensorFlow為數(shù)據(jù)集開(kāi)發(fā)一個(gè)多層感知器(MLP)模型。我們不知道學(xué)習(xí)超參數(shù)的哪種模型架構(gòu)對(duì)這個(gè)數(shù)據(jù)集將是好的還是最好的,所以我們必須進(jìn)行實(shí)驗(yàn)并發(fā)現(xiàn)什么是行之有效的。假設(shè)數(shù)據(jù)集很小,則小批量可能是個(gè)好主意,例如8或16行。入門時(shí),使用Adam版本的隨機(jī)梯度下降法是一個(gè)好主意,因?yàn)樗鼤?huì)自動(dòng)適應(yīng)學(xué)習(xí)率,并且在大多數(shù)數(shù)據(jù)集上都能很好地工作。在認(rèn)真評(píng)估模型之前,最好回顧一下學(xué)習(xí)動(dòng)態(tài)并調(diào)整模型體系結(jié)構(gòu)和學(xué)習(xí)配置,直到我們擁有穩(wěn)定的學(xué)習(xí)動(dòng)態(tài),然后再充分利用模型。

我們可以通過(guò)簡(jiǎn)單的訓(xùn)練/測(cè)試數(shù)據(jù)拆分并查看學(xué)習(xí)曲線圖來(lái)實(shí)現(xiàn)。這將幫助我們了解我們是學(xué)習(xí)過(guò)度還是學(xué)習(xí)不足;然后我們可以相應(yīng)地調(diào)整配置。首先,我們可以將數(shù)據(jù)集分為輸入和輸出變量,然后分為67/33訓(xùn)練和測(cè)試集。

# split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # split into train and test datasets  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)

接下來(lái),我們可以定義一個(gè)最小的MLP模型。在這種情況下,我們將使用一個(gè)包含10個(gè)節(jié)點(diǎn)的隱藏層和一個(gè)輸出層(任意選擇)。我們將在隱藏層中使用ReLU激活功能和“ he_normal”權(quán)重初始化,因?yàn)樗鼈兪且环N很好的做法。

模型的輸出是線性激活(不激活),我們將最小化均方誤差(MSE)損失。

# determine the number of input features  n_features = X.shape[1]  # define model  model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))  model.add(Dense(1))  # compile the model  model.compile(optimizer='adam', loss='mse')

我們將模型擬合為100個(gè)訓(xùn)練時(shí)期(任意選擇),批量為8個(gè),因?yàn)樗且粋€(gè)很小的數(shù)據(jù)集。我們正在原始數(shù)據(jù)上擬合模型,我們認(rèn)為這可能不是一個(gè)好主意,但這是一個(gè)重要的起點(diǎn)。

# fit the model  history = model.fit(X_train, y_train, epochs=100, batch_size=8, verbose=0, validation_data=(X_test,y_test))

在訓(xùn)練結(jié)束時(shí),我們將評(píng)估模型在測(cè)試數(shù)據(jù)集上的性能,并將性能報(bào)告為平均絕對(duì)誤差(MAE),我通常更喜歡MSE或RMSE。

# predict test set  yhat = model.predict(X_test)  # evaluate predictions  score = mean_absolute_error(y_test, yhat)  print('MAE: %.3f' % score)

最后,我們將在訓(xùn)練期間在訓(xùn)練和測(cè)試集上繪制MSE損失的學(xué)習(xí)曲線。

# plot learning curves  pyplot.title('Learning Curves')  pyplot.xlabel('Epoch')  pyplot.ylabel('Mean Squared Error')  pyplot.plot(history.history['loss'], label='train')  pyplot.plot(history.history['val_loss'], label='val')  pyplot.legend()  pyplot.show()

綜上所述,下面列出了評(píng)估我們?cè)谄嚤kU(xiǎn)數(shù)據(jù)集上的第一個(gè)MLP的完整示例。

# fit a simple mlp model and review learning curves  from pandas import read_csv  from sklearn.model_selection import train_test_split  from sklearn.metrics import mean_absolute_error  from tensorflow.keras import Sequential  from tensorflow.keras.layers import Dense  from matplotlib import pyplot  # load the dataset  path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  df = read_csv(path, header=None)  # split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # split into train and test datasets  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)  # determine the number of input features  n_features = X.shape[1]  # define model  model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))  model.add(Dense(1))  # compile the model  model.compile(optimizer='adam', loss='mse')  # fit the model  history = model.fit(X_train, y_train, epochs=100, batch_size=8, verbose=0, validation_data=(X_test,y_test))  # predict test set  yhat = model.predict(X_test)  # evaluate predictions  score = mean_absolute_error(y_test, yhat)  print('MAE: %.3f' % score)  # plot learning curves  pyplot.title('Learning Curves')  pyplot.xlabel('Epoch')  pyplot.ylabel('Mean Squared Error')  pyplot.plot(history.history['loss'], label='train')  pyplot.plot(history.history['val_loss'], label='val')  pyplot.legend()  pyplot.show()

運(yùn)行示例首先使模型適合訓(xùn)練數(shù)據(jù)集,然后報(bào)告測(cè)試數(shù)據(jù)集的MAE。

注意:由于算法或評(píng)估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會(huì)有所不同??紤]運(yùn)行該示例幾次并比較平均結(jié)果。

在這種情況下,我們可以看到該模型實(shí)現(xiàn)了大約33.2的MAE,這是性能的良好基準(zhǔn),我們可能可以對(duì)其進(jìn)行改進(jìn)。

MAE: 33.233

然后在火車和測(cè)試裝置上創(chuàng)建MSE的線圖。

我們可以看到該模型具有良好的擬合度,并且收斂良好。模型的配置是一個(gè)很好的起點(diǎn)。

怎么用Python神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)汽車保險(xiǎn)支出

到目前為止,學(xué)習(xí)動(dòng)力很好,MAE是一個(gè)粗略的估計(jì),不應(yīng)該被依賴。

我們可能可以稍微增加模型的容量,并期待類似的學(xué)習(xí)動(dòng)態(tài)。例如,我們可以添加具有八個(gè)節(jié)點(diǎn)(任意選擇)的第二個(gè)隱藏層,并將訓(xùn)練時(shí)期數(shù)增加一倍至200。

# define model  model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))  model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))  model.add(Dense(1))  # compile the model model.compile(optimizer='adam', loss='mse')  # fit the model  history = model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0, validation_data=(X_test,y_test))

完整實(shí)例如下:

# fit a deeper mlp model and review learning curves  from pandas import read_csv  from sklearn.model_selection import train_test_split  from sklearn.metrics import mean_absolute_error  from tensorflow.keras import Sequential  from tensorflow.keras.layers import Dense  from matplotlib import pyplot # load the dataset  path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  df = read_csv(path, header=None)  # split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # split into train and test datasets  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)  # determine the number of input features  n_features = X.shape[1]  # define model  model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))  model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))  model.add(Dense(1))  # compile the model  model.compile(optimizer='adam', loss='mse')  # fit the model  history = model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0, validation_data=(X_test,y_test))  # predict test set  yhat = model.predict(X_test)  # evaluate predictions  score = mean_absolute_error(y_test, yhat)  print('MAE: %.3f' % score)  # plot learning curves  pyplot.title('Learning Curves')  pyplot.xlabel('Epoch')  pyplot.ylabel('Mean Squared Error')  pyplot.plot(history.history['loss'], label='train')  pyplot.plot(history.history['val_loss'], label='val')  pyplot.legend()  pyplot.show()

運(yùn)行示例首先使模型適合訓(xùn)練數(shù)據(jù)集,然后報(bào)告測(cè)試數(shù)據(jù)集的MAE。

注意:由于算法或評(píng)估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會(huì)有所不同。考慮運(yùn)行該示例幾次并比較平均結(jié)果。

在這種情況下,我們可以看到MAE略有改善,約為27.9,盡管訓(xùn)練/測(cè)試拆分的高方差意味著該評(píng)估是不可靠的。

MAE: 27.939

然后繪制MSE訓(xùn)練和測(cè)試集的學(xué)習(xí)曲線。我們可以看到,正如預(yù)期的那樣,該模型在合理的迭代次數(shù)內(nèi)實(shí)現(xiàn)了良好的擬合和收斂。

怎么用Python神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)汽車保險(xiǎn)支出

最后,我們可以嘗試轉(zhuǎn)換數(shù)據(jù),看看它如何影響學(xué)習(xí)動(dòng)力。

在這種情況下,我們將使用冪變換來(lái)減少數(shù)據(jù)分布的偏差。這還將自動(dòng)標(biāo)準(zhǔn)化變量,以使它們的平均值為零,標(biāo)準(zhǔn)偏差為1,這是使用神經(jīng)網(wǎng)絡(luò)進(jìn)行建模時(shí)的一種好習(xí)慣。

首先,我們必須確保目標(biāo)變量是二維數(shù)組。

# ensure that the target variable is a 2d array  y_train, y_test = y_train.reshape((len(y_train),1)), y_test.reshape((len(y_test),1))

接下來(lái),我們可以將PowerTransformer應(yīng)用于輸入變量和目標(biāo)變量。

這可以通過(guò)首先將轉(zhuǎn)換適合訓(xùn)練數(shù)據(jù),然后轉(zhuǎn)換訓(xùn)練和測(cè)試集來(lái)實(shí)現(xiàn)。

此過(guò)程將分別應(yīng)用于輸入和輸出變量,以避免數(shù)據(jù)泄漏。

# power transform input data  pt1 = PowerTransformer()  pt1.fit(X_train)  X_train = pt1.transform(X_train)  X_test = pt1.transform(X_test)  # power transform output data  pt2 = PowerTransformer()  pt2.fit(y_train)  y_train = pt2.transform(y_train)  y_test = pt2.transform(y_test)

然后將數(shù)據(jù)用于擬合模型。

后面可以根據(jù)模型做出的預(yù)測(cè)以及測(cè)試集中的預(yù)期目標(biāo)值對(duì)變換進(jìn)行求逆,我們可以像以前一樣以正確的比例計(jì)算MAE。

# inverse transforms on target variable  y_test = pt2.inverse_transform(y_test)  yhat = pt2.inverse_transform(yhat)

結(jié)合在一起,下面列出了使用轉(zhuǎn)換后的數(shù)據(jù)擬合和評(píng)估MLP以及創(chuàng)建模型的學(xué)習(xí)曲線的完整示例。

# fit a mlp model with data transforms and review learning curves  from pandas import read_csv  from sklearn.model_selection import train_test_split  from sklearn.metrics import mean_absolute_error from sklearn.preprocessing import PowerTransformer  from tensorflow.keras import Sequential  from tensorflow.keras.layers import Dense  from matplotlib import pyplot  # load the dataset  path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  df = read_csv(path, header=None)  # split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # split into train and test datasets  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)  # ensure that the target variable is a 2d array  y_train, y_test = y_train.reshape((len(y_train),1)), y_test.reshape((len(y_test),1))  # power transform input data pt1 = PowerTransformer()  pt1.fit(X_train)  X_train = pt1.transform(X_train)  X_test = pt1.transform(X_test)  # power transform output data  pt2 = PowerTransformer()  pt2.fit(y_train)  y_train = pt2.transform(y_train)  y_test = pt2.transform(y_test)  # determine the number of input features  n_features = X.shape[1]  # define model  model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))  model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))  model.add(Dense(1))  # compile the model  model.compile(optimizer='adam', loss='mse')  # fit the model  history = model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0, validation_data=(X_test,y_test))  # predict test set  yhat = model.predict(X_test)  # inverse transforms on target variable  y_test = pt2.inverse_transform(y_test)  yhat = pt2.inverse_transform(yhat)  # evaluate predictions  score = mean_absolute_error(y_test, yhat) print('MAE: %.3f' % score)  # plot learning curves  pyplot.title('Learning Curves')  pyplot.xlabel('Epoch')  pyplot.ylabel('Mean Squared Error')  pyplot.plot(history.history['loss'], label='train') pyplot.plot(history.history['val_loss'], label='val')  pyplot.legend()  pyplot.show()

運(yùn)行示例首先使模型適合訓(xùn)練數(shù)據(jù)集,然后報(bào)告測(cè)試數(shù)據(jù)集的MAE。

注意:由于算法或評(píng)估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會(huì)有所不同??紤]運(yùn)行該示例幾次并比較平均結(jié)果。

在這種情況下,該模型可以達(dá)到合理的MAE分?jǐn)?shù),盡管比以前報(bào)告的性能差。我們暫時(shí)將忽略模型性能。

MAE: 34.320

創(chuàng)建了學(xué)習(xí)曲線的線圖,表明該模型達(dá)到了合理的擬合并且有足夠的時(shí)間收斂。

怎么用Python神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)汽車保險(xiǎn)支出

現(xiàn)在,我們對(duì)帶有或不帶有數(shù)據(jù)轉(zhuǎn)換的簡(jiǎn)單MLP模型的學(xué)習(xí)動(dòng)態(tài)有了一些了解,現(xiàn)在我們可以看一下評(píng)估模型的性能以及調(diào)整模型的配置。

評(píng)估和調(diào)整MLP模型

k倍交叉驗(yàn)證過(guò)程可以提供更可靠的MLP性能估計(jì),盡管它可能非常慢。這是因?yàn)楸仨殧M合和評(píng)估k個(gè)模型。當(dāng)數(shù)據(jù)集大小較小時(shí)(例如汽車保險(xiǎn)數(shù)據(jù)集),這不是問(wèn)題。我們可以使用KFold類創(chuàng)建拆分并手動(dòng)枚舉每個(gè)折疊,擬合模型,對(duì)其進(jìn)行評(píng)估,然后在過(guò)程結(jié)束時(shí)報(bào)告評(píng)估分?jǐn)?shù)的平均值。

# prepare cross validation  kfold = KFold(10)  # enumerate splits  scores = list()  for train_ix, test_ix in kfold.split(X, y):   # fit and evaluate the model...   ...  ...  # summarize all scores  print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

我們可以使用此框架通過(guò)一系列不同的數(shù)據(jù)準(zhǔn)備,模型架構(gòu)和學(xué)習(xí)配置來(lái)開(kāi)發(fā)MLP模型性能的可靠估計(jì)。

重要的是,在使用k-fold交叉驗(yàn)證來(lái)評(píng)估性能之前,我們首先對(duì)上一部分中的數(shù)據(jù)集模型的學(xué)習(xí)動(dòng)態(tài)有了了解。如果我們開(kāi)始直接調(diào)整模型,我們可能會(huì)獲得良好的結(jié)果,但是如果沒(méi)有,我們可能不知道為什么,例如 模型超出或不足。

如果我們?cè)俅螌?duì)模型進(jìn)行較大的更改,則最好返回并確認(rèn)模型正在適當(dāng)收斂。

下面列出了評(píng)估上一節(jié)中的基本MLP模型的此框架的完整示例。

# k-fold cross-validation of base model for the auto insurance regression dataset  from numpy import mean  from numpy import std  from pandas import read_csv  from sklearn.model_selection import KFold  from sklearn.metrics import mean_absolute_error  from tensorflow.keras import Sequential  from tensorflow.keras.layers import Dense  from matplotlib import pyplot  # load the dataset  path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  df = read_csv(path, header=None)  # split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # prepare cross validation  kfold = KFold(10)  # enumerate splits  scores = list()  for train_ix, test_ix in kfold.split(X, y):   # split data   X_train, X_test, y_train, y_test = X[train_ix], X[test_ix], y[train_ix], y[test_ix]   # determine the number of input features   n_features = X.shape[1]   # define model   model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))   model.add(Dense(1))   # compile the model   model.compile(optimizer='adam', loss='mse')   # fit the model  model.fit(X_train, y_train, epochs=100, batch_size=8, verbose=0)   # predict test set   yhat = model.predict(X_test)   # evaluate predictions   score = mean_absolute_error(y_test, yhat)   print('>%.3f' % score)   scores.append(score)  # summarize all scores  print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

運(yùn)行示例將在評(píng)估過(guò)程的每次迭代中報(bào)告模型性能,并在運(yùn)行結(jié)束時(shí)報(bào)告MAE的平均值和標(biāo)準(zhǔn)偏差。

注意:由于算法或評(píng)估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會(huì)有所不同??紤]運(yùn)行該示例幾次并比較平均結(jié)果。

在這種情況下,我們可以看到MLP模型的MAE約為38.913。

我們將使用此結(jié)果作為基準(zhǔn),以查看是否可以實(shí)現(xiàn)更好的性能。

>27.314  >69.577  >20.891  >14.810  >13.412  >69.540  >25.612  >49.508  >35.769  >62.696  Mean MAE: 38.913 (21.056)

首先,讓我們嘗試在原始數(shù)據(jù)集上評(píng)估更深的模型,以查看其性能是否比基準(zhǔn)模型更好。

# define model  model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))  model.add(Dense(8, activation='relu', kernel_initializer='he_normal')) model.add(Dense(1))  # compile the model  model.compile(optimizer='adam', loss='mse')  # fit the model  model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0)

完整實(shí)例如下:

# k-fold cross-validation of deeper model for the auto insurance regression dataset  from numpy import mean  from numpy import std  from pandas import read_csv  from sklearn.model_selection import KFold  from sklearn.metrics import mean_absolute_error  from tensorflow.keras import Sequential  from tensorflow.keras.layers import Dense  from matplotlib import pyplot  # load the dataset  path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  df = read_csv(path, header=None)  # split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # prepare cross validation  kfold = KFold(10)  # enumerate splits  scores = list()  for train_ix, test_ix in kfold.split(X, y):   # split data   X_train, X_test, y_train, y_test = X[train_ix], X[test_ix], y[train_ix], y[test_ix]   # determine the number of input features   n_features = X.shape[1]   # define model   model = Sequential()   model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))   model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))   model.add(Dense(1))  # compile the model   model.compile(optimizer='adam', loss='mse')   # fit the model   model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0)   # predict test set   yhat = model.predict(X_test)   # evaluate predictions  score = mean_absolute_error(y_test, yhat)   print('>%.3f' % score)   scores.append(score)  # summarize all scores  print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

運(yùn)行報(bào)告運(yùn)行結(jié)束時(shí)MAE的平均值和標(biāo)準(zhǔn)偏差。

注意:由于算法或評(píng)估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會(huì)有所不同??紤]運(yùn)行該示例幾次并比較平均結(jié)果。

在這種情況下,我們可以看到MLP模型獲得的MAE約為35.384,這略好于獲得MAE約為38.913的基線模型。

Mean MAE: 35.384 (14.951)

接下來(lái),讓我們嘗試使用與上一節(jié)相同的對(duì)輸入和目標(biāo)變量進(jìn)行冪變換的模型。

下面列出了完整的示例。

# k-fold cross-validation of deeper model with data transforms  from numpy import mean  from numpy import std  from pandas import read_csv  from sklearn.model_selection import KFold  from sklearn.metrics import mean_absolute_error  from sklearn.preprocessing import PowerTransformer  from tensorflow.keras import Sequential  from tensorflow.keras.layers import Dense  from matplotlib import pyplot  # load the dataset path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  df = read_csv(path, header=None)  # split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # prepare cross validation  kfold = KFold(10)  # enumerate splits  scores = list()  for train_ix, test_ix in kfold.split(X, y):   # split data   X_train, X_test, y_train, y_test = X[train_ix], X[test_ix], y[train_ix], y[test_ix]   # ensure target is a 2d array   y_train, y_test = y_train.reshape((len(y_train),1)), y_test.reshape((len(y_test),1))   # prepare input data   pt1 = PowerTransformer()   pt1.fit(X_train)   X_train = pt1.transform(X_train)  X_test = pt1.transform(X_test)   # prepare target   pt2 = PowerTransformer()   pt2.fit(y_train)   y_train = pt2.transform(y_train)   y_test = pt2.transform(y_test)   # determine the number of input features   n_features = X.shape[1]   # define model   model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))   model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))   model.add(Dense(1))   # compile the model   model.compile(optimizer='adam', loss='mse')   # fit the model   model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0)   # predict test set   yhat = model.predict(X_test)   # inverse transforms   y_test = pt2.inverse_transform(y_test)   yhat = pt2.inverse_transform(yhat)   # evaluate predictions   score = mean_absolute_error(y_test, yhat)   print('>%.3f' % score)   scores.append(score)  # summarize all scores  print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

運(yùn)行報(bào)告運(yùn)行結(jié)束時(shí)MAE的平均值和標(biāo)準(zhǔn)偏差。

注意:由于算法或評(píng)估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會(huì)有所不同。考慮運(yùn)行該示例幾次并比較平均結(jié)果。

在這種情況下,我們可以看到MLP模型獲得的MAE約為37.371,這比基準(zhǔn)模型好,但不比更深的基準(zhǔn)模型好。

也許這種轉(zhuǎn)變沒(méi)有我們最初認(rèn)為的那樣有用。

Mean MAE: 37.371 (29.326)

另一種變換是對(duì)輸入變量和目標(biāo)變量進(jìn)行規(guī)范化。

這意味著將每個(gè)變量的值縮放到[0,1]范圍。我們可以使用MinMaxScaler來(lái)實(shí)現(xiàn)。例如:

# prepare input data  pt1 = MinMaxScaler()  pt1.fit(X_train)  X_train = pt1.transform(X_train)  X_test = pt1.transform(X_test)  # prepare target  pt2 = MinMaxScaler()  pt2.fit(y_train) y_train = pt2.transform(y_train)  y_test = pt2.transform(y_test)

結(jié)合在一起,下面列出了使用數(shù)據(jù)規(guī)范化評(píng)估更深層MLP的完整示例。

# k-fold cross-validation of deeper model with normalization transforms  from numpy import mean  from numpy import std  from pandas import read_csv  from sklearn.model_selection import KFold  from sklearn.metrics import mean_absolute_error  from sklearn.preprocessing import MinMaxScaler  from tensorflow.keras import Sequential  from tensorflow.keras.layers import Dense  from matplotlib import pyplot  # load the dataset  path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  df = read_csv(path, header=None)  # split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # prepare cross validation  kfold = KFold(10)  # enumerate splits  scores = list()  for train_ix, test_ix in kfold.split(X, y):   # split data   X_train, X_test, y_train, y_test = X[train_ix], X[test_ix], y[train_ix], y[test_ix]   # ensure target is a 2d array   y_train, y_test = y_train.reshape((len(y_train),1)), y_test.reshape((len(y_test),1))   # prepare input data   pt1 = MinMaxScaler()   pt1.fit(X_train)   X_train = pt1.transform(X_train)   X_test = pt1.transform(X_test)   # prepare target   pt2 = MinMaxScaler()   pt2.fit(y_train)   y_train = pt2.transform(y_train)   y_test = pt2.transform(y_test)   # determine the number of input features   n_features = X.shape[1]   # define model   model = Sequential()   model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))   model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))   model.add(Dense(1))   # compile the model   model.compile(optimizer='adam', loss='mse')   # fit the model   model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0)   # predict test set  yhat = model.predict(X_test)   # inverse transforms   y_test = pt2.inverse_transform(y_test)   yhat = pt2.inverse_transform(yhat)   # evaluate predictions   score = mean_absolute_error(y_test, yhat)   print('>%.3f' % score)   scores.append(score)  # summarize all scores  print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

運(yùn)行報(bào)告運(yùn)行結(jié)束時(shí)MAE的平均值和標(biāo)準(zhǔn)偏差。

注意:由于算法或評(píng)估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會(huì)有所不同??紤]運(yùn)行該示例幾次并比較平均結(jié)果。

在這種情況下,我們可以看到MLP模型獲得的MAE約為30.388,這比我們迄今為止嘗試過(guò)的任何其他配置都要好。

Mean MAE: 30.388 (14.258)

我們可以繼續(xù)測(cè)試模型架構(gòu)的替代配置(更多或更少的節(jié)點(diǎn)或?qū)樱?,學(xué)習(xí)超參數(shù)(更多或更少的批處理)以及數(shù)據(jù)轉(zhuǎn)換。

我將其保留為練習(xí);讓我知道你發(fā)現(xiàn)了什么。您可以獲得更好的結(jié)果嗎?

將您的結(jié)果發(fā)表在下面的評(píng)論中,我很樂(lè)意看到您所得到的。

接下來(lái),讓我們看看如何擬合最終模型并使用它進(jìn)行預(yù)測(cè)。

最終模型和做出預(yù)測(cè)

選擇模型配置后,我們可以在所有可用數(shù)據(jù)上訓(xùn)練最終模型,并使用它對(duì)新數(shù)據(jù)進(jìn)行預(yù)測(cè)。在這種情況下,我們將使用數(shù)據(jù)標(biāo)準(zhǔn)化的更深層模型作為最終模型。這意味著,如果我們想將模型保存到文件中,則必須保存模型本身(用于進(jìn)行預(yù)測(cè)),輸入數(shù)據(jù)的轉(zhuǎn)換(用于新的輸入數(shù)據(jù))和目標(biāo)變量的轉(zhuǎn)換(用于新預(yù)測(cè))。盡管可以在整個(gè)數(shù)據(jù)集而不是數(shù)據(jù)集的訓(xùn)練子集上,但我們?nèi)钥梢韵褚郧耙粯訙?zhǔn)備數(shù)據(jù)并擬合模型。

# split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # ensure target is a 2d array  yy = y.reshape((len(y),1))  # prepare input data  pt1 = MinMaxScaler()  pt1.fit(X)  X = pt1.transform(X)  # prepare target  pt2 = MinMaxScaler()  pt2.fit(y)  y = pt2.transform(y)  # determine the number of input features  n_features = X.shape[1]  # define model  model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))  model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))  model.add(Dense(1))  # compile the model  model.compile(optimizer='adam', loss='mse')

然后,我們可以使用此模型對(duì)新數(shù)據(jù)進(jìn)行預(yù)測(cè)。首先,我們可以定義一行新數(shù)據(jù),這只是該數(shù)據(jù)集的一個(gè)變量。

# define a row of new data  row = [13]

然后,我們可以轉(zhuǎn)換此新數(shù)據(jù),以準(zhǔn)備用作模型的輸入。

# transform the input data  X_new = pt1.transform([row])

然后我們可以做出預(yù)測(cè)。

# make prediction  yhat = model.predict(X_new)

然后將預(yù)測(cè)的變換反轉(zhuǎn),以便我們可以按正確的比例使用或解釋結(jié)果。

# invert transform on prediction  yhat = pt2.inverse_transform(yhat)

在這種情況下,我們將僅報(bào)告預(yù)測(cè)。

# report prediction  print('f(%s) = %.3f' % (row, yhat[0]))

綜上所述,下面列出了為汽車保險(xiǎn)數(shù)據(jù)集擬合最終模型并使用其對(duì)新數(shù)據(jù)進(jìn)行預(yù)測(cè)的完整示例。

# fit a final model and make predictions on new data.  from pandas import read_csv  from sklearn.model_selection import KFold  from sklearn.metrics import mean_absolute_error  from sklearn.preprocessing import MinMaxScaler  from tensorflow.keras import Sequential  from tensorflow.keras.layers import Dense  # load the dataset  path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'  df = read_csv(path, header=None)  # split into input and output columns  X, y = df.values[:, :-1], df.values[:, -1]  # ensure target is a 2d array  yy = y.reshape((len(y),1))  # prepare input data  pt1 = MinMaxScaler()  pt1.fit(X)  X = pt1.transform(X)  # prepare target  pt2 = MinMaxScaler()  pt2.fit(y)  y = pt2.transform(y)  # determine the number of input features  n_features = X.shape[1]  # define model  model = Sequential()  model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))  model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))  model.add(Dense(1))  # compile the model  model.compile(optimizer='adam', loss='mse')  # fit the model  model.fit(X, y, epochs=200, batch_size=8, verbose=0)  # define a row of new data  row = [13]  # transform the input data  X_new = pt1.transform([row])  # make prediction  yhat = model.predict(X_new)  # invert transform on prediction  yhat = pt2.inverse_transform(yhat) # report prediction  print('f(%s) = %.3f' % (row, yhat[0]))

運(yùn)行示例可以使模型適合整個(gè)數(shù)據(jù)集,并為單行新數(shù)據(jù)做出預(yù)測(cè)。

注意:由于算法或評(píng)估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會(huì)有所不同。考慮運(yùn)行該示例幾次并比較平均結(jié)果。

在這種情況下,我們可以看到輸入13導(dǎo)致輸出62(千瑞典克朗)。

f([13]) = 62.595

到此,相信大家對(duì)“怎么用Python神經(jīng)網(wǎng)絡(luò)預(yù)測(cè)汽車保險(xiǎn)支出”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI