Save the date - Google I/O returns May 18-20. Register to get the most out of the digital experience: Build your schedule, reserve space, participate in Q&As, earn Google Developer profile badges, and more. Register now
本頁面由 Cloud Translation API 翻譯而成。
Switch to English

部署和管理自定義模型

您可以使用Firebase控制台或Firebase Admin Python和Node.js SDK部署和管理自定義模型和經過AutoML訓練的模型。如果您只想部署模型並偶爾進行更新,則使用Firebase控制台通常最簡單。在與構建管道集成,與Colab或Jupyter筆記本一起使用以及其他工作流程時,Admin 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. 在“存儲”頁面上,啟用“雲存儲”。記下您的存儲桶名稱。

      在將模型文件添加到Firebase項目中時,您需要一個Cloud Storage存儲桶來臨時存儲模型文件。如果您使用的是Blaze計劃,則可以為此目的創建和使用默認桶以外的其他桶。

    3. 如果您尚未啟用Firebase ML,請在Firebase ML頁面上,單擊“入門”

  2. Google API控制台中,打開Firebase項目並啟用Firebase ML API。

  3. 安裝並初始化Admin SDK

    初始化SDK時,請指定服務帳戶憑據和要用於存儲模型的Cloud Storage存儲桶:

    Python

    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',
      })
    

    Node.js

    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模型,請將其上傳到您的項目中,然後發布:

Python

# 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)

Node.js

// 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保存的模型格式轉換為TensorFlow Lite並將其上傳到Cloud Storage存儲桶。然後,以與部署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並在一個步驟中上傳它。您可以使用保存到HDF5文件的Keras模型:

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 API或Google Cloud Console UI訓練了Edge模型,則可以使用Admin SDK將模型部署到Firebase。

您將需要指定模型的資源標識符,該標識符是類似於以下示例的字符串:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER包含模型的Cloud Storage存儲桶的項目編號。這可能是您的Firebase項目或另一個Google Cloud項目。您可以在Firebase控制台或Google Cloud Console儀表板的“設置”頁面上找到此值。
STORAGE_LOCATION包含模型的Cloud Storage存儲桶的資源位置。此值始終是us-central1
MODEL_ID您從AutoML Cloud API獲得的模型ID。

Python

# 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)

Node.js

// 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);

列出您的項目模型

您可以列出項目的模型,可以選擇過濾結果:

Python

# 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))

Node.js

08十年10

您可以按以下字段進行過濾:

場地例子
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模型文件:

Python

# 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)

Node.js

// 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”的模型:

Python

# 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)

Node.js

// 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);