Wdrażanie modeli niestandardowych i zarządzanie nimi

Możesz wdrażać niestandardowe modele i modele wytrenowane przez AutoML oraz nimi zarządzać za pomocą: konsoli Firebase lub pakietów SDK Firebase Admin Python i Node.js. Jeśli po prostu chcesz wdrożyć model i od czasu do czasu go aktualizować. Zwykle za pomocą konsoli Firebase. Pakiet Admin SDK może być pomocny przy integracji z usługami tworzenia potoków oraz podczas pracy z notatnikami Colab lub Jupyter oraz 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 stronę niestandardowego modelu ML Firebase w konsoli Firebase.
  2. Kliknij Dodaj model niestandardowy (lub Dodaj kolejny model).
  3. Podaj nazwę, która będzie używana do identyfikowania Twojego modelu w Firebase projektu, a następnie prześlij plik modelu TensorFlow Lite (zwykle kończący się .tflite lub .lite).

Po wdrożeniu modelu znajdziesz go na stronie Niestandardowe. Następnie możesz może wykonać takie zadania jak aktualizacja modelu o nowy plik, pobranie model i usunięcie go z projektu.

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

W tej sekcji pokazujemy, jak wykonać typowe wdrażanie modelu i zarządzanie nim za pomocą pakietu Admin SDK. zobacz dokumentację pakietu SDK dla Pythona. lub Node.js.

Przykłady użycia pakietu SDK znajdziesz tutaj: Przykład krótkiego wprowadzenia w Pythonie i Przykład krótkiego wprowadzenia do Node.js.

Zanim zaczniesz

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

    1. Na stronie Ustawienia utwórz konto usługi. pobierz plik klucza konta usługi. Zadbaj o bezpieczeństwo tego pliku, przyznaje dostęp administracyjny do projektu.

    2. Na stronie Przechowywanie danych włącz Cloud Storage. Zanotuj swoje nazwa zasobnika.

      Do tymczasowego przechowywania plików modelu potrzebny jest zasobnik Cloud Storage podczas dodawania ich do projektu Firebase. Jeśli używasz urządzenia Blaze możesz utworzyć zasobnik inny niż domyślny i go używać cel.

    3. Na stronie Firebase ML kliknij Get Started (Rozpocznij), chyba że masz to już za sobą. włączono Firebase ML.

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

  3. Zainstaluj i zainicjuj pakiet Admin SDK.

    Podczas zainicjowania pakietu SDK podaj dane logowania do konta usługi oraz zasobnik Cloud Storage, w którym chcesz przechowywać modele:

    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 i opublikuj go:

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 SDK Pythona możesz przekonwertować model z formatu zapisanego modelu TensorFlow w TensorFlow Lite i przesyłać je do zasobnika Cloud Storage krok po kroku. Następnie wdróż ją w taki sam sposób, w jaki wdrażasz 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 przekonwertować na TensorFlow Lite i przesłać wystarczy, że wykonasz jeden krok. 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 treningowego:

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 za pomocą interfejsu konsoli Google Cloud możesz wdrożyć model w Firebase za pomocą: pakietu Admin SDK.

Musisz podać identyfikator zasobu modelu, czyli ciąg znaków, który wygląda w tym przykładzie:

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 inna usługa Google Cloud w projektach AI. Tę wartość znajdziesz na stronie Ustawienia w konsoli Firebase lub panelu konsoli Google Cloud.
STORAGE_LOCATION Lokalizacja zasobu zasobnika Cloud Storage, który zawiera w modelu. Ta wartość zawsze wynosi us-central1.
MODEL_ID Identyfikator modelu pobrany 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 projektu

Możesz wyświetlić listę modeli projektu i opcjonalnie filtrować 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);

Dane 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 prefiksów.

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

Stosuj filtry za pomocą operatorów AND, OR i NOT oraz nawiasów ((, )).

Aktualizowanie modeli

Po dodaniu modelu do projektu możesz zmienić jego wyświetlaną nazwę, 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 lub usuwanie modeli

Aby cofnąć publikację lub usunąć model, przekaż jego identyfikator do funkcji cofania publikacji lub usuwania modelu . Gdy wycofasz publikację modelu, pozostanie on w projekcie, ale nie i aplikacjami do pobrania. Gdy usuniesz model, jest on całkowicie usunięte z projektu. (Wycofywanie modelu nie jest oczekiwane w przypadku przepływu pracy, ale możesz go użyć do natychmiastowego cofnięcia publikacji nowego modelu opublikowana przypadkowo i nie jest jeszcze nigdzie używana jest gorsze, gdy użytkownicy pobiorą „zły” model, a następnie uzyskać nieznaleziony model ).

Jeśli nadal nie masz odniesienia do obiektu Model, prawdopodobnie pobierz identyfikator modelu, wyświetlając listę modeli projektu z filtrem. Aby na przykład: usuń wszystkie modele z 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);