लीगेसी कस्टम मॉडल एपीआई से माइग्रेट करें

Firebase/MLModelInterpreter लाइब्रेरी का संस्करण 0.20.0 एक नई getLatestModelFilePath() विधि पेश करता है, जो कस्टम मॉडल के डिवाइस पर स्थान प्राप्त करता है। आप इस विधि का उपयोग सीधे TensorFlow Lite Interpreter ऑब्जेक्ट को इंस्टेंट करने के लिए कर सकते हैं, जिसे आप फायरबेस के ModelInterpreter रैपर के बजाय उपयोग कर सकते हैं।

आगे बढ़ते हुए, यह पसंदीदा दृष्टिकोण है। क्योंकि TensorFlow Lite दुभाषिया संस्करण अब Firebase लाइब्रेरी संस्करण के साथ युग्मित नहीं है, आपके पास जब चाहें तब TensorFlow Lite के नए संस्करणों में अपग्रेड करने के लिए अधिक लचीलापन है, या अधिक आसानी से कस्टम TensorFlow Lite बिल्ड का उपयोग करें।

यह पृष्ठ दिखाता है कि आप ModelInterpreter उपयोग करने से टेन्सरफ्लो लाइट Interpreter पर कैसे स्थानांतरित हो सकते हैं।

1. परियोजना निर्भरताएँ अद्यतन करें

Firebase/MLModelInterpreter लाइब्रेरी (या नया) और TensorFlow Lite लाइब्रेरी के संस्करण 0.20.0 को शामिल करने के लिए अपने प्रोजेक्ट की पॉडफाइल को अपडेट करें:

पहले

तीव्र

pod 'Firebase/MLModelInterpreter', '0.19.0'

उद्देश्य सी

pod 'Firebase/MLModelInterpreter', '0.19.0'

बाद

तीव्र

pod 'Firebase/MLModelInterpreter', '~> 0.20.0'
pod 'TensorFlowLiteSwift'

उद्देश्य सी

pod 'Firebase/MLModelInterpreter', '~> 0.20.0'
pod 'TensorFlowLiteObjC'

2. फायरबेस मॉडलइंटरप्रेटर के बजाय एक टेन्सरफ्लो लाइट दुभाषिया बनाएं

फायरबेस ModelInterpreter बनाने के बजाय, getLatestModelFilePath() के साथ डिवाइस पर मॉडल का स्थान प्राप्त करें और TensorFlow Lite Interpreter बनाने के लिए इसका उपयोग करें।

पहले

तीव्र

let remoteModel = CustomRemoteModel(
    name: "your_remote_model"  // The name you assigned in the Firebase console.
)
interpreter = ModelInterpreter.modelInterpreter(remoteModel: remoteModel)

उद्देश्य सी

// Initialize using the name you assigned in the Firebase console.
FIRCustomRemoteModel *remoteModel =
        [[FIRCustomRemoteModel alloc] initWithName:@"your_remote_model"];
interpreter = [FIRModelInterpreter modelInterpreterForRemoteModel:remoteModel];

बाद

तीव्र

let remoteModel = CustomRemoteModel(
    name: "your_remote_model"  // The name you assigned in the Firebase console.
)
ModelManager.modelManager().getLatestModelFilePath(remoteModel) { (remoteModelPath, error) in
    guard error == nil, let remoteModelPath = remoteModelPath else { return }
    do {
        interpreter = try Interpreter(modelPath: remoteModelPath)
    } catch {
        // Error?
    }
}

उद्देश्य सी

FIRCustomRemoteModel *remoteModel =
        [[FIRCustomRemoteModel alloc] initWithName:@"your_remote_model"];
[[FIRModelManager modelManager] getLatestModelFilePath:remoteModel
                                            completion:^(NSString * _Nullable filePath,
                                                         NSError * _Nullable error) {
    if (error != nil || filePath == nil) { return; }

    NSError *tfError = nil;
    interpreter = [[TFLInterpreter alloc] initWithModelPath:filePath error:&tfError];
}];

3. इनपुट और आउटपुट तैयारी कोड अपडेट करें

ModelInterpreter के साथ, जब आप मॉडल चलाते हैं तो आप ModelInputOutputOptions ऑब्जेक्ट को इंटरप्रेटर में पास करके मॉडल के इनपुट और आउटपुट आकार निर्दिष्ट करते हैं।

TensorFlow Lite दुभाषिया के लिए, आप मॉडल के इनपुट और आउटपुट के लिए स्थान आवंटित करने के लिए allocateTensors() को कॉल करते हैं, फिर अपने इनपुट डेटा को इनपुट टेंसर पर कॉपी करते हैं।

उदाहरण के लिए, यदि आपके मॉडल में इनपुट आकार [1 224 224 3] float मान और आउटपुट आकार [1 1000] float मान है, तो ये परिवर्तन करें:

पहले

तीव्र

let ioOptions = ModelInputOutputOptions()
do {
    try ioOptions.setInputFormat(
        index: 0,
        type: .float32,
        dimensions: [1, 224, 224, 3]
    )
    try ioOptions.setOutputFormat(
        index: 0,
        type: .float32,
        dimensions: [1, 1000]
    )
} catch let error as NSError {
    print("Failed to set input or output format with error: \(error.localizedDescription)")
}

let inputs = ModelInputs()
do {
    let inputData = Data()
    // Then populate with input data.

    try inputs.addInput(inputData)
} catch let error {
    print("Failed to add input: \(error)")
}

