部署及管理自訂模型

您可以使用 Firebase 控制台,或 Firebase Admin Python 和 Node.js SDK,部署及管理自訂模型和以 AutoML 訓練的模型。如果您只是想部署模型並偶爾更新,通常最簡單的方式是使用 Firebase 控制台。整合建構管道、使用 Colab 或 Jupyter 筆記本,以及其他工作流程時,管理員 SDK 很有幫助。

Firebase 控制台中部署及管理模型

TensorFlow Lite 模型

如要使用 Firebase 控制台部署 TensorFlow Lite 模型,請按照下列步驟操作:

  1. Firebase 控制台中開啟「Firebase ML 自訂模型」頁面
  2. 按一下「新增自訂模型」 (或「新增其他模型」)。
  3. 指定名稱,用於在 Firebase 專案中識別模型,然後上傳 TensorFlow Lite 模型檔案 (通常以 .tflite.lite 結尾)。

模型部署完成後,您可以在「自訂」頁面中找到模型。您可以在這裡完成各項工作,例如使用新檔案更新模型、下載模型,以及從專案中刪除模型。

使用 Firebase Admin SDK 部署及管理模型

本節說明如何使用 Admin SDK 完成常見的模型部署和管理工作。如需其他協助,請參閱 PythonNode.js 的 SDK 參考資料。

如需 SDK 的使用範例,請參閱 Python 快速入門範例Node.js 快速入門範例

事前準備

  1. 如果您還沒有 Firebase 專案,請在 Firebase 控制台中建立新專案。接著開啟專案,然後執行下列操作:

    1. 在「設定」頁面中,建立服務帳戶並下載服務帳戶金鑰檔案。請妥善保管這個檔案,因為這會授予專案管理員存取權。

    2. 在「儲存空間」頁面中啟用 Cloud Storage。記下 bucket 名稱。

      您需要 Cloud Storage bucket,才能在將模型檔案新增至 Firebase 專案時暫時儲存這些檔案。如果採用 Blaze 方案,您可以建立並使用非預設 bucket 來達成這個目的。

    3. 在「Firebase ML」頁面中,如果尚未啟用 Firebase ML,請按一下「開始使用」

  2. Google API 控制台中開啟 Firebase 專案,並啟用 Firebase ML API。

  3. 安裝並初始化 Admin SDK

    初始化 SDK 時,請指定服務帳戶憑證和要用來儲存模型的 Cloud Storage 值區:

    PythonNode.js
    import firebase_admin
    from firebase_admin import ml
    from firebase_admin import credentials
    
    firebase_admin.initialize_app(
      credentials.Certificate('/path/to/your/service_account_key.json'),
      options={
          'storageBucket': 'your-storage-bucket',
      })
    
    const admin = require('firebase-admin');
    const serviceAccount = require('/path/to/your/service_account_key.json');
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      storageBucket: 'your-storage-bucket',
    });
    const ml = admin.machineLearning();
    

可部署模型

TensorFlow Lite 檔案

如要從模型檔案部署 TensorFlow Lite 模型,請將模型上傳至專案,然後發布:

PythonNode.js
# First, import and initialize the SDK as shown above.

# Load a tflite file and upload it to Cloud Storage
source = ml.TFLiteGCSModelSource.from_tflite_model_file('example.tflite')

# Create the model object
tflite_format = ml.TFLiteFormat(model_source=source)
model = ml.Model(
    display_name="example_model",  # This is the name you use from your app to load the model.
    tags=["examples"],             # Optional tags for easier management.
    model_format=tflite_format)

# Add the model to your Firebase project and publish it
new_model = ml.create_model(model)
ml.publish_model(new_model.model_id)
// First, import and initialize the SDK as shown above.

(async () => {
  // Upload the tflite file to Cloud Storage
  const storageBucket = admin.storage().bucket('your-storage-bucket');
  const files = await storageBucket.upload('./example.tflite');

  // Create the model object and add the model to your Firebase project.
  const bucket = files[0].metadata.bucket;
  const name = files[0].metadata.name;
  const gcsUri = `gs:/⁠/${bucket}/${name}`;
  const model = await ml.createModel({
    displayName: 'example_model',  // This is the name you use from your app to load the model.
    tags: ['examples'],  // Optional tags for easier management.
    tfliteModel: { gcsTfliteUri: gcsUri },
  });

  // Publish the model.
  await ml.publishModel(model.modelId);

  process.exit();
})().catch(console.error);

