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

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

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

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

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

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

    साथ ही, फायरबेस एमएल मॉडल डाउनलोडर स्थापित करने के हिस्से के रूप में, आपको अपने ऐप में TensorFlow Lite SDK जोड़ना होगा।

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.8.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")
    }

    फायरबेस एंड्रॉइड बीओएम का उपयोग करके, आपका ऐप हमेशा फायरबेस एंड्रॉइड लाइब्रेरी के संगत संस्करणों का उपयोग करेगा।

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

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

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

    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.2.3")
    // Also add the dependency for the TensorFlow Lite library and specify its version implementation("org.tensorflow:tensorflow-lite:2.3.0")
    }
    कोटलिन-विशिष्ट लाइब्रेरी मॉड्यूल खोज रहे हैं? अक्टूबर 2023 (फायरबेस बीओएम 32.5.0) से शुरू होकर, कोटलिन और जावा डेवलपर्स दोनों मुख्य लाइब्रेरी मॉड्यूल पर निर्भर हो सकते हैं (विवरण के लिए, इस पहल के बारे में अक्सर पूछे जाने वाले प्रश्न देखें)।
  3. अपने ऐप के मेनिफ़ेस्ट में घोषित करें कि इंटरनेट अनुमति आवश्यक है:
    <uses-permission android:name="android.permission.INTERNET" />

1. अपना मॉडल तैनात करें

फायरबेस कंसोल या फायरबेस एडमिन पायथन और नोड.जेएस एसडीके का उपयोग करके अपने कस्टम टेन्सरफ्लो मॉडल को तैनात करें। कस्टम मॉडल तैनात और प्रबंधित करें देखें।

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

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

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

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

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

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

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

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 (लॉलीपॉप) और नए पर, मॉडल को एक निर्देशिका में डाउनलोड किया जाता है जिसे स्वचालित बैकअप से बाहर रखा गया है।

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