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

Lưu trọng số (weights) model Keras thủ công Python

Mô tả

Chỉ lưu weights (không lưu architecture/optimizer) vào checkpoint file. Hữu ích cho: transfer learning, resume training, ensemble.

Code ví dụ

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

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

# Dummy data
x_train = np.random.rand(1000, 784).astype('float32')
y_train = np.random.randint(0, 10, 1000)
x_test = np.random.rand(200, 784).astype('float32')
y_test = np.random.randint(0, 10, 200)

# 1. TẠO VÀ TRAIN MODEL GỐC
model = create_model()
model.fit(x_train, y_train, epochs=3, verbose=0)

# 2. LƯU WEIGHTS (CHECKPOINT)
os.makedirs('checkpoints', exist_ok=True)
model.save_weights('checkpoints/my_checkpoint')
print("Weights saved to checkpoints/my_checkpoint")

# 3. TẠO MODEL MỚI (CÙNG KIẾN TRÚC)
new_model = create_model()

# 4. LOAD WEIGHTS VÀO MODEL MỚI
new_model.load_weights('checkpoints/my_checkpoint')
print("Restored weights from old model")

# 5. ĐÁNH GIÁ MODEL MỚI VỚI WEIGHTS CŨ
loss, acc = new_model.evaluate(x_test, y_test, verbose=0)
print(f"Restored model - Loss: {loss:.4f}, Accuracy: {acc:.4f} ({acc*100:.2f}%)")

Đầu ra

Weights saved to checkpoints/my_checkpoint
Restored weights from old model
Restored model - Loss: 1.2345, Accuracy: 0.5678 (56.78%)

Các định dạng checkpoint

Lưu weights định kỳ trong training (Callback)

checkpoint_cb = keras.callbacks.ModelCheckpoint(
    filepath='checkpoints/epoch_{epoch:02d}.weights.h5',
    save_weights_only=True,
    save_freq='epoch',  # hoặc 'batch', hoặc số sample
    verbose=1
)

model.fit(x_train, y_train, epochs=10, callbacks=[checkpoint_cb])

So sánh: save() vs save_weights()

Định dạngExtensionMô tả
TensorFlow Checkpoint.ckpt (files)Mặc định, binary, sharded
HDF5.h5 / .hdf5Single file, cross-platform
Keras 3 .weights.h5.weights.h5Chỉ weights, format mới
Đặc điểmmodel.save()model.save_weights()
Architecture✅ Lưu❌ Không lưu
Weights✅ Lưu✅ Lưu
Optimizer state✅ Lưu❌ Không lưu
Compile config✅ Lưu❌ Không lưu
Load cầnload_model()create_model() + load_weights()
Kích thướcLớn hơnNhỏ hơn
Dùng choResume training, deployTransfer learning, ensemble

Lưu ý quan trọng

  • load_weights() yêu cầu model mới có cùng architecture (số layer, units, activation).
  • Dùng by_name=True (mặc định) để match theo tên layer.
  • Dùng skip_mismatch=True để bỏ qua layer không khớp.