Men-deploy dan mengelola model kustom

Anda dapat men-deploy serta mengelola model kustom dan model yang dilatih AutoML menggunakan Firebase console atau Firebase Admin Python dan Node.js SDK. Jika Anda hanya ingin men-deploy model dan sesekali mengupdatenya, cara termudah biasanya menggunakan Firebase console. Admin SDK dapat membantu saat mengintegrasikan pipeline build, bekerja dengan notebook Colab atau Jupyter, dan alur kerja lainnya.

Men-deploy dan mengelola model di Firebase console

Model TensorFlow Lite

Untuk men-deploy model TensorFlow Lite menggunakan Firebase console:

  1. Buka halaman Firebase ML Custom model di Firebase console.
  2. Klik Add custom model (atau Add another model).
  3. Tentukan nama yang akan digunakan untuk mengidentifikasi model Anda di project Firebase, lalu upload file model TensorFlow Lite (biasanya diakhiri dengan .tflite atau .lite).

Setelah men-deploy model, Anda dapat menemukannya di halaman Kustom. Setelah itu, Anda dapat menyelesaikan tugas seperti mengupdate model dengan file baru, mendownload model, dan menghapus model dari project Anda.

Men-deploy dan mengelola model dengan Firebase Admin SDK

Bagian ini menunjukkan cara menyelesaikan tugas pengelolaan dan deployment model umum dengan Admin SDK. Lihat referensi SDK untuk Python atau Node.js untuk mendapatkan bantuan tambahan.

Untuk mengetahui contoh penggunaan SDK, lihat contoh panduan memulai Python dan contoh panduan memulai Node.js.

Sebelum memulai

  1. Jika Anda belum memiliki project Firebase, buat project baru di Firebase console. Kemudian, buka project Anda dan lakukan hal berikut:

    1. Di halaman Setelan, buat akun layanan dan download file kunci akun layanan. Pastikan agar file ini tetap aman, karena file tersebut memberi administrator akses ke project Anda.

    2. Pada halaman Storage, aktifkan Cloud Storage. Catat nama bucket Anda.

      Anda memerlukan bucket Cloud Storage untuk menyimpan file model secara sementara sekaligus menambahkannya ke project Firebase Anda. Jika Anda menggunakan paket Blaze, Anda dapat membuat dan menggunakan bucket selain default untuk tujuan ini.

    3. Di halaman Firebase ML, klik Get started jika Anda belum mengaktifkan Firebase ML.

  2. Di konsol API Google, buka project Firebase Anda dan aktifkan Firebase ML API.

  3. Instal dan inisialisasi Admin SDK.

    Saat Anda melakukan inisialisasi SDK, tentukan kredensial akun layanan dan bucket Cloud Storage yang ingin digunakan untuk menyimpan model Anda:

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

Men-deploy model

File TensorFlow Lite

Untuk men-deploy model TensorFlow Lite dari file model, upload file model ke project Anda, lalu publikasikan:

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

Model TensorFlow dan Keras

Dengan Python SDK, Anda dapat mengonversi model dari format model tersimpan TensorFlow ke TensorFlow Lite dan menguploadnya ke bucket Cloud Storage Anda dalam satu langkah. Kemudian, deploy model dengan cara yang sama seperti Anda men-deploy file 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)

Jika memiliki model Keras, Anda juga dapat mengonversinya menjadi TensorFlow Lite dan menguploadnya dalam satu langkah. Anda dapat menggunakan model Keras yang disimpan ke file 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.)
# ...

Atau, Anda dapat mengonversi dan mengupload model Keras langsung dari skrip pelatihan:

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

Model TensorFlow Lite AutoML

Jika Anda melatih model Edge dengan AutoML Cloud API atau dengan UI Google Cloud Console, Anda dapat men-deploy model tersebut ke Firebase menggunakan Admin SDK.

Anda harus menentukan ID resource model, yang merupakan string yang terlihat seperti contoh berikut:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER Nomor project bucket Cloud Storage yang berisi model. Ini dapat berupa project Firebase Anda atau project Google Cloud lainnya. Anda dapat menemukan nilai ini di halaman Setelan Firebase console atau dasbor Google Cloud Console.
STORAGE_LOCATION Lokasi resource bucket Cloud Storage yang berisi model. Nilai ini selalu us-central1.
MODEL_ID ID model, yang Anda dapatkan dari 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);

Mencantumkan model project Anda

Anda dapat mencantumkan model project Anda, dan secara opsional memfilter hasilnya:

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

Anda dapat memfilternya berdasarkan kolom berikut:

Kolom Contoh
display_name display_name = example_model
display_name != example_model

Semua nama tampilan dengan awalan experimental_:

display_name : experimental_*

Perlu diperhatikan bahwa hanya pencocokan awalan yang didukung.

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

Gabungkan filter dengan operator AND, OR, dan NOT serta tanda kurung ((, )).

Mengupdate model

Setelah menambahkan model ke project, Anda dapat mengupdate nama tampilan, tag, dan file model tflite-nya:

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

Membatalkan publikasi atau menghapus model

Untuk membatalkan publikasi atau menghapus model, teruskan ID model ke metode batalkan publikasi atau hapus. Saat Anda membatalkan publikasi model, model tersebut tetap ada di project Anda, tetapi tidak tersedia untuk didownload oleh aplikasi Anda. Saat Anda menghapus model, model tersebut akan dihapus sepenuhnya dari project Anda. (Membatalkan publikasi model bukan merupakan bagian umum dari alur kerja standar, tetapi Anda dapat menggunakannya untuk segera membatalkan publikasi model baru yang dipublikasi tanpa sengaja dan belum digunakan di mana pun, atau jika pengguna lebih baik mendapatkan error model tidak ditemukan daripada mendownload model yang "buruk".)

Jika tidak memiliki referensi ke objek Model, Anda mungkin perlu mendapatkan ID model dengan mencantumkan model project Anda dengan filter. Misalnya, untuk menghapus semua model yang diberi tag "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);