在 Apple 平台上使用自訂 TensorFlow Lite 模型

如果您的應用程式使用自訂TensorFlow Lite模型,您可以使用 Firebase ML 來部署模型。透過使用 Firebase 部署模型,您可以減少應用程式的初始下載大小並更新套用的 ML 模型,而無需發布應用程式的新版本。而且,透過遠端配置和 A/B 測試,您可以動態地為不同的使用者群組提供不同的模型。

先決條件

  • MLModelDownloader程式庫僅適用於 Swift。
  • TensorFlow Lite 僅在使用 iOS 9 及更高版本的裝置上運作。

TensorFlow Lite 模型

TensorFlow Lite 模型是經過最佳化以在行動裝置上運行的 ML 模型。若要取得 TensorFlow Lite 模型:

在你開始之前

若要將 TensorFlowLite 與 Firebase 結合使用,您必須使用 CocoaPods,因為 TensorFlowLite 目前不支援使用 Swift Package Manager 安裝。有關如何安裝MLModelDownloader說明,請參閱CocoaPods 安裝指南

安裝後,導入 Firebase 和 TensorFlowLite 以便使用它們。

迅速

import FirebaseMLModelDownloader
import TensorFlowLite

1. 部署您的模型

使用 Firebase 控制台或 Firebase 管理 Python 和 Node.js SDK 部署自訂 TensorFlow 模型。請參閱部署和管理自訂模型

將自訂模型新增至 Firebase 專案後,您可以使用指定的名稱在應用程式中引用該模型。您可以隨時部署新的 TensorFlow Lite 模型,並透過呼叫getModel()將新模型下載到使用者的裝置上(請參閱下文)。

2. 將模型下載到裝置並初始化 TensorFlow Lite 解釋器

若要在應用程式中使用 TensorFlow Lite 模型,請先使用 Firebase ML SDK 將最新版本的模型下載到裝置。

若要開始模型下載,請呼叫模型下載器的getModel()方法,指定上傳模型時為模型指派的名稱、是否要始終下載最新模型以及允許下載的條件。

您可以從三種下載行為中進行選擇:

下載類型描述
localModel從設備取得本地模型。如果沒有可用的本機模型,則其行為類似於latestModel 。如果您對檢查模型更新不感興趣,請使用此下載類型。例如,您使用遠端配置來檢索模型名稱,並且始終以新名稱上傳模型(建議)。
localModelUpdateInBackground從裝置取得本機模型並開始在背景更新模型。如果沒有可用的本機模型,則其行為類似於latestModel
latestModel取得最新型號。如果本機模型是最新版本,則傳回本機模型。否則,請下載最新型號。此行為將被阻止,直到下載最新版本(不建議)。僅在您明確需要最新版本的情況下才使用此行為。

您應該停用與模型相關的功能(例如,灰顯或隱藏部分 UI),直到您確認模型已下載。

迅速

let conditions = ModelDownloadConditions(allowsCellularAccess: false)
ModelDownloader.modelDownloader()
    .getModel(name: "your_model",
              downloadType: .localModelUpdateInBackground,
              conditions: conditions) { result in
        switch (result) {
        case .success(let customModel):
            do {
                // 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.
                let interpreter = try Interpreter(modelPath: customModel.path)
            } catch {
                // Error. Bad model file?
            }
        case .failure(let error):
            // Download was unsuccessful. Don't enable ML features.
            print(error)
        }
}

許多應用程式在其初始化程式碼中啟動下載任務,但您可以在需要使用模型之前隨時執行此操作。

3. 對輸入資料進行推理

取得模型的輸入和輸出形狀

TensorFlow Lite 模型解釋器將一個或多個多維數組作為輸入並產生輸出。這些陣列包含byteintlongfloat值。在將資料傳遞到模型或使用其結果之前,您必須知道模型使用的陣列的數量和維度(「形狀」)。

如果您自己建立模型,或者模型的輸入和輸出格式已記錄,您可能已經擁有此資訊。如果您不知道模型輸入和輸出的形狀和資料類型,可以使用 TensorFlow Lite 解釋器檢查模型。例如:

Python

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]浮點數值,則您可能必須將影像的色彩值縮放到浮點範圍,如下例所示:

迅速

let image: CGImage = // Your input image
guard let context = CGContext(
  data: nil,
  width: image.width, height: image.height,
  bitsPerComponent: 8, bytesPerRow: image.width * 4,
  space: CGColorSpaceCreateDeviceRGB(),
  bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue
) else {
  return false
}

context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
guard let imageData = context.data else { return false }

var inputData = Data()
for row in 0 ..&lt; 224 {
  for col in 0 ..&lt; 224 {
    let offset = 4 * (row * context.width + col)
    // (Ignore offset 0, the unused alpha channel)
    let red = imageData.load(fromByteOffset: offset+1, as: UInt8.self)
    let green = imageData.load(fromByteOffset: offset+2, as: UInt8.self)
    let blue = imageData.load(fromByteOffset: offset+3, as: UInt8.self)

    // Normalize channel values to [0.0, 1.0]. This requirement varies
    // by model. For example, some models might require values to be
    // normalized to the range [-1.0, 1.0] instead, and others might
    // require fixed-point values or the original bytes.
    var normalizedRed = Float32(red) / 255.0
    var normalizedGreen = Float32(green) / 255.0
    var normalizedBlue = Float32(blue) / 255.0

    // Append normalized values to Data object in RGB order.
    let elementSize = MemoryLayout.size(ofValue: normalizedRed)
    var bytes = [UInt8](repeating: 0, count: elementSize)
    memcpy(&amp;bytes, &amp;normalizedRed, elementSize)
    inputData.append(&amp;bytes, count: elementSize)
    memcpy(&amp;bytes, &amp;normalizedGreen, elementSize)
    inputData.append(&amp;bytes, count: elementSize)
    memcpy(&ammp;bytes, &amp;normalizedBlue, elementSize)
    inputData.append(&amp;bytes, count: elementSize)
  }
}

然後,將輸入NSData複製到解釋器並運行它:

迅速

try interpreter.allocateTensors()
try interpreter.copy(inputData, toInputAt: 0)
try interpreter.invoke()

您可以透過呼叫解釋器的output(at:)方法來取得模型的輸出。如何使用輸出取決於您所使用的型號。

例如,如果您正在執行分類,下一步,您可以將結果的索引對應到它們代表的標籤:

迅速

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: "retrained_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])")
}

附錄:模型安全性

無論您如何使 TensorFlow Lite 模型可供 Firebase ML 使用,Firebase ML 都會將它們以標準序列化 protobuf 格式儲存在本機儲存中。

從理論上講,這意味著任何人都可以複製您的模型。然而,在實踐中,大多數模型都是特定於應用程式的,並且因最佳化而變得混亂,因此風險類似於競爭對手反彙編和重複使用您的程式碼。儘管如此,在應用程式中使用自訂模型之前,您應該意識到這種風險。