פריסת מודלים בהתאמה אישית וניהול שלהם

אפשר לפרוס ולנהל מודלים מותאמים אישית ומודלים שאומנו על ידי AutoML באמצעות מסוף Firebase או ערכות ה-SDK של Firebase Admin עבור Python ו-Node.js. אם אתם רוצים רק לפרוס מודל ולעדכן אותו מדי פעם, בדרך כלל הכי פשוט להשתמש במסוף Firebase. ה-SDK של Admin יכול להיות שימושי כשמשלבים אותו עם צינורות עיבוד נתונים ל-build, עובדים עם קובצי notebook של Colab או Jupyter ותהליכי עבודה אחרים.

פריסת מודלים וניהול שלהם במסוף Firebase

דגמים של TensorFlow Lite

כדי לפרוס מודל TensorFlow Lite באמצעות המסוף Firebase:

  1. פותחים את דף המודל המותאם אישית Firebase ML בקטע מסוף Firebase.
  2. לוחצים על Add custom model (הוספת מודל מותאם אישית) או על Add another model (הוספת מודל נוסף).
  3. מציינים שם שמשמש לזיהוי המודל בפרויקט Firebase, ואז מעלים את קובץ המודל של TensorFlow Lite (בדרך כלל מסתיים ב-.tflite או ב-.lite).

לאחר פריסת המודל, תוכלו למצוא אותו בדף 'מותאם אישית'. מכאן אפשר יכולים להשלים משימות כמו עדכון המודל בקובץ חדש, הורדת ולמחוק את המודל מהפרויקט.

פריסה וניהול של מודלים באמצעות Firebase Admin SDK

בקטע הזה אפשר לראות איך מבצעים פריסה וניהול נפוצים של מודלים משימות עם ה-Admin SDK. לעיון בחומר העזר בנושא SDK של Python או Node.js כדי לקבל עזרה נוספת.

לדוגמאות לשימוש ב-SDK, ראו את הדוגמה למתחילים ב-Python ואת הדוגמה למתחילים ב-Node.js.

לפני שמתחילים

  1. אם עדיין אין לכם פרויקט Firebase, תוכלו ליצור פרויקט חדש במסוף Firebase. לאחר מכן פותחים את הפרויקט ו לבצע את הפעולות הבאות:

    1. בדף Settings (הגדרות), יוצרים חשבון שירות. מורידים את קובץ המפתח של חשבון השירות. הגנו על הקובץ הזה כי מעניקה גישת אדמין לפרויקט.

    2. בדף 'אחסון', מפעילים את האפשרות Cloud Storage. חשוב לשים לב שם הקטגוריה.

      צריך קטגוריה מסוג Cloud Storage כדי לאחסן באופן זמני את קובצי המודל בזמן ההוספה שלהם לפרויקט Firebase. אם אתם ב-Baze אפשר ליצור קטגוריה ולהשתמש בה במקום ברירת המחדל למטרה.

    3. בדף Firebase ML לוחצים על מתחילים אם עדיין לא עשיתם זאת. בוצעה הפעלה של Firebase ML.

  2. במסוף Google APIs, פותחים את Firebase לפרויקט ולהפעיל את Firebase ML API.

  3. מתקינים ומפעילים את Admin SDK.

    כשמאתחלים את ה-SDK, מציינים את פרטי הכניסה של חשבון השירות ו הקטגוריה Cloud Storage שבה רוצים להשתמש כדי לאחסן את המודלים:

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

פריסת מודלים

קבצים של TensorFlow Lite

כדי לפרוס מודל TensorFlow Lite מקובץ מודל, צריך להעלות אותו לפרויקט ולאחר מכן מפרסמים אותו:

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

מודלים של TensorFlow ו-Keras

באמצעות Python SDK אפשר להמיר מודל מפורמט המודל שנשמר ב-TensorFlow ל-TensorFlow Lite ומעלים אותו לקטגוריה של Cloud Storage בכל פעימה. אחר כך פורסים אותו באותה דרך שבה פורסים קובץ 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)

אם יש לכם מודל Keras, אתם יכולים גם להמיר אותו ל-TensorFlow Lite ולהעלות אותו בשלב אחד. ניתן להשתמש במודל Keras שנשמר בקובץ 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.)
# ...

לחלופין, אפשר להמיר ולהעלות מודל Keras ישירות מתסריט האימון:

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

דגמי AutoML TensorFlow Lite

אם אימנתם את מודל Edge באמצעות AutoML Cloud API או דרך ממשק המשתמש של מסוף Google Cloud, אפשר לפרוס את המודל ב-Firebase באמצעות על ה-Admin SDK.

צריך לציין את מזהה המשאב של המודל, שהוא מחרוזת נראה כמו בדוגמה הבאה:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER מספר הפרויקט של הקטגוריה Cloud Storage שמכילה את המודל. זה יכול להיות פרויקט Firebase או Google Cloud אחר פרויקט. אפשר למצוא את הערך הזה בדף Settings (הגדרות) מסוף Firebase או מרכז הבקרה של מסוף Google Cloud.
STORAGE_LOCATION מיקום המשאב של הקטגוריה Cloud Storage שמכילה את המודל. הערך הזה הוא תמיד us-central1.
MODEL_ID מזהה המודל, שקיבלתם מ-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);

הצגת רשימה של המודלים של הפרויקט

אתם יכולים להציג את רשימת המודלים של הפרויקט, ולסנן את התוצאות:

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

אפשר לסנן לפי השדות הבאים:

שדה דוגמאות
display_name display_name = example_model
display_name != example_model

כל השמות המוצגים עם הקידומת experimental_:

display_name : experimental_*

לתשומת ליבכם, יש תמיכה רק בהתאמה לקידומת.

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

שילוב מסננים עם האופרטורים והסוגריים AND, OR ו-NOT ((, )).

עדכון מודלים

אחרי שמוסיפים מודל לפרויקט, אפשר לעדכן את השם המוצג שלו, תגים וקובץ מודל אחד (tflite):

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

ביטול הפרסום או מחיקה של מודלים

כדי לבטל פרסום או למחוק מודל, יש להעביר את מזהה המודל לביטול הפרסום או למחיקה שיטות. כשמבטלים פרסום של מודל, הוא נשאר בפרויקט אבל לא שזמינות להורדה. כשמוחקים מודל, הוא הוסר מהפרויקט. (אין צורך לבטל פרסום של מודל אבל אפשר להשתמש בו כדי לבטל מיד את הפרסום של מודל חדש. פורסמו בטעות ועדיין לא נמצאים בשימוש בשום מקום, או במקרים שבהם גרוע יותר למשתמשים להוריד מאשר לקבל מודל ).

אם עדיין אין לכם הפניה לאובייקט Model, סביר להניח שתצטרכו לקבל את מזהה המודל על ידי הצגת המודלים של הפרויקט באמצעות מסנן. לדוגמה, כדי מחיקת כל המודלים שתויגו עם "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);