Deployment e gestione di modelli personalizzati

Puoi eseguire il deployment e gestire i modelli personalizzati e quelli addestrati con AutoML utilizzando la console Firebase o gli SDK Firebase Admin per Python e Node.js. Se eseguire il deployment di un modello e aggiornarlo occasionalmente. In genere è più semplice usa la console Firebase. L'SDK Admin può essere utile durante l'integrazione con creare pipeline, lavorando con blocchi note Colab o Jupyter e altri flussi di lavoro.

Esegui il deployment e gestisci i modelli nella console Firebase

Modelli TensorFlow Lite

Per eseguire il deployment di un modello TensorFlow Lite utilizzando la console Firebase:

  1. Apri la pagina Firebase ML Modello personalizzato nella Console Firebase.
  2. Fai clic su Aggiungi modello personalizzato (o Aggiungi un altro modello).
  3. Specifica un nome che verrà utilizzato per identificare il modello in Firebase progetto, quindi carica il file del modello TensorFlow Lite (che di solito termina con .tflite o .lite).

Dopo aver eseguito il deployment del modello, puoi trovarlo nella pagina Personalizzato. Da qui, puoi completare attività come l'aggiornamento del modello con un nuovo file, il download ed eliminare il modello dal tuo progetto.

Esegui il deployment e gestisci i modelli con l'SDK Firebase Admin

Questa sezione mostra come completare il deployment e la gestione comuni dei modelli con SDK Admin. Consulta il riferimento all'SDK per Python oppure Node.js per ulteriore assistenza.

Per esempi dell'SDK in uso, consulta la esempio della guida rapida di Python e Esempio di guida rapida di Node.js.

Prima di iniziare

  1. Se non hai ancora un progetto Firebase, creane uno nuovo nel Console Firebase. Poi apri il progetto e segui questi passaggi:

    1. Nella pagina Impostazioni, crea un account di servizio e scarica il file delle chiavi dell'account di servizio. Tieni questo file al sicuro, poiché concede l'accesso amministrativo al tuo progetto.

    2. Nella pagina Spazio di archiviazione, abilita Cloud Storage. Prendi nota il nome del bucket.

      Hai bisogno di un bucket Cloud Storage per archiviare temporaneamente i file del modello mentre li aggiungi al tuo progetto Firebase. Se utilizzi Blaze puoi creare e utilizzare un bucket diverso da quello predefinito che non ha uno scopo specifico.

    3. Nella pagina Firebase ML, fai clic su Inizia se non hai ancora attivato Firebase ML.

  2. Nella console API di Google, apri Firebase e abilitare l'API Firebase ML.

  3. Installa e inizializza l'SDK Admin.

    Quando inizializza l'SDK, specifica le credenziali dell'account di servizio il bucket Cloud Storage che vuoi utilizzare per archiviare i tuoi modelli:

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

Deployment modelli

File TensorFlow Lite

Per eseguire il deployment di un modello TensorFlow Lite da un file del modello, caricalo nel tuo progetto e poi pubblicalo:

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

Modelli TensorFlow e Keras

Con l'SDK Python puoi convertire un modello dal formato di modello salvato di TensorFlow in TensorFlow Lite e caricarlo nel bucket Cloud Storage in un unico passaggio. Quindi, esegui il deployment nello stesso modo in cui esegui il deployment di un 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)

Se hai un modello Keras, puoi anche convertirlo in TensorFlow Lite e caricarlo in un solo passaggio. Puoi utilizzare un modello Keras salvato in un 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.)
# ...

Oppure, puoi convertire e caricare un modello Keras direttamente dallo script di addestramento:

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

Modelli AutoML TensorFlow Lite

Se hai addestrato un modello Edge con l'API AutoML Cloud oppure con l'interfaccia utente della console Google Cloud, puoi eseguire il deployment del modello in Firebase utilizzando l'SDK Admin.

Dovrai specificare l'identificatore di risorsa del modello, ovvero una stringa è simile al seguente esempio:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER Il numero del progetto del bucket Cloud Storage che contiene la classe un modello di machine learning. Potrebbe trattarsi del tuo progetto Firebase o di un altro progetto Google Cloud. Puoi trovare questo valore nella pagina Impostazioni del Console Firebase o la dashboard della console Google Cloud.
STORAGE_LOCATION La località della risorsa del bucket Cloud Storage che contiene del modello. Questo valore è sempre us-central1.
MODEL_ID L'ID del modello, che hai ricevuto dall'API AutoML Cloud.

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

Elenca i modelli del tuo progetto

Puoi elencare i modelli del tuo progetto, facoltativamente filtrando i risultati:

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

Puoi filtrare in base ai seguenti campi:

Campo Esempi
display_name display_name = example_model
display_name != example_model

Tutti i nomi visualizzati con il prefisso experimental_:

display_name : experimental_*

Tieni presente che è supportata solo la corrispondenza del prefisso.

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

Combina i filtri con gli operatori e le parentesi AND, OR e NOT ((, )).

Aggiornamento modelli

Dopo aver aggiunto un modello al progetto, puoi aggiornarne il nome visualizzato, tag e tflite file del modello:

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

Annullare la pubblicazione o eliminare i modelli

Per annullare la pubblicazione o eliminare un modello, passa l'ID modello all'account di annullamento della pubblicazione o all'eliminazione di machine learning. Quando annulli la pubblicazione di un modello, questo rimane nel progetto, ma disponibili per il download delle app. Quando elimini un modello, questo viene completamente rimosso dal progetto. (La pubblicazione di un modello non è prevista negli standard ma puoi utilizzarlo per annullare immediatamente la pubblicazione di un nuovo modello è stata pubblicata per errore e non viene ancora utilizzata da nessuna parte o nei casi in cui è peggiore per gli utenti scaricare un errore anziché ottenere un modello non trovato errori).

Se non hai ancora un riferimento all'oggetto Model, probabilmente dovrai per ottenere l'ID modello, elencando i modelli del progetto con un filtro. Ad esempio, per eliminare tutti i modelli taggati come "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);