提早停止:讓最佳化更有效率
現在你已經知道如何在最佳化過程中監控模型效能,就可以使用提早停止,在最佳化不再有幫助時自動停止。由於在沒有幫助時會自動停止,你也可以像影片中 Dan 示範的那樣,在呼叫 .fit() 時將 epochs 設為較大的數值。
你要最佳化的模型已指定為 model。和之前一樣,資料已預先載入為 predictors 與 target。
本練習屬於課程
Python 深度學習入門
練習說明
- 從
tensorflow.keras.callbacks匯入EarlyStopping。 - 編譯模型,再次使用
'adam'作為optimizer,'categorical_crossentropy'作為損失函式,並設定metrics=['accuracy']以在每個 epoch 查看準確率。 - 建立名為
early_stopping_monitor的EarlyStopping物件。將EarlyStopping()的patience參數設為2,當驗證損失連續 2 個 epoch 沒有改善時就停止最佳化。 - 使用
predictors與target擬合模型。將epochs設為30,並使用0.3的驗證切分。此外,將[early_stopping_monitor]傳入callbacks參數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import EarlyStopping
____
# Save the number of columns in predictors: n_cols
n_cols = predictors.shape[1]
input_shape = (n_cols,)
# Specify the model
model = Sequential()
model.add(Dense(100, activation='relu', input_shape = input_shape))
model.add(Dense(100, activation='relu'))
model.add(Dense(2, activation='softmax'))
# Compile the model
____
# Define early_stopping_monitor
early_stopping_monitor = ____
# Fit the model
____