Skip to content
TensorFlow

Save and Load

Persist models in SavedModel and Keras formats.

By EZ4Code Team
saveload

Code

import tensorflow as tf

model = tf.keras.Sequential([tf.keras.layers.Dense(2, input_shape=(4,))])

# Keras native format (single file)
model.save("model.keras")
loaded = tf.keras.models.load_model("model.keras")

# SavedModel format (directory, deployable to TF Serving)
model.export("saved_model")

# Weights only
model.save_weights("weights.weights.h5")
new_model = tf.keras.Sequential([tf.keras.layers.Dense(2, input_shape=(4,))])
new_model.load_weights("weights.weights.h5")

# Save architecture as JSON
json_config = model.to_json()
restored = tf.keras.models.model_from_json(json_config)

Explanation

The .keras format is the recommended single-file archive for models and weights; SavedModel is a directory format suited to deployment with TF Serving. save_weights and load_weights move only parameters between architectures that match exactly. to_json serializes the architecture so it can be reconstructed later.

More TensorFlow Snippets