Catch up on highlights from Firebase at Google I/O 2023. Learn more

Android पर कस्टम TensorFlow Lite मॉडल का उपयोग करें

यदि आपका ऐप कस्टम TensorFlow Lite मॉडल का उपयोग करता है, तो आप अपने मॉडल को परिनियोजित करने के लिए Firebase ML का उपयोग कर सकते हैं। फायरबेस के साथ मॉडल परिनियोजित करके, आप अपने ऐप के शुरुआती डाउनलोड आकार को कम कर सकते हैं और अपने ऐप के नए संस्करण को जारी किए बिना अपने ऐप के एमएल मॉडल को अपडेट कर सकते हैं। और, Remote Config और A/B Testing के साथ, आप गतिशील रूप से विभिन्न मॉडलों को उपयोगकर्ताओं के विभिन्न समूहों के लिए सेवा प्रदान कर सकते हैं।

टेंसरफ्लो लाइट मॉडल

TensorFlow Lite मॉडल एमएल मॉडल हैं जिन्हें मोबाइल उपकरणों पर चलने के लिए अनुकूलित किया गया है। TensorFlow Lite मॉडल प्राप्त करने के लिए:

शुरू करने से पहले

  1. यदि आपने पहले से नहीं किया है, तो अपने Android प्रोजेक्ट में Firebase जोड़ें
  2. अपने मॉड्यूल (ऐप-लेवल) ग्रैडल फ़ाइल (आमतौर पर <project>/<app-module>/build.gradle ) में, फायरबेस एमएल मॉडल डाउनलोडर एंड्रॉइड लाइब्रेरी के लिए निर्भरता जोड़ें। हम लाइब्रेरी वर्ज़निंग को नियंत्रित करने के लिए Firebase Android BoM का उपयोग करने की सलाह देते हैं।

    साथ ही, Firebase ML मॉडल डाउनलोडर सेट अप करने के हिस्से के रूप में, आपको अपने ऐप में TensorFlow Lite SDK जोड़ना होगा।

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // Add the dependency for the Firebase ML model downloader library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-ml-modeldownloader-ktx'
    // Also add the dependency for the TensorFlow Lite library and specify its version implementation 'org.tensorflow:tensorflow-lite:2.3.0'
    }

    Firebase Android BoM का उपयोग करके, आपका ऐप हमेशा Firebase Android पुस्तकालयों के संगत संस्करणों का उपयोग करेगा।

    (वैकल्पिक) BoM का उपयोग किए बिना Firebase लाइब्रेरी निर्भरताएँ जोड़ें

    यदि आप Firebase BoM का उपयोग नहीं करना चुनते हैं, तो आपको प्रत्येक Firebase लाइब्रेरी संस्करण को उसकी निर्भरता रेखा में निर्दिष्ट करना होगा।

    ध्यान दें कि यदि आप अपने ऐप में एकाधिक फायरबेस लाइब्रेरी का उपयोग करते हैं, तो हम लाइब्रेरी संस्करणों को प्रबंधित करने के लिए बीओएम का उपयोग करने की दृढ़ता से अनुशंसा करते हैं, जो सुनिश्चित करता है कि सभी संस्करण संगत हैं।

    dependencies {
        // Add the dependency for the Firebase ML model downloader library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-ml-modeldownloader-ktx:24.1.2'
    // Also add the dependency for the TensorFlow Lite library and specify its version implementation 'org.tensorflow:tensorflow-lite:2.3.0'
    }

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // Add the dependency for the Firebase ML model downloader library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-ml-modeldownloader'
    // Also add the dependency for the TensorFlow Lite library and specify its version implementation 'org.tensorflow:tensorflow-lite:2.3.0'
    }

    Firebase Android BoM का उपयोग करके, आपका ऐप हमेशा Firebase Android पुस्तकालयों के संगत संस्करणों का उपयोग करेगा।

    (वैकल्पिक) BoM का उपयोग किए बिना Firebase लाइब्रेरी निर्भरताएँ जोड़ें

    यदि आप Firebase BoM का उपयोग नहीं करना चुनते हैं, तो आपको प्रत्येक Firebase लाइब्रेरी संस्करण को उसकी निर्भरता रेखा में निर्दिष्ट करना होगा।

    ध्यान दें कि यदि आप अपने ऐप में एकाधिक फायरबेस लाइब्रेरी का उपयोग करते हैं, तो हम लाइब्रेरी संस्करणों को प्रबंधित करने के लिए बीओएम का उपयोग करने की दृढ़ता से अनुशंसा करते हैं, जो सुनिश्चित करता है कि सभी संस्करण संगत हैं।

    dependencies {
        // Add the dependency for the Firebase ML model downloader library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-ml-modeldownloader:24.1.2'
    // Also add the dependency for the TensorFlow Lite library and specify its version implementation 'org.tensorflow:tensorflow-lite:2.3.0'
    }
  3. अपने ऐप के मेनिफेस्ट में, घोषणा करें कि इंटरनेट अनुमति आवश्यक है:
    <uses-permission android:name="android.permission.INTERNET" />

