Triển khai và quản lý các mô hình tuỳ chỉnh

Bạn có thể triển khai và quản lý mô hình tuỳ chỉnh cũng như mô hình được huấn luyện bằng AutoML bằng một trong hai cách sau: bảng điều khiển của Firebase hoặc SDK Node.js và Python Admin của Firebase. Nếu bạn chỉ muốn triển khai một mô hình và thỉnh thoảng cập nhật mô hình đó, cách đơn giản nhất là hãy sử dụng bảng điều khiển của Firebase. SDK dành cho quản trị viên có thể hữu ích khi tích hợp với tạo quy trình, làm việc với sổ tay Colab hoặc Jupyter và các quy trình làm việc khác.

Triển khai và quản lý các mô hình trong bảng điều khiển của Firebase

Mô hình TensorFlow Lite

Cách triển khai mô hình TensorFlow Lite bằng bảng điều khiển của Firebase:

  1. Mở trang Mô hình tuỳ chỉnh học máy của Firebase trong bảng điều khiển của Firebase.
  2. Nhấp vào Thêm mô hình tuỳ chỉnh (hoặc Thêm mô hình khác).
  3. Chỉ định tên sẽ được dùng để xác định mô hình trong Firebase dự án, sau đó tải tệp mô hình TensorFlow Lite lên (thường kết thúc bằng .tflite hoặc .lite).

Sau khi triển khai mô hình, bạn có thể tìm thấy mô hình đó trên Trang tuỳ chỉnh. Từ đó, bạn có thể hoàn thành những công việc như cập nhật mô hình bằng một tệp mới, tải mô hình phân bổ và xoá mô hình khỏi dự án của bạn.

Triển khai và quản lý các mô hình bằng SDK dành cho quản trị viên của Firebase

Phần này trình bày cách hoàn tất việc triển khai và quản lý mô hình chung công việc bằng SDK dành cho quản trị viên. Xem tài liệu tham khảo SDK cho Python hoặc Node.js để được trợ giúp thêm.

Để biết ví dụ về SDK được sử dụng, hãy xem Mẫu khởi động nhanh PythonMẫu bắt đầu nhanh Node.js.

Trước khi bắt đầu

  1. Nếu bạn chưa có dự án Firebase, hãy tạo một dự án mới trong Bảng điều khiển của Firebase. Sau đó, mở dự án của bạn và hãy làm như sau:

    1. Trên trang Cài đặt, hãy tạo một tài khoản dịch vụ rồi tải tệp khoá tài khoản dịch vụ xuống. Hãy giữ tệp này an toàn vì cấp cho quản trị viên quyền truy cập vào dự án của bạn.

    2. Trên trang Bộ nhớ, hãy bật Cloud Storage. Ghi lại tên bộ chứa.

      Bạn cần có một bộ chứa trên Cloud Storage để tạm thời lưu trữ các tệp mô hình khi thêm chúng vào dự án Firebase. Nếu bạn đang ở Blaze bạn có thể tạo và sử dụng một bộ chứa khác với bộ chứa mặc định cho mục đích.

    3. Trên trang Máy học của Firebase, hãy nhấp vào Bắt đầu nếu bạn chưa bật Firebase ML.

  2. Trong bảng điều khiển API của Google, hãy mở Firebase dự án và bật Firebase ML API.

  3. Cài đặt và khởi chạy SDK dành cho quản trị viên.

    Khi bạn khởi chạy SDK, hãy chỉ định thông tin xác thực tài khoản dịch vụ của bạn và bộ chứa Cloud Storage mà bạn muốn sử dụng để lưu trữ các mô hình của mình:

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

Triển khai mô hình

Tệp TensorFlow Lite

Để triển khai mô hình TensorFlow Lite từ tệp mô hình, hãy tải tệp đó lên dự án của bạn rồi xuất bản:

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

Mô hình TensorFlow và Keras

Với SDK Python, bạn có thể chuyển đổi một mô hình từ định dạng mô hình đã lưu trên TensorFlow lên TensorFlow Lite rồi tải lên bộ chứa Cloud Storage của bạn trong một . Sau đó, hãy triển khai mã này giống như cách bạn triển khai tệp 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)

Nếu có mô hình Keras, bạn cũng có thể chuyển đổi mô hình đó thành TensorFlow Lite rồi tải lên chỉ trong một bước duy nhất. Bạn có thể sử dụng mô hình Keras được lưu vào tệp 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.)
# ...

Hoặc bạn có thể chuyển đổi và tải mô hình Keras lên ngay từ tập lệnh huấn luyện:

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

Mô hình AutoML TensorFlow Lite

Nếu bạn đã huấn luyện một mô hình Edge bằng AutoML Cloud API hoặc thông qua giao diện người dùng của bảng điều khiển Google Cloud, bạn có thể triển khai mô hình cho Firebase bằng SDK dành cho quản trị viên.

Bạn sẽ cần chỉ định giá trị nhận dạng tài nguyên của mô hình, đây là một chuỗi sẽ có dạng như ví dụ sau:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER Số dự án của bộ chứa Cloud Storage chứa model. Đây có thể là dự án Firebase của bạn hoặc một Google Cloud khác dự án. Bạn có thể tìm thấy giá trị này trên trang Cài đặt của bảng điều khiển của Firebase hoặc trang tổng quan của bảng điều khiển Google Cloud.
STORAGE_LOCATION Vị trí tài nguyên của bộ chứa Cloud Storage chứa mô hình. Giá trị này luôn là us-central1.
MODEL_ID Mã mô hình mà bạn nhận được từ 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)

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

Liệt kê các mô hình của dự án

Bạn có thể liệt kê các mô hình của dự án và lọc kết quả theo ý muốn:

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

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

Bạn có thể lọc theo các trường sau:

Trường Ví dụ
display_name display_name = example_model
display_name != example_model

Tất cả tên hiển thị có tiền tố experimental_:

display_name : experimental_*

Xin lưu ý rằng hệ thống chỉ hỗ trợ so khớp tiền tố.

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

Kết hợp các bộ lọc bằng các toán tử AND, ORNOT và dấu ngoặc đơn ((, )).

Cập nhật mô hình

Sau khi thêm mô hình vào dự án, bạn có thể cập nhật tên hiển thị của mô hình đó, và tệp mô hình 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);

Huỷ xuất bản hoặc xoá mô hình

Để huỷ xuất bản hoặc xoá một mô hình, hãy chuyển mã mô hình vào thư mục huỷ xuất bản hoặc xoá . Khi bạn huỷ xuất bản một mô hình, mô hình đó sẽ vẫn còn trong dự án của bạn nhưng sẽ không có sẵn để tải xuống ứng dụng của bạn. Khi bạn xoá một mô hình, thao tác đó sẽ hoàn toàn đã bị xoá khỏi dự án của bạn. (Việc huỷ xuất bản mô hình trong phiên bản chuẩn quy trình công việc, nhưng bạn có thể sử dụng quy trình này để huỷ xuất bản mô hình mới ngay lập tức vô tình xuất bản và không được sử dụng ở bất cứ đâu hoặc trong trường hợp sẽ tệ hơn nếu người dùng tải xuống tệp "không hợp lệ" hơn là lấy mô hình không tìm thấy lỗi.)

Nếu vẫn chưa tham chiếu đến đối tượng Mô hình, có thể bạn cần phải lấy mã mô hình bằng cách liệt kê các mô hình của dự án qua một bộ lọc. Ví dụ: để xoá tất cả người mẫu được gắn thẻ "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);