Keras에서 모델 가중치 저장하기 !

져닝·2025년 2월 4일

tensorflow-keras

목록 보기
5/5

딥러니 모델을 훈련할 때 ModelCheckpoint 콜백을 사용하면 특정 조건을 만족하는 가중치를 저장할 수 있다. 기본적으로 모든 에폭마다 가중치를 저장할 수도 있지만, 가장 좋은 성능(예: val_loss가 최소인 경우)을 보인 가중치만 저장하는 방법이 있다.


기본적인 ModelCheckpoint 사용법

기본적으로 ModelCheckpoint는 다음과 같이 사용된다.

import os
import tensorflow as tf

# 체크포인트 저장 경로 설정
cp_filepath = os.path.join("checkpoints", "{epoch:02d}.h5")

cp_callback = tf.keras.callbacks.ModelCheckpoint(
	filepath=cp_filepath,
    save_weights_only=True,
    monitor='val_loss',
    mode='min')

위 코드를 실행하면 매 에폭마다 {epoch:02d}.h5 형식으로 가중치가 저장된다.


가장 좋은 가중치만 저장하는 방법

모든 에폭이 아니라, 가장 낮은 val_loss를 기록한 가중치만 저장하고 싶다면 save_best_only=True 옵션을 추가하면 된다.

import os
import tensorflow as tf

cp_filepath = os.paht.join("checkpoints", "best_model.h5")

cp_callback = tf.keras.callbacks.ModelCheckpoint(
	filepath=cp_filepath,
    save_weights_only=True,
    monitor='val_loss',
    mode='min',
    save_best_only=True)
    
# model train
hist = model.fit(
	inp, tar,
    epochs=50,
    validation_split=0.2,
    batch_size=32,
    callbacks=[cp_callback])

이렇게 하면 val_loss가 가장 낮았던 에폭의 가중치만 best_model.h5 파일에 저장된다.


저장된 가중치 불러오기

훈련 후 가장 좋은 가중치르 불러올 때는 다음과 같이 하면 된다.

model.load_weights("checkpoints/best_model.h5")

이를 통해 모델을 재훈련하지 않고도 최적의 가중치를 적용하여 예측할 수 있다.


ModelCheckpoint를 활용하면 훈련 과정에서 불필요한 체크포인트 파일을 줄이고, 가장 좋은 성능을 가진 가중치만 저장할 수 있다. 특히, 학습이 오래 걸리는 모델에서는 이 방법을 사용하면 효율적으로 최적의 모델을 저장하고 활용할 수 있다.

profile
태양물리박사 / 코드 공부 끄적끄적하는 공간 / Space weather forecasting

0개의 댓글