interpreter.run(inputs: inputs, options: ioOptions) { outputs, error in
    guard error == nil, let outputs = outputs else { return }
    // Process outputs
    // ...
}

उद्देश्य सी

FIRModelInputOutputOptions *ioOptions = [[FIRModelInputOutputOptions alloc] init];
NSError *error;
[ioOptions setInputFormatForIndex:0
                             type:FIRModelElementTypeFloat32
                       dimensions:@[@1, @224, @224, @3]
                            error:&error];
if (error != nil) { return; }
[ioOptions setOutputFormatForIndex:0
                              type:FIRModelElementTypeFloat32
                        dimensions:@[@1, @1000]
                             error:&error];
if (error != nil) { return; }

FIRModelInputs *inputs = [[FIRModelInputs alloc] init];
NSMutableData *inputData = [[NSMutableData alloc] initWithCapacity:0];
// Then populate with input data.

[inputs addInput:inputData error:&error];
if (error != nil) { return; }

[interpreter runWithInputs:inputs
                   options:ioOptions
                completion:^(FIRModelOutputs * _Nullable outputs,
                             NSError * _Nullable error) {
  if (error != nil || outputs == nil) {
    return;
  }
  // Process outputs
  // ...
}];

बाद

तीव्र

do {
    try interpreter.allocateTensors()

    let inputData = Data()
    // Then populate with input data.

    try interpreter.copy(inputData, toInputAt: 0)

    try interpreter.invoke()
} catch let err {
    print(err.localizedDescription)
}

उद्देश्य सी

NSError *error = nil;

[interpreter allocateTensorsWithError:&error];
if (error != nil) { return; }

TFLTensor *input = [interpreter inputTensorAtIndex:0 error:&error];
if (error != nil) { return; }

NSMutableData *inputData = [[NSMutableData alloc] initWithCapacity:0];
// Then populate with input data.

[input copyData:inputData error:&error];
if (error != nil) { return; }

[interpreter invokeWithError:&error];
if (error != nil) { return; }

4. आउटपुट हैंडलिंग कोड अपडेट करें

अंत में, ModelOutputs ऑब्जेक्ट के output() विधि के साथ मॉडल का आउटपुट प्राप्त करने के बजाय, दुभाषिया से आउटपुट टेंसर प्राप्त करें और उसके डेटा को आपके उपयोग के मामले में सुविधाजनक संरचना में परिवर्तित करें।

उदाहरण के लिए, यदि आप वर्गीकरण कर रहे हैं, तो आप निम्नलिखित जैसे परिवर्तन कर सकते हैं:

पहले

तीव्र

let output = try? outputs.output(index: 0) as? [[NSNumber]]
let probabilities = output?[0]

guard let labelPath = Bundle.main.path(
    forResource: "custom_labels",
    ofType: "txt"
) else { return }
let fileContents = try? String(contentsOfFile: labelPath)
guard let labels = fileContents?.components(separatedBy: "\n") else { return }

for i in 0 ..< labels.count {
    if let probability = probabilities?[i] {
        print("\(labels[i]): \(probability)")
    }
}

उद्देश्य सी

// Get first and only output of inference with a batch size of 1
NSError *error;
NSArray *probabilites = [outputs outputAtIndex:0 error:&error][0];
if (error != nil) { return; }

NSString *labelPath = [NSBundle.mainBundle pathForResource:@"retrained_labels"
                                                    ofType:@"txt"];
NSString *fileContents = [NSString stringWithContentsOfFile:labelPath
                                                   encoding:NSUTF8StringEncoding
                                                      error:&error];
if (error != nil || fileContents == NULL) { return; }
NSArray<NSString *> *labels = [fileContents componentsSeparatedByString:@"\n"];
for (int i = 0; i < labels.count; i++) {
    NSString *label = labels[i];
    NSNumber *probability = probabilites[i];
    NSLog(@"%@: %f", label, probability.floatValue);
}

बाद

तीव्र

do {
    // After calling interpreter.invoke():
    let output = try interpreter.output(at: 0)
    let probabilities =
            UnsafeMutableBufferPointer<Float32>.allocate(capacity: 1000)
    output.data.copyBytes(to: probabilities)

    guard let labelPath = Bundle.main.path(
        forResource: "custom_labels",
        ofType: "txt"
    ) else { return }
    let fileContents = try? String(contentsOfFile: labelPath)
    guard let labels = fileContents?.components(separatedBy: "\n") else { return }

    for i in labels.indices {
        print("\(labels[i]): \(probabilities[i])")
    }
} catch let err {
    print(err.localizedDescription)
}

उद्देश्य सी

NSError *error = nil;

TFLTensor *output = [interpreter outputTensorAtIndex:0 error:&error];
if (error != nil) { return; }

NSData *outputData = [output dataWithError:&error];
if (error != nil) { return; }

Float32 probabilities[outputData.length / 4];
[outputData getBytes:&probabilities length:outputData.length];

NSString *labelPath = [NSBundle.mainBundle pathForResource:@"custom_labels"
                                                    ofType:@"txt"];
NSString *fileContents = [NSString stringWithContentsOfFile:labelPath
                                                   encoding:NSUTF8StringEncoding
                                                      error:&error];
if (error != nil || fileContents == nil) { return; }

NSArray<NSString *> *labels = [fileContents componentsSeparatedByString:@"\n"];
for (int i = 0; i < labels.count; i++) {
    NSLog(@"%@: %f", labels[i], probabilities[i]);
}