TensorFlow 和 Keras 模型

使用 Python SDK,您可以將模型從 TensorFlow SavedModel 格式轉換為 TensorFlow Lite,並在單一步驟中上傳至 Cloud Storage bucket。接著,以部署 TensorFlow Lite 檔案的方式部署模型。

Python
# First, import and initialize the SDK as shown above.

# Convert the model to TensorFlow Lite and upload it to Cloud Storage
source = ml.TFLiteGCSModelSource.from_saved_model('./model_directory')

# Create the model object
tflite_format = ml.TFLiteFormat(model_source=source)
model = ml.Model(
    display_name="example_model",  # This is the name you use from your app to load the model.
    tags=["examples"],             # Optional tags for easier management.
    model_format=tflite_format)

# Add the model to your Firebase project and publish it
new_model = ml.create_model(model)
ml.publish_model(new_model.model_id)

如果您有 Keras 模型,也可以將其轉換為 TensorFlow Lite,然後在單一步驟中上傳。您可以將 Keras 模型儲存至 HDF5 檔案:

Python
import tensorflow as tf

# Load a Keras model, convert it to TensorFlow Lite, and upload it to Cloud Storage
model = tf.keras.models.load_model('your_model.h5')
source = ml.TFLiteGCSModelSource.from_keras_model(model)

# Create the model object, add the model to your project, and publish it. (See
# above.)
# ...

或者,您也可以直接從訓練指令碼轉換及上傳 Keras 模型:

Python
import tensorflow as tf

# Create a simple Keras model.
x = [-1, 0, 1, 2, 3, 4]
y = [-3, -1, 1, 3, 5, 7]

