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

Cách dùng Keras lưu trọng số mô hình sau số epoch xác định trong Python


TensorFlow là framework machine learning của Google, mã nguồn mở, dùng với Python để triển khai thuật toán, deep learning. Tensor là cấu trúc dữ liệu đa chiều. Keras là high-level API trong TensorFlow, hỗ trợ lưu mô hình linh hoạt.

Cài đặt: pip install tensorflow. Truy cập Keras: from tensorflow import keras. Ví dụ dưới đây chạy trên Google Colab (miễn phí GPU).

Ví dụ

import os
import tensorflow as tf
from tensorflow import keras

checkpoint_path = "training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)
batch_size = 32
print("Tạo callback lưu trọng số sau mỗi 4 epoch")
cp_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_path,
    verbose=1,
    save_weights_only=True,
    save_freq=4 * batch_size)
print("Tạo instance mô hình mới")
model = create_model()  # giả định hàm create_model đã định nghĩa
print("Lưu trọng số ban đầu với checkpoint_path")
model.save_weights(checkpoint_path.format(epoch=0))

Nguồn mã: https://www.tensorflow.org/tutorials/keras/save_and_load

Kết quả

Tạo callback lưu trọng số sau mỗi 4 epoch
Tạo instance mô hình mới
Lưu trọng số ban đầu với checkpoint_path

Giải thích

  • ModelCheckpoint callback cho phép đặt tên checkpoint duy nhất, điều chỉnh tần suất lưu (save_freq).
  • Mô hình mới được huấn luyện.
  • Trọng số được lưu với tên duy nhất tại mỗi checkpoint sau mỗi 4 epoch.