友快網

導航選單

神經網路與傳統統計方法的簡單對比

傳統的統計方法如OLS假設變數之間符合簡單的線性關係或者高階線性關係進行擬合(或函式逼近),然而,並不是所有關係都是簡單的線性關係或者高階線性關係,這時就需要藉助神經網路 (neural network,NN)等方法來進行建模。神經網路可以在不需要知道函式關係具體形式的條件下近似各種函式關係。

預測模型

1。 scikit-learn

下例使用scikit-learn 庫中的 MLPRegressor 類,該類可用 DNN 進行迴歸估計。DNN 有時也被稱為多層感知器(multi-layer perceptron,MLP)。從最終的MSE來看,結果並不完美,但是對一個配置簡單的模型來說,效果已經非常不錯了。

from sklearn。neural_network import MLPRegressor# 生成樣本資料def f(x): return 2 * x ** 2 - x ** 3 / 3x = np。linspace(-2, 4, 25)y = f(x)# 例項化 MLPRegressor 物件model = MLPRegressor(hidden_layer_sizes=3 * [256], learning_rate_init=0。03, max_iter=5000)# 擬合或學習步驟。model。fit(x。reshape(-1, 1), y)# 預測步驟y_ = model。predict(x。reshape(-1, 1))MSE = ((y - y_) ** 2)。mean()MSE# Out:# 0。003216321978018745

樣本和預測結果圖

plt。figure(figsize=(10, 6))plt。plot(x, y, ‘ro’, label=‘sample data’)plt。plot(x, y_, lw=3。0, label=‘dnn estimation’)plt。legend();

樣本資料和基於神經網路的預測

2。 Keras

下一個示例使用了 Keras 深度學習軟體包中的序列模型 Sequential,對該模型每輪進行100次迭代訓練,重複5輪。每輪訓練之後,我們將更新並繪製由神經網路預測的近似值。如圖顯示,隨著每一輪訓練的近似值的準確率逐漸提高,MSE值逐漸降低。與之前的模型相似,最終結果並不完美,但是鑑於模型的簡單性,它還是不錯的。

import tensorflow as tftf。random。set_seed(100)from keras。layers import Densefrom keras。models import Sequential# 例項化 Sequential 模型物件model = Sequential()# 新增採用整流線性單元(ReLU)啟用函式的全連線層作為隱藏層model。add(Dense(256, activation=‘relu’, input_dim=1))# 新增線性啟用的輸出層model。add(Dense(1, activation=‘linear’))# 編譯模型物件model。compile(loss=‘mse’, optimizer=‘rmsprop’)# 原始樣本資料圖plt。figure(figsize=(10, 6))plt。plot(x, y, ‘ro’, label=‘sample data’)# 迭代訓練指定次數for _ in range(1, 6): # 訓練神經網路 model。fit(x, y, epochs=100, verbose=False) # 預測近似值 y_ = model。predict(x) # 計算當前的 MSE MSE = ((y - y_。flatten()) ** 2)。mean() print(f‘round={_} | MSE={MSE:。5f}’) # 繪製當前的近似結果 plt。plot(x, y_, ‘——’, label=f‘round={_}’)plt。legend();# Out:# round=1 | MSE=3。87256# round=2 | MSE=0。92527# round=3 | MSE=0。28527# round=4 | MSE=0。13191# round=5 | MSE=0。09568

樣本資料和多輪訓練後得到的預測值

從以上兩個示例來看,相比OLS迴歸完美的復刻原有方程的係數,神經網路只能提供一個近似的預測,那麼為什麼還要使用神經網路呢?假設我們的資料不是透過預定義好的數學函式生成的,而是隨機產生的特徵和標籤呢?下面我們再看一個例子,當然該示例僅用於說明,不具有實際意義。

# 隨機生成測試資料np。random。seed(0)x = np。linspace(-1, 1)y = np。random。random(len(x)) * 2 - 1# 用不同的多次項OLS迴歸進行擬合plt。figure(figsize=(10, 6))plt。plot(x, y, ‘ro’, label=‘sample data’)for deg in [1, 5, 9, 11, 13, 15]: reg = np。polyfit(x, y, deg=deg) y_ = np。polyval(reg, x) MSE = ((y - y_) ** 2)。mean() print(f‘deg={deg:2d} | MSE={MSE:。5f}’) plt。plot(x, np。polyval(reg, x), label=f‘deg={deg}’)plt。legend();# Out:# deg= 1 | MSE=0。28153# deg= 5 | MSE=0。27331# deg= 9 | MSE=0。25442# deg=11 | MSE=0。23458# deg=13 | MSE=0。22989# deg=15 | MSE=0。21672

