نشر النماذج المخصَّصة وإدارتها

يمكنك نشر النماذج المخصّصة وإدارتها باستخدام إما وحدة تحكُّم 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 و نموذج البدء السريع للغة Node.js.

قبل البدء

  1. إذا لم يكن لديك مشروع على Firebase، أنشئ مشروعًا جديدًا في الـ Firebase وحدة تحكُّم. بعد ذلك، افتح مشروعك ونفِّذ ما يلي:

    1. في صفحة "الإعدادات"، أنشئ حساب خدمة و نزِّل ملف مفتاح حساب الخدمة. احتفِظ بهذا الملف في مكان آمن، لأنّه يمنح إذن الوصول إلى المشرف في مشروعك.

    2. في صفحة "مساحة التخزين"، فعِّل Cloud Storage. دوِّن اسم مساحة التخزين.

      تحتاج إلى مساحة تخزين Cloud Storage لتخزين ملفات النماذج مؤقتًا أثناء إضافتها إلى مشروعك على Firebase. إذا كنت تستخدم خطة Blaze، يمكنك إنشاء مساحة تخزين واستخدامها غير مساحة التخزين التلقائية لهذا الغرض.

    3. في صفحة Firebase ML، انقر على البدء إذا لم يسبق لك تفعيل Firebase ML.

  2. في Google APIs console، افتح مشروعك على 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.)
# ...

إدراج نماذج مشروعك

يمكنك إدراج نماذج مشروعك، مع إمكانية فلترة النتائج:

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.
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":

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