Deep learning_ 모델 구현

sujineeda·2021년 3월 26일
0

🤯AI

목록 보기
3/7

모델 저장과 복원

#모델 저장
model.save("my_model.h5")
#모델 불러오기
model = keras.models.load_model("my_model.h5")

케라스는 HDF5 포맷을 사용하여 모델 구조와 층의 모든 연결 가중치, 편향, 옵티마이저 저장
단, sequential, functional API에서만 사용가능
subclassing API는 save_weights(), load_weights()를 통해 모델 파라미터만 저장, 복원 가능

콜백

  • 콜백이 필요한 이유 ?
    : 훈련이 몇시간 동안 지속될 경우, 도중에 데이터를 잃지 않기 위해 훈련 도중 일정 간격으로 체크포인트 저장해야함
checkpoint_cb = keras.callbacks.ModelCheckpoint("my_model.h5", save_best_only = True)
history = model.fit(X_train, y_train, epochs = 10, callbacks = [checkpoint_cb])
  • save_best_only 파라미터는 최상의 검증 세트 점수에서만 모델을 저장할 수 있도록 함
    • 오랜 훈련 시간으로 인한 과대적합 방지 가능
  • 훈련 시간 단축 방법
    • 조기종료
    • EarlyStopping 콜백이 훈련 끝난 후 최상의 가중치를 복워하기 때문에 저장된 모델을 따로 복원할 필요 x
checkpoint_cb = keras.callbacks.ModelCheckpoint("my_model.h5", save_best_only = True)
early_stopping_cb = keras.callbacks.EarlyStopping(patience = 10, restore_best_weights = True)
history = model.fit(X_train, y_train, epochs = 100, 
	callbacks = [checkpoint_cb, early_stopping_cb])

모델 시각화 - Tensorboard

텐서보드를 사용하려면 이벤트 파일인 이진 로그 파일에 시각화하려는 데이터를 출력해야 함.
각각의 이진 데이터 레코드 = summary
텐서보드 서버는 로그 디렉터리를 모니터링하고 자동으로 변경사항을 읽어 그래프를 업뎃함.
실시간으로 데이터 시각화 가능

텐서보드 서버가 루트 로그 디렉터리를 가리키고 프로그램은 실행할 때마다 다른 서브디렉터리에 이벤트를 기록함

#루트 로그 디렉토리 정의
import os
root_logdir = os.path.join(os.curdir, "my_logs")

def get_run_logdir():
    import time
    run_id = time.strftime("run_%Y_%m_%d-%H_%M_%S")
    return os.path.join(root_logdir, run_id)

run_logdir = get_run_logdir()

#텐서보드 콜백
tensorboard_cb = keras.callbacks.TensorBoard(run_logdir)
history = model.fit(X, y, epochs = 200, callbacks =[tensorboard_cb])

#텐서보드 서버 구동 (tensorflow 설치한 virtualenv에서 터미널 실행) 
$ tensorboard --logdir=./my_logs --port=6006

#서버가 실행되면 웹 브라우저를 열어 http://localhost:6006 접속
  • tf.summary 패키지 실행
    • create_file_writer()함수 사용해 summarywriter 를 만든 후 with 블럭 안에서 텐서보드를 사용해 시각화할 수 있는 스칼라, 이미지, 오디오 등 기록 가능
# 이미지 텐서보드에서 시각화하기
# 시각화하기 위해 shape를 4가지 수준에 맞게 reshape 해주어야 함. (batch size, width, height, color channel)
image = np.reshape(-1, 180, 180, 3)
test_logdir = get_run_logdir()
writer = tf.summary.create_file_writer(test_logdir)
with writer.as_default():
    for step in range(10):
        tf.summary.image("title", image, step = step)
    
profile
AD+AI Ph.D course

0개의 댓글