隨機樣本資料和 OLS 迴歸線

明顯可見,OLS 迴歸的效果並不理想。OLS迴歸假設我們可以透過有限個(基於多項式的)基函式的組合來逼近目標函式,由於樣本資料集是隨機生成的,因此在這種情況下,OLS 迴歸效果不佳。下面我們用神經網路來試下。

model = Sequential()model。add(Dense(256, activation=‘relu’, input_dim=1))# 此處新增3個隱藏層for _ in range(3): model。add(Dense(256, activation=‘relu’))model。add(Dense(1, activation=‘linear’))model。compile(loss=‘mse’, optimizer=‘rmsprop’)# 顯示神經網路架構以及可訓練引數的數量model。summary()# Out:# Model: “sequential_1”# _________________________________________________________________# Layer (type) Output Shape Param # # =================================================================# dense_2 (Dense) (None, 256) 512 # # dense_3 (Dense) (None, 256) 65792 # # dense_4 (Dense) (None, 256) 65792 # # dense_5 (Dense) (None, 256) 65792 # # dense_6 (Dense) (None, 1) 257 # # =================================================================# Total params: 198,145# Trainable params: 198,145# Non-trainable params: 0# _________________________________________________________________%%timeplt。figure(figsize=(10, 6))plt。plot(x, y, ‘ro’, label=‘sample data’)for _ in range(1, 8): model。fit(x, y, epochs=500, verbose=False) y_ = model。predict(x) MSE = ((y - y_。flatten()) ** 2)。mean() print(f‘round={_} | MSE={MSE:。5f}’) plt。plot(x, y_, ‘——’, label=f‘round={_}’)plt。legend();# Out:# round=1 | MSE=0。13428# round=2 | MSE=0。08515# round=3 | MSE=0。05811# round=4 | MSE=0。04389# round=5 | MSE=0。03376# round=6 | MSE=0。00722# round=7 | MSE=0。00644# CPU times: user 22。8 s, sys: 3。97 s, total: 26。8 s# Wall time: 12。1 s

隨機樣本資料和神經網路預測

儘管預測結果並不完美,但預測結果明顯好於OLS。神經網路架構有近200000個可訓練的引數(權重),與OLS 迴歸(最多使用15+1個引數)相比,這提供了相對較高的靈活性。

分類任務

神經網路也可以很容易地用於分類任務。考慮以下基於 Keras 實現神經網路分類,二元特徵資料和二元標籤資料是隨機生成的。建模方面的主要調整是將輸出層的啟用函式從linear更改為sigmoid。雖然分類效果並不完美,但是也達到了很高的準確率。

# 建立隨機特徵資料和標籤資料f = 5n = 10np。random。seed(124812)x = np。random。randint(0, 2, (n, f))y = np。random。randint(0, 2, n)model = Sequential()model。add(Dense(256, activation=‘relu’, input_dim=f))# 輸出層的啟用函式為 sigmoidmodel。add(Dense(1, activation=‘sigmoid’))# 損失函式為 binary_crossentropymodel。compile(loss=‘binary_crossentropy’, optimizer=‘rmsprop’, metrics=[‘acc’])model。fit(x, y, epochs=50, verbose=False)y_ = np。where(model。predict(x)。flatten() > 0。5, 1, 0)# 預測值與標籤資料的比較結果y == y_# Out:# array([ True, True, True, True, True, True, True, False, True, True])# 繪製每輪訓練的損失函式和準確率值res = pd。DataFrame(model。history。history)res。plot(figsize=(10, 6));

分類準確率及損失與訓練輪數的關係

由以上示例說明,對比傳統統計方法,神經網路的一些基本特徵:

問題無關性

在給定一組特徵值的情況下,神經網路方法的效能與需要預測或者分類的具體標籤值是無關的。而統計方法(比如OLS 迴歸)可能對較小的一組問題表現良好,對其他問題則表現不太好或根本沒有效果。

2。 增量學習

給定一個用來度量成功的目標,神經網路中的最佳權重是基於隨機初始化和增量改進而逐步學習得到的。這些增量改進是在考慮預測值和樣本標籤值之間的差異後,透過神經網路反向傳播權重更新來實現的。

3。 通用函式逼近器

有嚴格的數學定理表明神經網路(即使只有一個隱藏層)幾乎可以逼近任何函式。

上一篇:汪小菲再開直播氣色差,話語裡不滿老媽張蘭,還愛著大S
下一篇:千名百歲老人調查:長壽的共性被找到,除了運動、心態,還有2點