簡體   English   中英

在神經網絡中尋找最佳學習率和時期

[英]Finding the optimum learning rate & epochs in a Neural Network

我創建了一個單層神經網絡,它有兩個輸出(每個類一個,0 或 1),並使用 sigmoid 方法和 SGD 優化器進行訓練。 我還訓練了沒有任何隱藏層的神經網絡。 此外,我已經使用帶有 4 個分割的 StratifiedKFold 驗證了模型的性能。 訓練的模型設計為 lr=0.1 和 epochs=150,但是,我不知道這些值是否正在優化模型。 出於這個原因,我想運行 20 種學習率參數和時期的組合,以查看最准確的結果,以及我正在獲得這些參數的哪種組合。 在限制之下:

  • epochs:10 到 150 之間的值
  • 學習率:0.01 到 1 之間的值

請看下面的代碼:

from sklearn.model_selection import StratifiedKFold
from keras.models import Sequential
from keras.layers.core import Dense
from keras import layers
from keras.optimizers import SGD
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score

#Function to create the NN model
def create_model():    
    #Neural Network model
    ann = Sequential()
    #Number of columns of training dataset
    n_cols = x_train.shape[1]
    #Output
    ann.add(Dense(units=1,activation='sigmoid',input_shape=(n_cols,)))
    #SGD Optimizer
    sgd = SGD(lr=0.1)
    #Compile with SGD optimizer and binary_crossentropy
    ann.compile(optimizer=sgd,
                loss='binary_crossentropy',
                metrics=['accuracy'])
    return ann

#Creating the model
model=KerasClassifier(build_fn=create_model,epochs=150,batch_size=10,verbose=0)
#Evaluating the model using StratifiedKFold
kfold = StratifiedKFold(n_splits=4, shuffle=True, random_state=2)
results=cross_val_score(model,x_train,y_train,cv=kfold)
#Accuracies
print(results)

為了創建由學習率和 epochs 形成的 20 個組合,首先,我創建了 lr 和 epochs 的隨機值:

   #Epochs
   epo = np.random.randint(10,150)
   #Learning Rate
   learn = np.random.randint(0.01,1)

我的問題是我不知道如何將其放入 NN 的代碼中,以便找到哪個組合可以提供模型的最佳准確度。

無需優化您可以輕松使用提前停止的時代數,當您的損失或准確性沒有改善時,它將停止,因此只需將您的時代設置一個大數字(例如 300 )並添加:

keras.callbacks.callbacks.EarlyStopping(monitor='val_loss', min_delta=0.1)

您還可以通過以下方式調用最佳權重(就在模型開始過度擬合之前):

restore_best_weights=True

首先在create_model()函數中,您定義了將學習率作為參數傳遞給的優化器:

#SGD Optimizer
sgd = SGD(lr=0.1)

這是優化過程的起始學習率,從這一點優化器處理最優學習率。 盡管如此,您可以在循環中傳遞多個起始學習率,重復調用 create_model create_model()函數並將學習率參數傳遞給該函數。

此外,正如 parsa 提到的,選擇正確的紀元數是基於驗證結果,它顯示了您的模型在哪里過擬合。 關鍵是,紀元數達到了最佳狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM