Data Science/AI

[에러 해결] RuntimeError: You must compile your model before training/testing. Use `model.compile(optimizer, loss)`. 해결하기

토마토. 2023. 3. 9. 13:10
model = keras.models.load_model("model-whole.h5")
model.evaluate(val_scaled, val_target)

.h5 파일에 저장한 모델을 다시 불러오려다 에러가 발생했다. 

발생한 에러는 다음과 같다. 

 

WARNING:tensorflow:No training configuration found in the save file, so the model was *not* compiled. Compile it manually.

 

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[54], line 2
      1 model = keras.models.load_model("model-whole.h5")
----> 2 model.evaluate(val_scaled, val_target)

File c:\Users\.venv\lib\site-packages\keras\utils\traceback_utils.py:70, in filter_traceback..error_handler(*args, **kwargs)
     67     filtered_tb = _process_traceback_frames(e.__traceback__)
     68     # To get the full stack trace, call:
     69     # `tf.debugging.disable_traceback_filtering()`
---> 70     raise e.with_traceback(filtered_tb) from None
     71 finally:
     72     del filtered_tb

File c:\Users\.venv\lib\site-packages\keras\engine\training.py:3690, in Model._assert_compile_was_called(self)
   3684 def _assert_compile_was_called(self):
   3685     # Checks whether `compile` has been called. If it has been called,
   3686     # then the optimizer is set. This is different from whether the
   3687     # model is compiled
   3688     # (i.e. whether the model is built and its inputs/outputs are set).
   3689     if not self._is_compiled:
-> 3690         raise RuntimeError(
   3691             "You must compile your model before "
   3692             "training/testing. "
   3693             "Use `model.compile(optimizer, loss)`."
   3694         )

RuntimeError: You must compile your model before training/testing. Use `model.compile(optimizer, loss)`.

 


해결 방법

model.save('iris.h5')
model = keras.models.load_model("iris.h5")
model.evaluate(val_scaled, val_target, verbose=2)

모델 저장 단계에서 문제가 생긴 것 같아

모델을 학습시킨 직후에 모델을 저장하고 다시 불러오니 문제가 해결되었다.