2025.03.15 - [Data & Research] - [ML & DL 기초] Table of Contents
콜백(Callback) 함수를 사용하면 학습 과정 중에 특정 시점(예: 에포크 시작/종료, 배치 시작/종료)에 원하는 동작을 수행하도록 할 수 있습니다. 기본적인 사용방식은 아래와 같습니다.
# 1. 필요한 콜백 임포트
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
# 2. 콜백 객체 생성
early_stopping = EarlyStopping(monitor='val_loss', patience=10)
model_checkpoint = ModelCheckpoint(
filepath='best_model.keras',
save_best_only=True,
monitor='val_loss',
verbose=1
)
# 3. model.fit()에 콜백 리스트 전달
history = model.fit(
x_train, y_train,
epochs=100,
validation_data=(x_val, y_val),
callbacks=[early_stopping, model_checkpoint] # ◀◀◀
)
callback함수에는 다양한 유용한 기능을 넣을 수 있습니다.
1) Learning_rate 조절
callbacks.ReduceLROnPlateau(
monitor="val_loss",
factor=0.1, # new_lr = lr * factor.
patience=5,
verbose=0,
mode="auto",
min_delta=0.0002,
cooldown=0,
min_lr=0,
**kwargs
)
reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', verbose=1,factor=0.4
, patience=10, min_lr=1e-6)
2) 모델 저장
keras.callbacks.ModelCheckpoint(
filepath, # 저장경로
save_weights_only=True, # 모델전체로 할 것이냐 가중치만 저장할 것이냐
monitor='val_acc', # 기준 metric
mode='max', # "최선"의 기준(auto, min, max)
save_best_only=True) # 더 나아졌을 때만 저장할 것이냐
3) 비정상 종료 시 이어서 학습
Backup_ = keras.callbacks.BackupAndRestore(backup_dir="./backupfile")
'Data & Research' 카테고리의 다른 글
[Deep Learning] Batch/Layer Normalization (0) | 2025.07.02 |
---|---|
[TensorFlow/Keras 기초] Keras 구현의 3가지 방식 (2) | 2025.07.01 |
[Reinforcement Learning] The Cliff Walking Problem (4) | 2025.07.01 |
[Reinforcement Learning] Table of Contents (0) | 2025.06.29 |
[Reinforcement Learning] Actor-Critic Algorithm (2) | 2025.06.29 |