오늘의 인기 글
최근 글
최근 댓글
Today
Total
04-28 07:25
관리 메뉴

우노

[ML] Tensorflow 모델을 TFLite 로 변환하는 방법 본문

AI/Machine Learning

[ML] Tensorflow 모델을 TFLite 로 변환하는 방법

운호(Noah) 2022. 1. 25. 13:21

들어가기 앞서,

  • 양자화(quantization)는 float32 로 학습된 weight 값들을 float16, int8 등의 형태로 변환하는 작업을 의미합니다.
  • 이 작업을 하게되면, .tflite 의 파일크기가 대략 4분의 1정도로 줄어들게 되지만,
  • 세밀한 데이터값을 버리는 작업이므로, model 의 정확도를 잃을 수 있는 작업이 됩니다.
  • 결과적으로 양자화는, model 의 사이즈를 줄임으로써, 정확도는 떨어지지만 빠른 추론 시간을 얻게 되는 작업이라고 볼 수 있습니다.

TFLite 변환 시, FP16 양자화 적용 예제

  • 파일로 저장되어 있는 모델을 load 한 뒤, TFLite 모델로 변환

      import tensorflow as tf
    
      # 파일로 저장되어 있는 모델을 load 한 뒤, TFLite 모델로 변환
      converter = tf.lite.TFLiteConverter.from_saved_model('모델파일위치')
    
      # FP16 양자화 설정
      converter.target_spec.supported_types = [tf.float16]
      converter.optimizations = [tf.lite.Optimize.DEFAULT]
    
      # 모델 양자화
      tflite_model = converter.convert()
    
      # 변환된 모델을 .tflite 파일에 저장
      open("변환모델저장명.tflite", "wb").write(tflite_model)
  • 변수로 저장되어 있는 모델을, TFLite 모델로 변환

      import tensorflow as tf
    
      # 변수로 저장되어 있는 모델을, TFLite 모델로 변환
      converter = tf.lite.TFLiteConverter.from_keras_model(모델변수)
    
      # FP16 양자화 설정
      converter.target_spec.supported_types = [tf.float16]
      converter.optimizations = [tf.lite.Optimize.DEFAULT]
    
      # 모델 양자화
      tflite_model = converter.convert()
    
      # 변환된 모델을 .tflite 파일에 저장
      open("변환모델저장명.tflite", "wb").write(tflite_model)

참고

Comments