Catch up on highlights from Firebase at Google I/O 2023. Learn more

Özel modelleri dağıtın ve yönetin

Firebase konsolunu veya Firebase Admin Python ve Node.js SDK'larını kullanarak özel modelleri ve AutoML tarafından eğitilmiş modelleri dağıtabilir ve yönetebilirsiniz. Yalnızca bir model dağıtmak ve onu ara sıra güncellemek istiyorsanız, genellikle Firebase konsolunu kullanmak en kolay yoldur. Admin SDK, yapı işlem hatlarıyla tümleştirme, Colab veya Jupyter not defterleri ve diğer iş akışlarıyla çalışırken yardımcı olabilir.

Modelleri Firebase konsolunda dağıtın ve yönetin

TensorFlow Lite modelleri

Firebase konsolunu kullanarak bir TensorFlow Lite modelini dağıtmak için:

  1. Firebase konsolunda Firebase ML Özel model sayfasını açın.
  2. Özel model ekle'ye (veya Başka bir model ekle'ye ) tıklayın.
  3. Firebase projenizde modelinizi tanımlamak için kullanılacak bir ad belirtin, ardından TensorFlow Lite model dosyasını yükleyin (genellikle .tflite veya .lite ile biter).

Modelinizi dağıttıktan sonra Özel sayfasında bulabilirsiniz. Buradan modeli yeni bir dosya ile güncelleme, modeli indirme ve modeli projenizden silme gibi görevleri tamamlayabilirsiniz.

Firebase Admin SDK ile modelleri dağıtın ve yönetin

Bu bölüm, Admin SDK ile ortak model dağıtımını ve yönetim görevlerini nasıl tamamlayabileceğinizi gösterir. Ek yardım için Python veya Node.js için SDK referansına bakın.

Kullanılan SDK örnekleri için Python hızlı başlangıç ​​örneğine ve Node.js hızlı başlangıç ​​örneğine bakın.

Sen başlamadan önce

  1. Halihazırda bir Firebase projeniz yoksa Firebase konsolunda yeni bir proje oluşturun. Ardından, projenizi açın ve aşağıdakileri yapın:

    1. Ayarlar sayfasında bir hizmet hesabı oluşturun ve hizmet hesabı anahtar dosyasını indirin. Projenize yönetici erişimi sağladığı için bu dosyayı güvende tutun.

    2. Depolama sayfasında, Bulut Depolamayı etkinleştirin. Kova adınızı not edin.

      Model dosyalarını Firebase projenize eklerken geçici olarak depolamak için bir Bulut Depolama grubuna ihtiyacınız vardır. Blaze planındaysanız bu amaçla default dışında bir bucket oluşturup kullanabilirsiniz.

    3. Firebase ML sayfasında, Firebase ML'yi henüz etkinleştirmediyseniz Başlayın'ı tıklayın.

  2. Google APIs konsolunda Firebase projenizi açın ve Firebase ML API'yi etkinleştirin.

  3. Admin SDK'yı kurun ve başlatın .

    SDK'yı başlattığınızda, hizmet hesabı kimlik bilgilerinizi ve modellerinizi depolamak için kullanmak istediğiniz Bulut Depolama grubunu belirtin:

    Piton

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

Modelleri dağıtın

TensorFlow Lite dosyaları

Bir model dosyasından bir TensorFlow Lite modelini dağıtmak için, onu projenize yükleyin ve ardından yayınlayın:

Piton

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

TensorFlow ve Keras modelleri

Python SDK ile, bir modeli TensorFlow kayıtlı model biçiminden TensorFlow Lite'a dönüştürebilir ve tek bir adımda Bulut Depolama grubunuza yükleyebilirsiniz. Ardından, bir TensorFlow Lite dosyasını dağıttığınız gibi dağıtın.

Piton

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

Bir Keras modeliniz varsa, onu da TensorFlow Lite'a dönüştürebilir ve tek adımda yükleyebilirsiniz. Bir HDF5 dosyasına kaydedilmiş bir Keras modelini kullanabilirsiniz:

Piton

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

Ya da doğrudan eğitim betiğinizden bir Keras modelini dönüştürebilir ve yükleyebilirsiniz:

Piton

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

AutoML TensorFlow Lite modelleri

AutoML Cloud API veya Google Cloud Console kullanıcı arayüzü ile bir Edge modeli eğittiyseniz, Admin SDK'yı kullanarak modeli Firebase'e dağıtabilirsiniz.

Aşağıdaki örneğe benzeyen bir dize olan modelin kaynak tanımlayıcısını belirtmeniz gerekecek:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER Modeli içeren Cloud Storage paketinin proje numarası. Bu, Firebase projeniz veya başka bir Google Cloud projeniz olabilir. Bu değeri Firebase konsolunun Ayarlar sayfasında veya Google Cloud Console kontrol panelinde bulabilirsiniz.
STORAGE_LOCATION Modeli içeren Cloud Storage paketinin kaynak konumu. Bu değer her zaman us-central1 şeklindedir.
MODEL_ID AutoML Cloud API'den aldığınız modelin kimliği.

Piton

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

Projenizin modellerini listeleyin

İsteğe bağlı olarak sonuçları filtreleyerek projenizin modellerini listeleyebilirsiniz:

Piton

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

Aşağıdaki alanlara göre filtreleme yapabilirsiniz:

Alan örnekler
display_name display_name = example_model
display_name != example_model

experimental_ ön ekine sahip tüm görünen adlar:

display_name : experimental_*

Yalnızca önek eşleştirmenin desteklendiğini unutmayın.

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

Filtreleri AND , OR ve NOT işleçleri ve parantezlerle ( ( , ) ) birleştirin.

Modelleri güncelle

Projenize bir model ekledikten sonra görünen adını, etiketlerini ve tflite model dosyasını güncelleyebilirsiniz:

Piton

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

Modelleri yayından kaldırın veya silin

Bir modeli yayından kaldırmak veya silmek için model kimliğini yayından kaldırma veya silme yöntemlerine iletin. Bir modeli yayından kaldırdığınızda, model projenizde kalır ancak uygulamalarınızın indirmesi için kullanılamaz. Bir modeli sildiğinizde, projenizden tamamen kaldırılır. (Standart bir iş akışında bir modelin yayından kaldırılması beklenmez, ancak yanlışlıkla yayınladığınız ve henüz hiçbir yerde kullanılmayan yeni bir modeli hemen yayından kaldırmak için veya kullanıcıların "kötü" bir model indirmesinin daha kötü olduğu durumlarda bunu kullanabilirsiniz. model bulunamadı hataları almaktan daha fazla model.)

Hala Model nesnesine bir referansınız yoksa, muhtemelen projenizin modellerini bir filtreyle listeleyerek model kimliğini almanız gerekecektir. Örneğin, "face_detector" etiketli tüm modelleri silmek için:

Piton

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