Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To obtain the optimal model utilizing the EarlyStopping callback feature in Keras, follow the steps below:

  1. Import the necessary libraries:
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
  1. Create a sequential Keras model:
model = Sequential()
model.add(Dense(32, input_shape=(10,), activation='relu'))
model.add(Dense(16, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
  1. Compile the model with the necessary parameters:
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  1. Define the EarlyStopping callback with the necessary parameters:
early_stopping = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)
  1. Train the model with the training dataset, including the EarlyStopping callback:
model.fit(X_train, y_train, epochs=50, batch_size=64, validation_data=(X_val, y_val), callbacks=[early_stopping])
  1. Evaluate the model with the testing dataset:
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.