1. अपना मॉडल परिनियोजित करें

Firebase कंसोल या Firebase Admin Python और Node.js SDKs का उपयोग करके अपने कस्टम TensorFlow मॉडल परिनियोजित करें। कस्टम मॉडल को परिनियोजित और प्रबंधित करें देखें।

अपने फायरबेस प्रोजेक्ट में एक कस्टम मॉडल जोड़ने के बाद, आप अपने द्वारा निर्दिष्ट नाम का उपयोग करके अपने ऐप में मॉडल को संदर्भित कर सकते हैं। किसी भी समय, आप नया TensorFlow Lite मॉडल परिनियोजित कर सकते हैं और getModel() (नीचे देखें) पर कॉल करके नए मॉडल को उपयोगकर्ताओं के डिवाइस पर डाउनलोड कर सकते हैं।

2. मॉडल को डिवाइस में डाउनलोड करें और TensorFlow Lite दुभाषिया को इनिशियलाइज़ करें

अपने ऐप में अपने TensorFlow Lite मॉडल का उपयोग करने के लिए, पहले डिवाइस में मॉडल का नवीनतम संस्करण डाउनलोड करने के लिए Firebase ML SDK का उपयोग करें। फिर, मॉडल के साथ TensorFlow Lite दुभाषिया को इंस्टेंट करें।

मॉडल डाउनलोड शुरू करने के लिए, मॉडल डाउनलोडर की getModel() विधि को कॉल करें, यह निर्दिष्ट करते हुए कि आपने इसे अपलोड करते समय मॉडल को निर्दिष्ट किया था, क्या आप हमेशा नवीनतम मॉडल डाउनलोड करना चाहते हैं, और किन शर्तों के तहत आप डाउनलोड करने की अनुमति देना चाहते हैं।

आप तीन डाउनलोड व्यवहारों में से चुन सकते हैं:

डाउनलोड प्रकार विवरण
LOCAL_MODEL डिवाइस से स्थानीय मॉडल प्राप्त करें। यदि कोई स्थानीय मॉडल उपलब्ध नहीं है, तो यह LATEST_MODEL जैसा व्यवहार करता है। यदि आप मॉडल अद्यतनों की जाँच करने में रुचि नहीं रखते हैं तो इस डाउनलोड प्रकार का उपयोग करें। उदाहरण के लिए, आप मॉडल नामों को पुनः प्राप्त करने के लिए रिमोट कॉन्फिग का उपयोग कर रहे हैं और आप हमेशा नए नामों के तहत मॉडल अपलोड करते हैं (अनुशंसित)।
LOCAL_MODEL_UPDATE_IN_बैकग्राउंड डिवाइस से स्थानीय मॉडल प्राप्त करें और पृष्ठभूमि में मॉडल को अपडेट करना प्रारंभ करें। यदि कोई स्थानीय मॉडल उपलब्ध नहीं है, तो यह LATEST_MODEL जैसा व्यवहार करता है।
नवीनतम मॉडल नवीनतम मॉडल प्राप्त करें। यदि स्थानीय मॉडल नवीनतम संस्करण है, तो स्थानीय मॉडल लौटाता है। अन्यथा, नवीनतम मॉडल डाउनलोड करें। नवीनतम संस्करण डाउनलोड होने तक यह व्यवहार अवरुद्ध रहेगा (अनुशंसित नहीं)। इस व्यवहार का उपयोग केवल उन मामलों में करें जहां आपको स्पष्ट रूप से नवीनतम संस्करण की आवश्यकता है।

जब तक आप यह पुष्टि नहीं कर लेते कि मॉडल डाउनलोड हो गया है, तब तक आपको मॉडल से संबंधित कार्यात्मकता को अक्षम कर देना चाहिए—उदाहरण के लिए, अपने UI के भाग को ग्रे-आउट या छिपा देना चाहिए।

Kotlin+KTX

val conditions = CustomModelDownloadConditions.Builder()
        .requireWifi()  // Also possible: .requireCharging() and .requireDeviceIdle()
        .build()
FirebaseModelDownloader.getInstance()
        .getModel("your_model", DownloadType.LOCAL_MODEL_UPDATE_IN_BACKGROUND,
            conditions)
        .addOnSuccessListener { model: CustomModel? ->
            // Download complete. Depending on your app, you could enable the ML
            // feature, or switch from the local model to the remote model, etc.

            // The CustomModel object contains the local path of the model file,
            // which you can use to instantiate a TensorFlow Lite interpreter.
            val modelFile = model?.file
            if (modelFile != null) {
                interpreter = Interpreter(modelFile)
            }
        }

