Principle:Tensorflow Tfjs Python Model Export
| Knowledge Sources | |
|---|---|
| Domains | Model_Persistence, Deployment |
| Implementation | Implementation:Tensorflow_Tfjs_Tf_Saved_Model_Save |
| Type | External Tool Doc (Python TF/Keras, not in this JS repo) |
| Last Updated | 2026-02-10 00:00 GMT |
Overview
Exporting trained Python TensorFlow/Keras models into a portable format (SavedModel or HDF5) that can be converted for other runtimes. Model export is the process of serializing a trained model from the training environment into a standardized file format, making it independent of the original training code and ready for cross-platform deployment.
Theory
SavedModel Format
The TensorFlow SavedModel format is the recommended serialization format for TensorFlow 2.x models. It stores the complete model as a self-contained directory with the following structure:
- saved_model.pb (or saved_model.pbtxt): The computation graph serialized as a protocol buffer. This includes all tf.function-traced computations, variable definitions, and serving signatures.
- variables/: A subdirectory containing checkpoint shards that hold the trained weight values. Weights are stored in a binary format optimized for efficient loading.
- assets/ (optional): Additional files needed by the model at inference time, such as vocabulary files or lookup tables.
- fingerprint.pb (TF 2.12+): A fingerprint of the model for integrity verification.
SavedModel preserves the full computation graph including custom operations, control flow, and resource management. It supports serving signatures, which define named input/output mappings for deployment via TensorFlow Serving, TensorFlow Lite, or TensorFlow.js.
Keras HDF5 Format
The older HDF5 format (.h5 extension) stores:
- Model architecture as a JSON string embedded in the HDF5 file attributes
- Trained weights as HDF5 datasets organized by layer name
- Optimizer state (if saved during training) for resuming training
HDF5 is a simpler format but has limitations: it does not preserve custom objects without explicit registration, and it cannot store tf.function traces or arbitrary TensorFlow operations outside the Keras layer abstraction.
Interchange Representations
Both formats serve as interchange representations enabling cross-platform deployment. The key insight is that model export decouples the trained model from:
- The training code (Python scripts, data pipelines, training loops)
- The training environment (GPU drivers, library versions, OS)
- The training framework version (forward compatibility within major versions)
This decoupling is what enables the downstream conversion pipeline: a model exported on a GPU training cluster can be converted and deployed in a browser environment without any of the original training dependencies.
Format Selection Guidelines
| Criterion | SavedModel | Keras HDF5 |
|---|---|---|
| Computation graph | Full TF graph preserved | Keras architecture only |
| Custom ops | Supported | Requires registration |
| Serving signatures | Yes | No |
| TF.js conversion | Graph model or Layers model | Layers model only |
| File structure | Directory | Single file |
| Recommended for | Production deployment | Simple Keras models |
Signature
# SavedModel export (recommended)
tf.saved_model.save(obj, export_dir, signatures=None, options=None)
# Keras .save() — saves as SavedModel directory (TF 2.x default)
model.save('path/to/model')
# Keras .save() — saves as HDF5 file (explicit extension)
model.save('path/to/model.h5')
# Keras save_weights — weights only
model.save_weights('path/to/weights.h5')
Inputs and Outputs
Inputs
- A trained Python TensorFlow or Keras model — either a tf.keras.Model subclass, a Sequential model, a Functional API model, or a raw tf.Module with tf.function-decorated methods
- An export directory path (for SavedModel) or file path (for HDF5) where the serialized model will be written
- Optional signatures dictionary mapping signature keys to concrete tf.function traces (SavedModel only)
- Optional SaveOptions for advanced configuration such as experimental features or custom function tracing
Outputs
- SavedModel directory containing:
- saved_model.pb — serialized computation graph as protocol buffer
- variables/ — directory with checkpoint shards (variables.index + variables.data-00000-of-NNNNN)
- assets/ — optional additional files
- OR a Keras HDF5 file (.h5) containing architecture JSON and weight datasets
Example
import tensorflow as tf
# Build and train a Keras model
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
model.fit(x_train, y_train, epochs=5)
# Export as SavedModel (recommended for TF.js graph model conversion)
model.save('/tmp/my_saved_model')
# Export as HDF5 (for TF.js layers model conversion)
model.save('/tmp/my_model.h5')
# Export with explicit serving signature
@tf.function(input_signature=[tf.TensorSpec(shape=[None, 784], dtype=tf.float32)])
def serve(x):
return model(x)
tf.saved_model.save(model, '/tmp/my_saved_model_with_sig',
signatures={'serving_default': serve})
Relationship to TensorFlow.js Conversion
Model export is Step 1 of the end-to-end deployment pipeline:
- Export the trained model (this principle)
- Install the tensorflowjs converter
- Convert the exported model to TF.js format
- Host the converted model files
- Load the model in JavaScript
- Run inference in the browser or Node.js
The export format determines which conversion path is available:
- SavedModel → tfjs_graph_model (via tensorflowjs_converter --input_format=tf_saved_model)
- SavedModel → tfjs_layers_model (via tensorflowjs_converter --input_format=keras_saved_model)
- Keras HDF5 → tfjs_layers_model (via tensorflowjs_converter --input_format=keras)
See Also
- Implementation:Tensorflow_Tfjs_Tf_Saved_Model_Save — Concrete implementation of this principle
- Principle:Tensorflow_Tfjs_Converter_Installation — Next step: installing the conversion toolchain
- Principle:Tensorflow_Tfjs_Model_Format_Conversion — Next step: converting the exported model