본문 바로가기
IT/AI, ML

텐서플로우 h5 모델 tflite로 변환 방법

by 프론트엔드 지식백과 2025. 4. 5.

Firebase ML을 사용해 머신러닝 모델을 배포하려면 .tflite 형식의 모델이 필요하다. 하지만 많은 경우 Keras나 TensorFlow에서 모델을 저장할 때 .h5 또는 SavedModel 형식으로 저장하게 된다.

 

h5와 tflite의 차이점

1. h5 (Hierarchical Data Format)

  • h5는 Keras에서 모델을 저장할 때 자주 사용하는 포맷이다.
  • 모델의 구조와 가중치를 함께 저장할 수 있으며, Python 기반 환경에서 불러오기 용이하다.
  • 하지만 용량이 크고 모바일/임베디드 환경에서는 비효율적이다.

2. tflite (TensorFlow Lite)

  • TensorFlow Lite는 모바일, IoT 기기 등 리소스가 제한된 환경을 위한 경량화된 모델 형식이다.
  • 용량이 작고 실행 속도가 빠르며, Android/iOS에서도 쉽게 배포할 수 있다.
  • Firebase ML과 같은 모바일 플랫폼에서도 tflite 형식만 지원한다. (파이어베이스를 통해 배포하려면 tflite를 사용할 수 밖에 없다.)

 

h5 모델을 tflite로 변환하는 방법

TensorFlow에서는 TFLiteConverter를 사용하여 간단하게 변환할 수 있다!

 

다만, 환경에 따라 버전 충돌이나 오류가 발생할 수 있으므로 불필요한 패키지를 정리하고, 필요한 라이브러리를 새로 설치하는 것이 좋다.
나는 TensorFlow와 TensorFlow Hub를 함께 사용했기 때문에 다음과 같이 설치하였다.

!pip uninstall tensorflow tensorflow-hub -y
!pip install tensorflow==2.15.0 tensorflow-hub==0.15.0

 

import tensorflow as tf
import tensorflow_hub as hub
import json

print("--- Versions after Reinstall ---")
print("TensorFlow Version:", tf.__version__)
print("TensorFlow Hub Version:", hub.__version__)
print("-----------------------------")

# 1. h5 모델 로드 시 custom_objects 지정
model_path = 'best_model.h5'
custom_objects = {'KerasLayer': hub.KerasLayer}

try:
    model = tf.keras.models.load_model(model_path, custom_objects=custom_objects)
    print("Model loaded successfully.")

    # 2. TensorFlow Lite 변환기 생성
    converter = tf.lite.TFLiteConverter.from_keras_model(model)

    # 3. tflite 모델로 변환
    tflite_model = converter.convert()

    # 4. tflite 파일로 저장
    tflite_model_path = 'best_model.tflite'
    with open(tflite_model_path, 'wb') as f:
        f.write(tflite_model)
    print(f"Model converted and saved to {tflite_model_path}")

    # 5. 변환된 TFLite 모델 정보 확인
    interpreter = tf.lite.Interpreter(model_path=tflite_model_path)
    interpreter.allocate_tensors()
    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()
    print("\n--- TFLite Model Input/Output Details ---")
    print("Input Details:", input_details)
    print("Output Details:", output_details)
    print("----------------------------------------")

except Exception as e:
    print(f"An error occurred: {e}")

 

참고) 옵션으로 converter.optimizations를 설정하면 양자화 등의 기법을 통해 모델 크기를 더 줄일 수 있다.

다만 이 경우 정확도에 약간의 손실이 생길 수 있으니 테스트가 필요하다.

# (선택) 최적화 옵션 적용 – 모델 용량 줄이기
converter.optimizations = [tf.lite.Optimize.DEFAULT]

 

결과

 

 

정리하자면,

  • Firebase ML에서는 .tflite 포맷만 지원하므로, 기존의 h5 모델을 변환해야 한다.
  • tflite는 모바일 환경에 최적화된 경량 모델 형식이다.
  • TensorFlow의 TFLiteConverter를 통해 쉽게 변환할 수 있다
728x90

'IT > AI, ML' 카테고리의 다른 글

[AI/ML]CNN과 블랙박스 현상  (1) 2025.03.25
인과 학습(Causal Learning)이란?  (3) 2022.09.05