Java

CustomModelDownloadConditions conditions = new CustomModelDownloadConditions.Builder()
    .requireWifi()  // Also possible: .requireCharging() and .requireDeviceIdle()
    .build();
FirebaseModelDownloader.getInstance()
    .getModel("your_model", DownloadType.LOCAL_MODEL_UPDATE_IN_BACKGROUND, conditions)
    .addOnSuccessListener(new OnSuccessListener<CustomModel>() {
      @Override
      public void onSuccess(CustomModel model) {
        // Download complete. Depending on your app, you could enable the ML
        // feature, or switch from the local model to the remote model, etc.

        // The CustomModel object contains the local path of the model file,
        // which you can use to instantiate a TensorFlow Lite interpreter.
        File modelFile = model.getFile();
        if (modelFile != null) {
            interpreter = new Interpreter(modelFile);
        }
      }
    });

कई ऐप्स अपने प्रारंभिक कोड में डाउनलोड कार्य प्रारंभ करते हैं, लेकिन आप मॉडल का उपयोग करने से पहले किसी भी समय ऐसा कर सकते हैं।

3. इनपुट डेटा पर अनुमान लगाएं

अपने मॉडल का इनपुट और आउटपुट आकार प्राप्त करें

TensorFlow Lite मॉडल दुभाषिया इनपुट के रूप में लेता है और आउटपुट के रूप में एक या अधिक बहुआयामी सरणियाँ बनाता है। इन सरणियों में या तो byte , int , long या float मान होते हैं। इससे पहले कि आप किसी मॉडल को डेटा पास कर सकें या उसके परिणाम का उपयोग कर सकें, आपको अपने मॉडल द्वारा उपयोग की जाने वाली सरणियों की संख्या और आयाम ("आकार") पता होना चाहिए।

यदि आपने स्वयं मॉडल बनाया है, या यदि मॉडल का इनपुट और आउटपुट स्वरूप प्रलेखित है, तो आपके पास पहले से ही यह जानकारी हो सकती है। यदि आप अपने मॉडल के इनपुट और आउटपुट के आकार और डेटा प्रकार को नहीं जानते हैं, तो आप अपने मॉडल का निरीक्षण करने के लिए TensorFlow Lite दुभाषिया का उपयोग कर सकते हैं। उदाहरण के लिए:

अजगर

import tensorflow as tf

interpreter = tf.lite.Interpreter(model_path="your_model.tflite")
interpreter.allocate_tensors()

# Print input shape and type
inputs = interpreter.get_input_details()
print('{} input(s):'.format(len(inputs)))
for i in range(0, len(inputs)):
    print('{} {}'.format(inputs[i]['shape'], inputs[i]['dtype']))

# Print output shape and type
outputs = interpreter.get_output_details()
print('\n{} output(s):'.format(len(outputs)))
for i in range(0, len(outputs)):
    print('{} {}'.format(outputs[i]['shape'], outputs[i]['dtype']))

उदाहरण आउटपुट:

1 input(s):
[  1 224 224   3] <class 'numpy.float32'>

1 output(s):
[1 1000] <class 'numpy.float32'>

दुभाषिया चलाएं

अपने मॉडल के इनपुट और आउटपुट का प्रारूप निर्धारित करने के बाद, अपना इनपुट डेटा प्राप्त करें और डेटा पर कोई भी परिवर्तन करें जो आपके मॉडल के लिए सही आकार का इनपुट प्राप्त करने के लिए आवश्यक हो।

उदाहरण के लिए, यदि आपके पास [1 224 224 3] फ़्लोटिंग-पॉइंट मानों के इनपुट आकार के साथ एक छवि वर्गीकरण मॉडल है, तो आप Bitmap ऑब्जेक्ट से एक इनपुट ByteBuffer उत्पन्न कर सकते हैं जैसा कि निम्नलिखित उदाहरण में दिखाया गया है:

Kotlin+KTX

val bitmap = Bitmap.createScaledBitmap(yourInputImage, 224, 224, true)
val input = ByteBuffer.allocateDirect(224*224*3*4).order(ByteOrder.nativeOrder())
for (y in 0 until 224) {
    for (x in 0 until 224) {
        val px = bitmap.getPixel(x, y)

        // Get channel values from the pixel value.
        val r = Color.red(px)
        val g = Color.green(px)
        val b = Color.blue(px)

        // Normalize channel values to [-1.0, 1.0]. This requirement depends on the model.
        // For example, some models might require values to be normalized to the range
        // [0.0, 1.0] instead.
        val rf = (r - 127) / 255f
        val gf = (g - 127) / 255f
        val bf = (b - 127) / 255f

        input.putFloat(rf)
        input.putFloat(gf)
        input.putFloat(bf)
    }
}

