How to Save a Keras Model

  • Post category:Keras / Python

Saving your trained Keras models is crucial for later use, deployment, or sharing with others. Here’s how to save a Keras model to disk.

# Import necessary libraries
import keras
from keras.models import Sequential
from keras.layers import Dense

# Create a simple Keras model (for demonstration)
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))

# Compile and train your model (skip if you already have a trained model)

# Save the model to a file
model.save('my_keras_model.h5')

print("Model saved successfully!")

Now you’ve learned how to save a Keras model as an HDF5 file (‘my_keras_model.h5’ in this example).