To save a trained Keras model, you can use the ‘model.save()‘ method, which stores the model architecture, weights, and optimizer state in a single file format called HDF5.
Here’s an example:
from tensorflow import keras
# Create and train a Keras model
model = keras.models.Sequential([
keras.layers.Dense(10, input_shape=(20,), activation="relu"),
keras.layers.Dense(1, activation="sigmoid")
])
model.compile(loss="binary_crossentropy", optimizer="sgd")
model.fit(x_train, y_train, epochs=10)
# Save the trained model
model.save("my_model.h5")
To load a saved model, you can use the ‘keras.models.load_model()‘ method, which loads the architecture, weights, and optimizer state from the HDF5 file.
Here’s an example:
# Load a saved Keras model
model = keras.models.load_model("my_model.h5")
# Make predictions with the loaded model
y_pred = model.predict(x_test)
Note that when you load a model, you should use the same version of Keras and TensorFlow that were used to save the model, otherwise loading the model may fail.