Callback in Keras

Introduzione al Deep Learning con Keras

Miguel Esteban

Data Scientist & Founder

Cos'è un callback?

Introduzione al Deep Learning con Keras

Callback in Keras

Introduzione al Deep Learning con Keras

Un callback che ti mancava

# Allena un modello e salva il suo history
history = model.fit(X_train, y_train,
                    epochs=100,
                    metrics=['accuracy'])

print(history.history['loss'])
[0.6753975939750672, ..., 0.3155936544282096]
print(history.history['accuracy'])
[0.7030952412741525, ..., 0.8604761900220599]
Introduzione al Deep Learning con Keras

Un callback che ti mancava

# Allena un modello e salva il suo history
history = model.fit(X_train, y_train,
                    epochs=100,
                    validation_data=(X_test, y_test),
                    metrics=['accuracy'])        

print(history.history['val_loss'])
[0.7753975939750672, ..., 0.4155936544282096]
print(history.history['val_accuracy'])
[0.6030952412741525, ..., 0.7604761900220599]
Introduzione al Deep Learning con Keras

Grafici dell'history

# Grafica accuracy di train vs test per epoca
plt.figure()

# Usa le metriche di history plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy'])
# Migliora l'estetica plt.title('Model accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Test']) plt.show()

Introduzione al Deep Learning con Keras

Grafici dell'history

Introduzione al Deep Learning con Keras

Early stopping

# Importa early stopping dai callback di keras
from tensorflow.keras.callbacks import EarlyStopping

# Istanzia un callback di early stopping early_stopping = EarlyStopping(monitor='val_loss', patience=5)
# Allena il modello con il callback model.fit(X_train, y_train, epochs=100, validation_data=(X_test, y_test), callbacks = [early_stopping])
Introduzione al Deep Learning con Keras

Model checkpoint

# Importa model checkpoint dai callback di keras
from keras.callbacks import ModelCheckpoint

# Istanzia un callback di model checkpoint model_save = ModelCheckpoint('best_model.hdf5', save_best_only=True)
# Allena il modello con il callback model.fit(X_train, y_train, epochs=100, validation_data=(X_test, y_test), callbacks = [model_save])
Introduzione al Deep Learning con Keras

Esercitiamoci!

Introduzione al Deep Learning con Keras

Preparing Video For Download...