0
0
TensorFlowml~5 mins

SavedModel format in TensorFlow

Choose your learning style9 modes available
Introduction
SavedModel format lets you save your trained TensorFlow model so you can use it later without retraining.
You want to save a model after training to use it later for predictions.
You need to share your model with others or deploy it to a server.
You want to load a model in a different program or environment.
You want to keep a backup of your model during development.
You want to serve your model in production with TensorFlow Serving.
Syntax
TensorFlow
model.save('path_to_folder')

# To load the model later:
loaded_model = tf.keras.models.load_model('path_to_folder')
The 'path_to_folder' is a directory where the model files will be saved.
SavedModel format saves the entire model architecture, weights, and optimizer state.
Examples
Saves the model in a folder named 'my_model' in SavedModel format.
TensorFlow
model.save('my_model')
Loads the saved model from the 'my_model' folder.
TensorFlow
loaded_model = tf.keras.models.load_model('my_model')
Saves the model inside a nested folder structure.
TensorFlow
model.save('models/house_price_predictor')
Sample Model
This code trains a simple model, saves it in SavedModel format, loads it back, and makes predictions to show it works.
TensorFlow
import tensorflow as tf
import numpy as np

# Create a simple model
model = tf.keras.Sequential([
    tf.keras.layers.Dense(5, activation='relu', input_shape=(3,)),
    tf.keras.layers.Dense(1)
])

model.compile(optimizer='adam', loss='mse')

# Generate some dummy data
x_train = np.random.random((10, 3))
y_train = np.random.random((10, 1))

# Train the model
model.fit(x_train, y_train, epochs=3, verbose=0)

# Save the model
model.save('saved_model_example')

# Load the model
loaded_model = tf.keras.models.load_model('saved_model_example')

# Predict with the loaded model
predictions = loaded_model.predict(x_train)

print('Predictions shape:', predictions.shape)
print('First prediction:', predictions[0])
OutputSuccess
Important Notes
SavedModel format saves everything needed to resume training or do inference.
The saved folder contains assets, variables, and a saved_model.pb file.
You can use this format to deploy models on different platforms easily.
Summary
SavedModel format stores the full TensorFlow model for later use.
It is easy to save and load models with model.save() and tf.keras.models.load_model().
This format is great for sharing, deploying, and backing up models.