Mô tả
SavedModel là format mặc định của TensorFlow (thư mục chứa .pb, variables/, assets/). Phù hợp cho production serving (TF Serving, TFLite, TF.js).
Lưu SavedModel
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(10,)),
layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse')
# Dummy train
import numpy as np
model.fit(np.random.rand(100, 10), np.random.rand(100, 1), epochs=1, verbose=0)
# LƯU SAVEDMODEL (thư mục)
model.save('saved_model/my_model') # Không có extension
print("SavedModel saved to saved_model/my_model/")
Cấu trúc thư mục SavedModel
saved_model/my_model/ ├── assets/ ├── variables/ │ ├── variables.data-00000-of-00001 │ └── variables.index ├── saved_model.pb # Graph definition (protobuf) ├── keras_metadata.pb # Keras metadata └── fingerprint.pb # Fingerprint
Load SavedModel
# Cách 1: Load as Keras model (full functionality)
new_model = tf.keras.models.load_model('saved_model/my_model')
print("Loaded as Keras model:")
new_model.summary()
# Cách 2: Load as TensorFlow SavedModel (low-level, cho serving)
imported = tf.saved_model.load('saved_model/my_model')
print("\nLoaded as TF SavedModel:")
print(f"Signatures: {list(imported.signatures.keys())}")
# Gọi signature serving_default
infer = imported.signatures['serving_default']
input_tensor = tf.ones((1, 10))
output = infer(input_tensor)
print(f"Output: {output}")
Đầu ra
Loaded as Keras model:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 64) 704
dense_1 (Dense) (None, 1) 65
=================================================================
Total params: 769
Loaded as TF SavedModel:
Signatures: ['serving_default', '__saved_model_init_op']
Output: {'dense_1': }
So sánh HDF5 vs SavedModel
| Đặc điểm | HDF5 (.h5) | SavedModel (folder) |
|---|---|---|
| Format | Single file | Directory |
| TF Serving | Cần convert | Native support |
| TFLite/TFJS convert | Hỗ trợ | Hỗ trợ (khuyên dùng) |
| Custom objects | Cần custom_objects | Tự động (metadata) |
| Keras 3+ default | Legacy | Mặc định (.keras) |
Khi nào dùng SavedModel?
- Deploy với TensorFlow Serving / Docker.
- Convert sang TFLite (mobile), TF.js (web).
- Model có custom layers/objects phức tạp.
- Production pipeline.