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ý các mô hình tuỳ chỉnh bằng bảng điều khiển Firebase hoặc SDK Firebase Admin Python và Node.js. Nếu chỉ muốn triển khai một mô hình và thỉnh thoảng cập nhật mô hình đó, thì cách đơn giản nhất thường là 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 quy trình xây dựng, làm việc với sổ tay Colab hoặc Jupyter và các quy trình công việc khác.

Triển khai và quản lý mô hình trong bảng điều khiển 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 Firebase ML trong bảng điều khiển 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 một tên sẽ được dùng để xác định mô hình trong dự án Firebase, 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 tất các tác vụ như cập nhật mô hình bằng một tệp mới, tải mô hình xuống và xoá mô hình khỏi dự án.

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

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

Để xem các ví dụ về cách sử dụng SDK, hãy xem mẫu bắt đầu nhanh cho Pythonmẫu bắt đầu nhanh cho Node.js.

Trước khi bắt đầu

  1. Nếu 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 Firebase. Sau đó, hãy mở dự án và làm như sau:

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

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

    3. Trên trang Firebase ML, 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 Google API, hãy mở dự án Firebase và bật API Firebase ML.

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

    Khi khởi chạy SDK, hãy chỉ định thông tin xác thực của tài khoản dịch vụ và nhóm Cloud Storage mà bạn muốn sử dụng để lưu trữ các mô hì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ừ một tệp mô hình, hãy tải tệp đó lên dự á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 của TensorFlow sang TensorFlow Lite và tải mô hình đó lên nhóm Cloud Storage chỉ trong một bước. Sau đó, hãy triển khai mô hình đó theo cách tương tự 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 đó sang TensorFlow Lite và tải mô hình đó lên chỉ trong một bước. Bạn có thể sử dụng mô hình Keras đã 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.)
# ...

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, đồng thời lọc kết quả (không bắt buộc):

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 chúng tôi chỉ hỗ trợ tính năng 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 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ị, thẻ 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.
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 truyền mã mô hình đến các phương thứ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 đó vẫn còn trong dự án nhưng ứng dụng của bạn không thể tải xuống. Khi bạn xoá một mô hình, mô hình đó sẽ bị xoá hoàn toàn khỏi dự án. (Việc huỷ xuất bản một mô hình không được mong đợi trong quy trình làm việc tiêu chuẩn, nhưng bạn có thể sử dụng tính năng này để huỷ xuất bản ngay một mô hình mới mà bạn vô tình xuất bản và chưa được sử dụng ở bất kỳ đâu, hoặc trong trường hợp người dùng tải xuống một mô hình "xấu" sẽ tệ hơn là gặp lỗi không tìm thấy mô hình.)

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