您可以使用 Firebase 控制台或 Firebase Admin Python 和 Node.js SDK 部署和管理自定义模型和 AutoML 训练模型。如果您只想部署模型并偶尔更新它,使用 Firebase 控制台通常是最简单的。在与构建管道集成、使用 Colab 或 Jupyter 笔记本以及其他工作流时,Admin SDK 会很有帮助。
在 Firebase 控制台中部署和管理模型
TensorFlow Lite 模型
要使用 Firebase 控制台部署 TensorFlow Lite 模型:
- 在 Firebase 控制台中打开Firebase ML 自定义模型页面。
- 单击添加自定义模型(或添加另一个模型)。
- 指定一个名称,用于在您的 Firebase 项目中识别您的模型,然后上传 TensorFlow Lite 模型文件(通常以
.tflite
或.lite
)。
部署模型后,您可以在自定义页面上找到它。从那里,您可以完成诸如使用新文件更新模型、下载模型以及从项目中删除模型等任务。
使用 Firebase Admin SDK 部署和管理模型
本节介绍如何使用 Admin SDK 完成常见模型部署和管理任务。请参阅Python或Node.js的 SDK 参考以获取更多帮助。
有关正在使用的 SDK 的示例,请参阅Python 快速入门示例和Node.js 快速入门示例。
在你开始之前
如果您还没有 Firebase 项目,请在Firebase 控制台中创建一个新项目。然后,打开您的项目并执行以下操作:
在“设置”页面上,创建一个服务帐户并下载服务帐户密钥文件。请妥善保管此文件,因为它会授予管理员访问您的项目的权限。
在存储页面上,启用云存储。记下您的存储桶名称。
您需要一个 Cloud Storage 存储桶来临时存储模型文件,同时将它们添加到您的 Firebase 项目中。如果您使用的是 Blaze 计划,则可以为此目的创建和使用默认存储桶以外的存储桶。
如果您尚未启用 Firebase ML,请在 Firebase ML 页面上单击开始。
在Google APIs 控制台中,打开您的 Firebase 项目并启用 Firebase ML API。
初始化 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', })
节点.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)
节点.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 | 模型的 ID,您从 AutoML Cloud API 获得。 |
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)
节点.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))
节点.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) {
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 所有带有 display_name : experimental_* 请注意,仅支持前缀匹配。 |
tags | tags: face_detector tags: face_detector AND tags: experimental |
state.published | state.published = true state.published = false |
将筛选器与AND
、 OR
和NOT
运算符以及括号 ( (
, )
) 组合在一起。
更新模型
将模型添加到项目后,您可以更新其显示名称、标签和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)
节点.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)
节点.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);