메타데이터를 사용하여 모델 인터페이스 생성

개발자는 TensorFlow Lite 메타데이터를 사용하여 Android에서 통합을 사용 설정하는 래퍼 코드를 생성할 수 있습니다. 대부분의 개발자는 Android 스튜디오 ML 모델 결합의 그래픽 인터페이스가 가장 사용하기 쉽습니다. 추가 맞춤설정이 필요하거나 명령줄 도구를 사용하고 있다면 TensorFlow Lite Codegen도 사용할 수 있습니다.

Android 스튜디오 ML 모델 결합 사용

메타데이터로 향상된 TensorFlow Lite 모델의 경우 개발자는 Android 스튜디오 ML 모델 결합을 사용하여 자동으로 프로젝트 설정을 구성하고 모델 메타데이터를 기반으로 래퍼 클래스를 생성할 수 있습니다. 래퍼 코드를 사용하면 ByteBuffer와 직접 상호작용할 필요가 없습니다. 대신 개발자는 유형이 지정된 객체(예: BitmapRect)를 사용하여 TensorFlow Lite 모델과 상호작용할 수 있습니다.

Android 스튜디오에서 TensorFlow Lite 모델 가져오기

  1. TFLite 모델을 사용할 모듈을 마우스 오른쪽 버튼으로 클릭하거나 File를 클릭한 다음 New > Other > TensorFlow Lite Model을 클릭합니다.

  2. TFLite 파일의 위치를 선택합니다. 이 도구는 ML 모델 결합과 Android 모듈의 build.gradle 파일에 자동으로 삽입되는 모든 종속 항목을 통해 자동으로 모듈의 종속 항목을 구성합니다.

    선택사항: GPU 가속을 사용하려면 TensorFlow GPU를 가져오는 두 번째 체크박스를 선택합니다.

  3. Finish 아이콘을 클릭합니다.

  4. 가져오기가 완료되면 다음 화면이 표시됩니다. 모델 사용을 시작하려면 Kotlin 또는 Java를 선택하고 코드를 복사하여 Sample Code 섹션 아래에 붙여넣습니다. Android 스튜디오의 ml 디렉터리에 있는 TFLite 모델을 더블클릭하여 이 화면으로 돌아올 수 있습니다.

모델 추론 가속화

ML 모델 바인딩은 개발자가 대리자 및 스레드 수를 사용하여 코드를 가속화할 수 있는 방법을 제공합니다.

1단계: 모듈 build.gradle 파일에서 다음 종속 항목이 포함되어 있는지 확인합니다.

    dependencies {
        ...
        // TFLite GPU delegate 2.3.0 or above is required.
        implementation 'org.tensorflow:tensorflow-lite-gpu:2.3.0'
    }

2단계: 여러 CPU 스레드를 사용하여 모델을 실행하지 않는 경우 기기에서 실행 중인 GPU가 TensorFlow GPU 대리자와 호환되는지 감지합니다.

Kotlin

    import org.tensorflow.lite.gpu.CompatibilityList
    import org.tensorflow.lite.gpu.GpuDelegate

    val compatList = CompatibilityList()

    val options = if(compatList.isDelegateSupportedOnThisDevice) {
        // if the device has a supported GPU, add the GPU delegate
        Model.Options.Builder().setDevice(Model.Device.GPU).build()
    } else {
        // if the GPU is not supported, run on 4 threads
        Model.Options.Builder().setNumThreads(4).build()
    }

    // Initialize the model as usual feeding in the options object
    val myModel = MyModel.newInstance(context, options)

    // Run inference per sample code
      

Java

    import org.tensorflow.lite.support.model.Model
    import org.tensorflow.lite.gpu.CompatibilityList;
    import org.tensorflow.lite.gpu.GpuDelegate;

    // Initialize interpreter with GPU delegate
    Model.Options options;
    CompatibilityList compatList = CompatibilityList();

    if(compatList.isDelegateSupportedOnThisDevice()){
        // if the device has a supported GPU, add the GPU delegate
        options = Model.Options.Builder().setDevice(Model.Device.GPU).build();
    } else {
        // if the GPU is not supported, run on 4 threads
        options = Model.Options.Builder().setNumThreads(4).build();
    }

    MyModel myModel = new MyModel.newInstance(context, options);

    // Run inference per sample code
      

TensorFlow Lite 코드 생성기로 모델 인터페이스 생성

