Wdrażanie modeli niestandardowych i zarządzanie nimi

Modele niestandardowe i modele wytrenowane z użyciem AutoML możesz wdrażać i nimi zarządzać za pomocą Firebasekonsoli lub pakietów Firebase Admin SDK w językach Python i Node.js. Jeśli chcesz tylko wdrożyć model i od czasu do czasu go aktualizować, najprościej jest użyć Firebasekonsoli. Pakiet Admin SDK może być przydatny podczas integracji z potokami kompilacji, pracy z notatnikami Colab lub Jupyter i innymi przepływami pracy.

Wdrażanie modeli i zarządzanie nimi w konsoli Firebase

Modele TensorFlow Lite

Aby wdrożyć model TensorFlow Lite za pomocą konsoli Firebase:

  1. Otwórz Firebase MLstronę modelu niestandardowego w konsoli Firebase.
  2. Kliknij Dodaj model niestandardowy (lub Dodaj kolejny model).
  3. Podaj nazwę, która będzie używana do identyfikowania modelu w projekcie Firebase, a potem prześlij plik modelu TensorFlow Lite (zwykle z rozszerzeniem .tflite lub .lite).

Po wdrożeniu model znajdziesz na stronie Niestandardowe. Możesz tam wykonywać takie zadania jak aktualizowanie modelu za pomocą nowego pliku, pobieranie modelu i usuwanie go z projektu.

Wdrażanie modeli i zarządzanie nimi za pomocą pakietu Firebase Admin SDK

W tej sekcji dowiesz się, jak za pomocą pakietu Admin SDK wykonywać typowe zadania związane z wdrażaniem modeli i zarządzaniem nimi. Dodatkowe informacje znajdziesz w dokumentacji pakietu SDK dla Pythona lub Node.js.

Przykłady użycia pakietu SDK znajdziesz w krótkim wprowadzeniu do Pythonakrótkim wprowadzeniu do Node.js.

Zanim zaczniesz

  1. Jeśli nie masz jeszcze projektu Firebase, utwórz nowy projekt w Firebasekonsoli. Następnie otwórz projekt i wykonaj te czynności:

    1. Na stronie Ustawienia utwórz konto usługi i pobierz plik klucza konta usługi. Chroń ten plik, ponieważ zapewnia on dostęp do projektu na poziomie administratora.

    2. Na stronie Miejsce na dane włącz Cloud Storage. Zanotuj nazwę zasobnika.

      Potrzebujesz Cloud Storagezasobnika do tymczasowego przechowywania plików modelu podczas dodawania ich do projektu Firebase. Jeśli korzystasz z planu Blaze, możesz utworzyć i używać w tym celu innego zasobnika niż domyślny.

    3. Na stronie Firebase ML kliknij Rozpocznij, jeśli nie masz jeszcze włączonej usługi Firebase ML.

  2. W konsoli interfejsów API Google otwórz projekt Firebase i włącz interfejs Firebase ML API.

  3. Zainstaluj i zainicjuj pakiet Admin SDK.

    Podczas inicjowania pakietu SDK podaj dane logowania konta usługi i Cloud Storage, którego chcesz używać do przechowywania modeli:

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

Wdrażanie modeli

Pliki TensorFlow Lite

Aby wdrożyć model TensorFlow Lite z pliku modelu, prześlij go do projektu, a następnie opublikuj:

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

Modele TensorFlow i Keras

Za pomocą pakietu Python SDK możesz przekonwertować model z formatu zapisanego modelu TensorFlow na TensorFlow Lite i przesłać go do zasobnika Cloud Storage w jednym kroku. Następnie wdróż go w taki sam sposób jak plik 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)

Jeśli masz model Keras, możesz go też przekonwertować na TensorFlow Lite i przesłać w jednym kroku. Możesz użyć modelu Keras zapisanego w pliku 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.)
# ...

Możesz też przekonwertować i przesłać model Keras bezpośrednio ze skryptu trenowania:

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

Modele AutoML TensorFlow Lite

Jeśli model Edge został wytrenowany za pomocą interfejsu AutoML Cloud API lub Google Cloud konsoli, możesz wdrożyć go w Firebase za pomocą pakietu Admin SDK.

Musisz podać identyfikator zasobu modelu, czyli ciąg znaków podobny do tego przykładu:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER Numer projektu zasobnika Cloud Storage zawierającego model. Może to być Twój projekt Firebase lub inny projekt Google Cloud. Tę wartość znajdziesz na stronie Ustawienia w Firebase konsoli lub na pulpicie konsoli Google Cloud.
STORAGE_LOCATION Lokalizacja zasobu zasobnika Cloud Storage, który zawiera model. Ta wartość zawsze wynosi us-central1.
MODEL_ID Identyfikator modelu uzyskany z interfejsu 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);

Wyświetlanie listy modeli w projekcie

Możesz wyświetlić listę modeli projektu, opcjonalnie filtrując wyniki:

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

Możesz filtrować według tych pól:

Pole Przykłady
display_name display_name = example_model
display_name != example_model

Wszystkie wyświetlane nazwy z prefiksem experimental_:

display_name : experimental_*

Pamiętaj, że obsługiwane jest tylko dopasowanie prefiksu.

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

Łącz filtry za pomocą operatorów AND, ORNOT oraz nawiasów ((, )).

Aktualizowanie modeli

Po dodaniu modelu do projektu możesz zaktualizować jego wyświetlaną nazwę, tagi i tflite plik modelu:

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

Cofanie publikacji i usuwanie modeli

Aby cofnąć publikację modelu lub go usunąć, przekaż jego identyfikator do metod unpublish lub delete. Gdy cofniesz publikację modelu, pozostanie on w projekcie, ale nie będzie dostępny do pobrania przez aplikacje. Gdy usuniesz model, zostanie on całkowicie usunięty z projektu. (Cofnięcie publikacji modelu nie jest oczekiwane w standardowym przepływie pracy, ale możesz go użyć, aby natychmiast cofnąć publikację nowego modelu, który został opublikowany przez przypadek i nie jest jeszcze nigdzie używany, lub w przypadkach, gdy pobranie „złego” modelu jest gorsze dla użytkowników niż otrzymywanie błędów „nie znaleziono modelu”).

Jeśli nadal nie masz odwołania do obiektu Model, prawdopodobnie musisz uzyskać identyfikator modelu, wyświetlając listę modeli projektu z filtrem. Aby na przykład usunąć wszystkie modele oznaczone tagiem „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);