Java

Bitmap bitmap = Bitmap.createScaledBitmap(yourInputImage, 224, 224, true);
ByteBuffer input = ByteBuffer.allocateDirect(224 * 224 * 3 * 4).order(ByteOrder.nativeOrder());
for (int y = 0; y < 224; y++) {
    for (int x = 0; x < 224; x++) {
        int px = bitmap.getPixel(x, y);

        // Get channel values from the pixel value.
        int r = Color.red(px);
        int g = Color.green(px);
        int b = Color.blue(px);

        // Normalize channel values to [-1.0, 1.0]. This requirement depends
        // on the model. For example, some models might require values to be
        // normalized to the range [0.0, 1.0] instead.
        float rf = (r - 127) / 255.0f;
        float gf = (g - 127) / 255.0f;
        float bf = (b - 127) / 255.0f;

        input.putFloat(rf);
        input.putFloat(gf);
        input.putFloat(bf);
    }
}

फिर, मॉडल के आउटपुट को समाहित करने के लिए पर्याप्त रूप से एक ByteBuffer आवंटित करें और TensorFlow Lite दुभाषिया के run() विधि में इनपुट बफर और आउटपुट बफर पास करें। उदाहरण के लिए, [1 1000] फ़्लोटिंग-पॉइंट मानों के आउटपुट आकार के लिए:

Kotlin+KTX

val bufferSize = 1000 * java.lang.Float.SIZE / java.lang.Byte.SIZE
val modelOutput = ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.nativeOrder())
interpreter?.run(input, modelOutput)

Java

int bufferSize = 1000 * java.lang.Float.SIZE / java.lang.Byte.SIZE;
ByteBuffer modelOutput = ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.nativeOrder());
interpreter.run(input, modelOutput);

आप आउटपुट का उपयोग कैसे करते हैं यह आपके द्वारा उपयोग किए जा रहे मॉडल पर निर्भर करता है।

उदाहरण के लिए, यदि आप वर्गीकरण कर रहे हैं, तो अगले चरण के रूप में, आप परिणाम के इंडेक्स को उनके द्वारा दर्शाए जाने वाले लेबल पर मैप कर सकते हैं:

Kotlin+KTX

modelOutput.rewind()
val probabilities = modelOutput.asFloatBuffer()
try {
    val reader = BufferedReader(
            InputStreamReader(assets.open("custom_labels.txt")))
    for (i in probabilities.capacity()) {
        val label: String = reader.readLine()
        val probability = probabilities.get(i)
        println("$label: $probability")
    }
} catch (e: IOException) {
    // File not found?
}

Java

modelOutput.rewind();
FloatBuffer probabilities = modelOutput.asFloatBuffer();
try {
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(getAssets().open("custom_labels.txt")));
    for (int i = 0; i < probabilities.capacity(); i++) {
        String label = reader.readLine();
        float probability = probabilities.get(i);
        Log.i(TAG, String.format("%s: %1.4f", label, probability));
    }
} catch (IOException e) {
    // File not found?
}

परिशिष्ट: मॉडल सुरक्षा

भले ही आप अपने TensorFlow Lite मॉडल को Firebase ML के लिए कैसे उपलब्ध कराते हैं, Firebase ML उन्हें स्थानीय स्टोरेज में मानक क्रमबद्ध प्रोटोबॉफ़ प्रारूप में संग्रहीत करता है।

सिद्धांत रूप में, इसका मतलब है कि कोई भी आपके मॉडल की नकल कर सकता है। हालाँकि, व्यवहार में, अधिकांश मॉडल एप्लिकेशन-विशिष्ट हैं और अनुकूलन द्वारा अस्पष्ट हैं कि जोखिम आपके कोड को अलग करने और पुन: उपयोग करने वाले प्रतियोगियों के समान है। फिर भी, अपने ऐप में कस्टम मॉडल का उपयोग करने से पहले आपको इस जोखिम के बारे में पता होना चाहिए।

एंड्रॉइड एपीआई स्तर 21 (लॉलीपॉप) और नए पर, मॉडल को एक निर्देशिका में डाउनलोड किया जाता है जिसे स्वचालित बैकअप से बाहर रखा गया है।

Android API स्तर 20 और पुराने पर, मॉडल को ऐप-निजी आंतरिक संग्रहण में com.google.firebase.ml.custom.models नामक निर्देशिका में डाउनलोड किया जाता है। यदि आपने BackupAgent का उपयोग करके फ़ाइल बैकअप सक्षम किया है, तो आप इस निर्देशिका को बाहर करना चुन सकते हैं।