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

אתה יכול לפרוס ולנהל מודלים מותאמים אישית ומודלים מאומנים ב-AutoML באמצעות קונסולת Firebase או Firebase Admin Python ו-Node.js SDK. אם אתה רק רוצה לפרוס דגם ולעדכן אותו מדי פעם, בדרך כלל הכי פשוט להשתמש במסוף Firebase. ה-Admin SDK יכול להיות מועיל בעת שילוב עם צינורות בנייה, עבודה עם מחברות Colab או 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 Quickstart ו- Node.js Quickstart .

לפני שאתה מתחיל

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

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

    2. בדף Storage, הפעל את Cloud Storage. שים לב לשם הדלי שלך.

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

    3. בדף Firebase ML, לחץ על התחל אם עדיין לא הפעלת את Firebase ML.

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

  3. התקן ואתחל את ה-Admin SDK .

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

    פִּיתוֹן

    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 מקובץ מודל, העלה אותו לפרויקט שלך ולאחר מכן פרסם אותו:

פִּיתוֹן

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

פִּיתוֹן

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

פִּיתוֹן

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 ישירות מתסריט האימון שלך:

פִּיתוֹן

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.

פִּיתוֹן

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

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

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

פִּיתוֹן

# 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 שלו:

פִּיתוֹן

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

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

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

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

פִּיתוֹן

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