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

Lưu model Keras định dạng HDF5 (.h5) Python

Mô tả

Lưu toàn bộ model (architecture + weights + optimizer state) vào file HDF5 (.h5), sau đó load lại.

Code ví dụ

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

# Tạo model mẫu
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

model = create_model()
# model.fit(...)  # Giả sử đã train

# 1. LƯU MODEL VÀO HDF5
model.save('my_model.h5')
print("Model saved to HDF5 format")

# 2. LOAD MODEL TỪ HDF5
new_model = tf.keras.models.load_model('my_model.h5')
print("Model recreated with same weights and optimizer")

# 3. KIỂM TRA KIẾN TRÚC
new_model.summary()

# 4. VERIFY WEIGHTS
import numpy as np
for w1, w2 in zip(model.weights, new_model.weights):
    assert np.allclose(w1.numpy(), w2.numpy()), "Weights mismatch!"
print("Weights verified: IDENTICAL")

Đầu ra summary

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 dense (Dense)               (None, 64)                50240
 dense_1 (Dense)             (None, 10)                650
=================================================================
Total params: 50,890
Trainable params: 50,890
Non-trainable params: 0
_________________________________________________________________

Nội dung file .h5 (HDF5)

  • model_config: JSON architecture (layers, connections).
  • model_weights: Group chứa weights của từng layer.
  • optimizer_weights: Trạng thái optimizer (momentum, lr, etc.).
  • training_config: Loss, metrics, compile config.

Xem cấu trúc file HDF5

import h5py

with h5py.File('my_model.h5', 'r') as f:
    def print_structure(name, obj):
        print(f"{name}: {type(obj).__name__}")
    f.visititems(print_structure)

Lưu ý

  • File .h5 chứa mọi thứ cần để resume training.
  • Kích thước file = model size + optimizer state.
  • Tương thích cross-platform, cross-language (HDF5 standard).
  • Keras 3+ khuyên dùng format .keras (zip-based, hiệu quả hơn).

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

# Khuyên dùng cho TF 2.13+
model.save('my_model.keras')  # Thay vì .h5
new_model = keras.models.load_model('my_model.keras')