메타데이터로 향상된 TensorFlow Lite 모델의 경우 개발자는 TensorFlow Lite Android 래퍼 코드 생성기를 사용하여 플랫폼별 래퍼 코드를 만들 수 있습니다. 래퍼 코드를 사용하면 ByteBuffer와 직접 상호작용할 필요가 없습니다. 대신 개발자는 유형이 지정된 객체(예: BitmapRect)를 사용하여 TensorFlow Lite 모델과 상호작용할 수 있습니다.

코드 생성기의 유용성은 TensorFlow Lite 모델의 메타데이터 항목의 완전성에 따라 달라집니다. codegen 도구가 각 필드를 파싱하는 방법은 metadata_schema.fbs의 관련 필드 아래에 있는 <Codegen usage> 섹션을 참고하세요.

래퍼 코드 생성

터미널에 다음 도구를 설치해야 합니다.

pip install tflite-support

완료되면 다음 구문을 사용하여 코드 생성기를 사용할 수 있습니다.

tflite_codegen --model=./model_with_metadata/mobilenet_v1_0.75_160_quantized.tflite \
    --package_name=org.tensorflow.lite.classify \
    --model_class_name=MyClassifierModel \
    --destination=./classify_wrapper

결과 코드는 대상 디렉터리에 있습니다. Google Colab 또는 기타 원격 환경을 사용 중인 경우 결과를 zip 파일로 압축하여 Android 스튜디오 프로젝트에 다운로드하는 것이 더 쉬울 수 있습니다.

# Zip up the generated code
!zip -r classify_wrapper.zip classify_wrapper/

# Download the archive
from google.colab import files
files.download('classify_wrapper.zip')

생성된 코드 사용

1단계: 생성된 코드 가져오기

필요한 경우 생성된 코드를 디렉터리 구조에 압축 해제합니다. 생성된 코드의 루트는 SRC_ROOT로 간주됩니다.

TensorFlow Lite 모델을 사용할 Android 스튜디오 프로젝트를 열고 파일 -> 새로 만들기 -> 모듈 가져오기 -> SRC_ROOT를 선택하여 생성된 모듈을 가져옵니다.

위의 예를 사용하면 가져온 디렉터리와 모듈은 classify_wrapper라고 합니다.

2단계: 앱의 build.gradle 파일 업데이트

생성된 라이브러리 모듈을 사용할 앱 모듈에서 다음을 수행합니다.

android 섹션에서 다음을 추가합니다.

aaptOptions {
   noCompress "tflite"
}

종속 항목 섹션에서 다음을 추가합니다.

implementation project(":classify_wrapper")

3단계: 모델 사용

// 1. Initialize the model
MyClassifierModel myImageClassifier = null;

try {
    myImageClassifier = new MyClassifierModel(this);
} catch (IOException io){
    // Error reading the model
}

if(null != myImageClassifier) {

    // 2. Set the input with a Bitmap called inputBitmap
    MyClassifierModel.Inputs inputs = myImageClassifier.createInputs();
    inputs.loadImage(inputBitmap));

    // 3. Run the model
    MyClassifierModel.Outputs outputs = myImageClassifier.run(inputs);

    // 4. Retrieve the result
    Map<String, Float> labeledProbability = outputs.getProbability();
}

모델 추론 가속화

생성된 코드를 통해 개발자는 대리자 사용 및 스레드 수를 통해 코드 속도를 높일 수 있습니다. 모델 객체를 초기화할 때 다음 세 가지 매개변수를 사용할 수 있습니다.

  • Context: Android 활동 또는 서비스의 컨텍스트
  • (선택사항) Device: TFLite 가속 위임. 예: GPUDelegate
  • (선택사항) numThreads: 모델을 실행하는 데 사용되는 스레드 수입니다. 기본값은 1입니다.

예를 들어 GPU 대리자와 최대 3개의 스레드를 사용하려면 다음과 같이 모델을 초기화하면 됩니다.

try {
    myImageClassifier = new MyClassifierModel(this, Model.Device.GPU, 3);
} catch (IOException io){
    // Error reading the model
}

문제 해결

'java.io.FileNotFoundException: 이 파일을 파일 설명자로 열 수 없습니다. 압축되었을 수 있습니다' 오류가 발생하면 라이브러리 모듈을 사용할 앱 모듈의 Android 섹션 아래에 다음 줄을 삽입합니다.

aaptOptions {
   noCompress "tflite"
}