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

يمكنك نشر وإدارة النماذج المخصّصة والنماذج المُدرَّبة على تكنولوجيا تعلُّم الآلة من خلال أيٍّ مما يلي: وحدة تحكُّم Firebase أو حِزم تطوير البرامج (SDK) لمشرِف Firebase وNode.js. إذا كنت نشر نموذج وتحديثه من حين لآخر، فعادةً ما يكون من الأسهل تستخدم وحدة تحكم Firebase. يمكن أن تكون حزمة SDK للمشرف مفيدة عند الدمج مع وإنشاء مسارات التعلّم والعمل باستخدام أوراق ملاحظات Colab أو Jupyter، وغيرها من مهام سير العمل.

نشر النماذج وإدارتها في وحدة تحكُّم Firebase

طُرز TensorFlow Lite

لنشر نموذج TensorFlow Lite باستخدام وحدة تحكُّم Firebase، اتّبِع الخطوات التالية:

  1. افتح صفحة النموذج المخصّص لتعلُّم الآلة من Firebase في "وحدة تحكُّم Firebase".
  2. انقر على إضافة نموذج مخصّص (أو إضافة نموذج آخر).
  3. حدِّد اسمًا سيتم استخدامه لتحديد نموذجك في Firebase. ثم تحميل ملف نموذج TensorFlow Lite (الذي ينتهي عادةً بـ .tflite أو .lite).

بعد نشر النموذج، يمكنك العثور عليه في الصفحة المخصصة. من هناك، يمكنك إكمال مهام مثل تحديث النموذج بملف جديد أو تنزيل وحذف النموذج من مشروعك.

نشر النماذج وإدارتها باستخدام حزمة تطوير البرامج (SDK) لمشرف Firebase

يوضح هذا القسم كيفية إكمال نشر النماذج الشائعة وإدارتها. المهام باستخدام SDK للمشرف. الاطّلاع على مرجع حزمة تطوير البرامج (SDK) للغة Python أو Node.js للحصول على مساعدة إضافية.

للحصول على أمثلة عن حزمة SDK قيد الاستخدام، يمكنك مراجعة نموذج Python Quickstart نموذج البدء السريع في Node.js

قبل البدء

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

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

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

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

    3. في صفحة تعلُّم الآلة في Firebase، انقر على البدء إذا لم تكن قد فعلت ذلك بعد. وتفعيل تكنولوجيا تعلُّم الآلة في Firebase.

  2. في وحدة تحكُّم Google APIs، افتح Firebase. مشروعك وتفعيل واجهة برمجة تطبيقات Firebase ML.

  3. ثبِّت حزمة 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 Console، يمكنك نشر النموذج في Firebase باستخدام SDK للمشرف.

سيلزمك تحديد معرِّف مورد النموذج، وهو عبارة عن سلسلة يبدو مثل المثال التالي:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER رقم مشروع حزمة Cloud Storage التي تحتوي على model. يمكن أن يكون هذا مشروعك على 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);

إلغاء نشر النماذج أو حذفها

لإلغاء نشر نموذج أو حذفه، عليك ضبط رقم تعريف النموذج على حقل إلغاء النشر أو الحذف. الطرق. عند إلغاء نشر أحد النماذج، سيبقى ضمن المشروع، ولكنه لن يظل كذلك. المتاحة لتطبيقاتك للتنزيل. وعندما تحذف نموذجًا، يتم حذف من مشروعك. (ليس من المتوقع إلغاء نشر نموذج وفقًا لمعيار ولكن يمكنك استخدامه لإلغاء نشر نموذج جديد أن يتم نشرها عن طريق الخطأ ولا يتم استخدامها في أي مكان حتى الآن أو في الحالات التي يكون أسوأ من أن يقوم المستخدمون بتنزيل إصدار "سيئ" عدم العثور على النموذج المطلوب الأخطاء).

إذا لم يكن لديك مرجع إلى كائن النموذج، من المحتمل أن تحتاج إلى للحصول على معرّف النموذج من خلال إدراج نماذج مشروعك باستخدام فلتر. على سبيل المثال، بهدف حذف جميع النماذج التي تمّ وضع عليها علامة 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);