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

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

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

מודלים של TensorFlow Lite

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

  1. פותחים את Firebase ML הדף 'מודל בהתאמה אישית' במסוף Firebase.
  2. לוחצים על הוספת מודל בהתאמה אישית (או על הוספת מודל נוסף).
  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 bucket כדי לאחסן באופן זמני קובצי מודלים בזמן שאתם מוסיפים אותם לפרויקט Firebase. אם אתם משתמשים בתוכנית Blaze, אתם יכולים ליצור דלי ולהשתמש בו במקום בדלי ברירת המחדל למטרה הזו.

    3. בדף Firebase ML, לוחצים על Get started (התחלת העבודה) אם עדיין לא הפעלתם את 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. אפשר למצוא את הערך הזה בדף ההגדרות של מסוף 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);

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

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

אם עדיין אין לכם הפניה לאובייקט 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);