Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lưu toàn bộ model Keras (SavedModel format) Python

Mô tả

Lưu model Keras hoàn chỉnh (architecture + weights + optimizer + training config) vào format SavedModel (thư mục) - format mặc định TensorFlow.

Code ví dụ

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np

def create_model():
    model = keras.Sequential([
        layers.Dense(64, activation='relu', input_shape=(784,)),
        layers.Dense(10, activation='softmax')
    ])
    model.compile(optimizer='adam', 
                  loss='sparse_categorical_crossentropy', 
                  metrics=['accuracy'])
    return model

# 1. TẠO MODEL MỚI
model = create_model()
print("A new model instance is created")

# 2. TRAIN MODEL
print("The model is fit to the training data...")
# Dummy data cho demo
x_train = np.random.rand(1000, 784).astype('float32')
y_train = np.random.randint(0, 10, 1000)
model.fit(x_train, y_train, epochs=3, verbose=1)

# 3. LƯU MODEL (SAVEDMODEL FORMAT)
import os
os.makedirs('saved_model', exist_ok=True)
model.save('saved_model/my_model')
print("The model is saved")

# 4. KIỂM TRA NỘI DUNG THƯ MỤC
print("\nSavedModel directory contents:")
for root, dirs, files in os.walk('saved_model/my_model'):
    for f in files:
        path = os.path.join(root, f)
        size = os.path.getsize(path)
        print(f"  {path} ({size} bytes)")

Đầu ra thư mục

SavedModel directory contents:
  saved_model/my_model/saved_model.pb (12345 bytes)
  saved_model/my_model/keras_metadata.pb (567 bytes)
  saved_model/my_model/fingerprint.pb (89 bytes)
  saved_model/my_model/variables/variables.data-00000-of-00001 (50890 bytes)
  saved_model/my_model/variables/variables.index (1234 bytes)

Chi tiết các file

  • saved_model.pb: Graph definition (protobuf) - architecture, operations.
  • variables/: Weights (data + index).
  • keras_metadata.pb: Keras-specific config (compile args, losses, metrics).
  • fingerprint.pb: Checksum để verify integrity.

Format .keras mới (Keras 3 / TF 2.13+)

File zip đơn giản, thay thế cả .h5 và SavedModel folder.

# Khuyên dùng cho TF 2.13+
model.save('my_model.keras')  # Single file, zip-based
new_model = keras.models.load_model('my_model.keras')

Best Practices

  1. Luôn save sau khi train xong (hoặc dùng Callback).
  2. Dùng save_format='tf' explicit: model.save('path', save_format='tf').
  3. Version control: Không commit file model lớn vào git. Dùng DVC, MLflow, S3.
  4. Metadata: Thêm mô tả vào model: model._metadata = {'version': '1.0', 'author': '...'}.