model = tf.keras.models.Sequential(
    [tf.keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x, y, epochs=3)

# Convert the model to TensorFlow Lite and upload it to Cloud Storage
source = ml.TFLiteGCSModelSource.from_keras_model(model)

# Create the model object, add the model to your project, and publish it. (See
# above.)
# ...

AutoML TensorFlow Lite 模型

如果您使用 AutoML Cloud APIGoogle Cloud 控制台 UI 訓練 Edge 模型,可以使用 Admin SDK 將模型部署至 Firebase。

您需要指定模型的資源 ID,這是一個字串,看起來類似以下範例:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER 包含模型的 Cloud Storage 值區專案編號。這可能是您的 Firebase 專案或其他專案。Google Cloud 您可以在 Firebase 控制台的「設定」頁面或 Google Cloud 控制台資訊主頁上找到這個值。
STORAGE_LOCATION 包含模型的 Cloud Storage 值區資源位置。這個值一律為 us-central1
MODEL_ID 模型 ID (從 AutoML Cloud API 取得)。
PythonNode.js
# First, import and initialize the SDK as shown above.

# Get a reference to the AutoML model
source = ml.TFLiteAutoMlSource('projects/{}/locations/{}/models/{}'.format(
    # See above for information on these values.
    project_number,
    storage_location,
    model_id
))

# Create the model object
tflite_format = ml.TFLiteFormat(model_source=source)
model = ml.Model(
    display_name="example_model",  # This is the name you will use from your app to load the model.
    tags=["examples"],             # Optional tags for easier management.
    model_format=tflite_format)

# Add the model to your Firebase project and publish it
new_model = ml.create_model(model)
new_model.wait_for_unlocked()
ml.publish_model(new_model.model_id)
// First, import and initialize the SDK as shown above.

(async () => {
  // Get a reference to the AutoML model. See above for information on these
  // values.
  const automlModel = `projects/${projectNumber}/locations/${storageLocation}/models/${modelId}`;

  // Create the model object and add the model to your Firebase project.
  const model = await ml.createModel({
    displayName: 'example_model',  // This is the name you use from your app to load the model.
    tags: ['examples'],  // Optional tags for easier management.
    tfliteModel: { automlModel: automlModel },
  });

  // Wait for the model to be ready.
  await model.waitForUnlocked();

  // Publish the model.
  await ml.publishModel(model.modelId);

  process.exit();
})().catch(console.error);

列出專案的模型

您可以列出專案的模型,並視需要篩選結果:

PythonNode.js
# First, import and initialize the SDK as shown above.

face_detectors = ml.list_models(list_filter="tags: face_detector").iterate_all()
print("Face detection models:")
for model in face_detectors:
  print('{} (ID: {})'.format(model.display_name, model.model_id))
// First, import and initialize the SDK as shown above.

(async () => {
  let listOptions = {filter: 'tags: face_detector'}
  let models;
  let pageToken = null;
  do {
    if (pageToken) listOptions.pageToken = pageToken;
    ({models, pageToken} = await ml.listModels(listOptions));
    for (const model of models) {
      console.log(`${model.displayName} (ID: ${model.modelId})`);
    }
  } while (pageToken != null);

  process.exit();
})().catch(console.error);

您可以依下列欄位篩選:

欄位 範例
display_name display_name = example_model
display_name != example_model

所有前置字串為 experimental_ 的顯示名稱:

display_name : experimental_*

請注意,系統只支援前置字元比對。

tags tags: face_detector
tags: face_detector AND tags: experimental
state.published state.published = true
state.published = false

使用 ANDORNOT 運算子和括號 (()) 合併篩選器。

可更新模型

將模型新增至專案後,您可以更新模型的顯示名稱、標記和 tflite 模型檔案:

PythonNode.js
# First, import and initialize the SDK as shown above.

model = ...   # Model object from create_model(), get_model(), or list_models()

# Update the model with a new tflite model. (You could also update with a
# `TFLiteAutoMlSource`)
source = ml.TFLiteGCSModelSource.from_tflite_model_file('example_v2.tflite')
model.model_format = ml.TFLiteFormat(model_source=source)

# Update the model's display name.
model.display_name = "example_model"

# Update the model's tags.
model.tags = ["examples", "new_models"]

# Add a new tag.
model.tags += "experimental"

# After you change the fields you want to update, save the model changes to
# Firebase and publish it.
updated_model = ml.update_model(model)
ml.publish_model(updated_model.model_id)
// First, import and initialize the SDK as shown above.

(async () => {
  const model = ... // Model object from createModel(), getModel(), or listModels()

  // Upload a new tflite file to Cloud Storage.
  const files = await storageBucket.upload('./example_v2.tflite');
  const bucket = files[0].metadata.bucket;
  const name = files[0].metadata.name;

  // Update the model. Any fields you omit will be unchanged.
  await ml.updateModel(model.modelId, {
    displayName: 'example_model',  // Update the model's display name.
    tags: model.tags.concat(['new']),  // Add a tag.
    tfliteModel: {gcsTfliteUri: `gs:/⁠/${bucket}/${name}`},
  });

  process.exit();
})().catch(console.error);

取消發布或刪除模型

如要取消發布或刪除模型,請將模型 ID 傳遞至取消發布或刪除方法。取消發布模型後,模型仍會保留在專案中,但應用程式無法下載。刪除模型後,系統會從專案中完全移除該模型。(在標準工作流程中,不應取消發布模型,但您可以藉此立即取消發布您不慎發布的新模型,且該模型尚未在任何地方使用,或是在使用者下載「不良」模型比收到模型找不到錯誤更糟的情況下使用)。

如果還是沒有 Model 物件的參照,您可能需要透過篩選條件列出專案的模型,藉此取得模型 ID。舉例來說,如要刪除所有標記為「face_detector」的模型:

PythonNode.js
# First, import and initialize the SDK as shown above.

face_detectors = ml.list_models(list_filter="tags: 'face_detector'").iterate_all()
for model in face_detectors:
  ml.delete_model(model.model_id)
// First, import and initialize the SDK as shown above.

(async () => {
  let listOptions = {filter: 'tags: face_detector'}
  let models;
  let pageToken = null;
  do {
    if (pageToken) listOptions.pageToken = pageToken;
    ({models, pageToken} = await ml.listModels(listOptions));
    for (const model of models) {
      await ml.deleteModel(model.modelId);
    }
  } while (pageToken != null);

  process.exit();
})().catch(console.error);