1 | initial version |
To obtain the optimal model utilizing the EarlyStopping callback feature in Keras, follow the steps below:
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
model = Sequential()
model.add(Dense(32, input_shape=(10,), activation='relu'))
model.add(Dense(16, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
model.fit(X_train, y_train, epochs=50, batch_size=64, validation_data=(X_val, y_val), callbacks=[early_stopping])
loss, accuracy = model.evaluate(X_test, y_test)
print(f'Testing accuracy: {accuracy}')
In this code, the EarlyStopping callback is set to monitor the validation loss and terminate the training process if there is no improvement in the validation loss after three epochs. The restorebestweights parameter ensures that the model's weights are set to the ones that produced the best validation loss during the training process.