[tensorflow] H5 Keras 모델 로드

h5 Model load and fit

h5모델은 .h5(HDF5) 포맷도 모델 및 가중치를 모두 가지고 있는 데이터 파일.

h5로 저장된 모델을 불러와서 임시 파일로 테스트 해보려 함.
참고 문서는 텐서플로 공식 문서 중
https://www.tensorflow.org/guide/keras/save_and_serialize?hl=ko
를 참고했음

Keras H5 형식
Keras는 또한 모델의 아키텍처, 가중치 값 및 compile() 정보가 포함된 단일 HDF5 파일 저장을 지원합니다. SavedModel에 대한 가벼운 대안입니다.

model = get_model()

# Train the model.
test_input = np.random.random((128, 32))
test_target = np.random.random((128, 1))
model.fit(test_input, test_target)

# Calling `save('my_model.h5')` creates a h5 file `my_model.h5`.
model.save("my_h5_model.h5")

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model("my_h5_model.h5")

# Let's check:
np.testing.assert_allclose(
    model.predict(test_input), reconstructed_model.predict(test_input)
)

# The reconstructed model is already compiled and has retained the optimizer
# state, so training can resume:
reconstructed_model.fit(test_input, test_target)

기존 모델을
get_model()로 모델 불러오고
test_input 과 test_target 변수를 통해서 model에 적합 시킨다 fit().
이 모델을 save('my_model.h5') 를 통해서 h5 형식으로 저장한다.

이 h5 모델은 keras.models.load_model("my_h5_model.h5") 을 통해서 로드 가능함
np.testing.assert_allclose(
model.predict(test_input), reconstructed_model.predict(test_input)
)
을 통해서 모델의 테스트 input 예측과 h5모델 테스트 input 예측결과가 맞는지 확인

reconstructed_model.fit(test_input, test_target)로 적합 가능

saveModel 형식과 비교해 h5는 외부 손실 및 메트릭 저장X


좋은 웹페이지 즐겨찾기