ปรับใช้และจัดการโมเดลที่กำหนดเอง

คุณสามารถปรับใช้และจัดการโมเดลที่กำหนดเองและโมเดลที่ได้รับการฝึก AutoML ได้โดยใช้คอนโซล Firebase หรือ Firebase Admin Python และ Node.js SDK หากคุณเพียงต้องการปรับใช้โมเดลและอัปเดตเป็นครั้งคราว การใช้คอนโซล Firebase เป็นวิธีที่ง่ายที่สุด Admin SDK จะมีประโยชน์เมื่อผสานรวมกับไปป์ไลน์บิวด์ การทำงานกับสมุดบันทึก Colab หรือ Jupyter และเวิร์กโฟลว์อื่นๆ

ปรับใช้และจัดการโมเดลในคอนโซล Firebase

รุ่น TensorFlow Lite

หากต้องการปรับใช้โมเดล TensorFlow Lite โดยใช้คอนโซล Firebase ให้ทำดังนี้

  1. เปิด หน้าโมเดล Firebase ML Custom ในคอนโซล 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 ให้เปิดโปรเจ็กต์ 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',
      })
    

    โหนด 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)

โหนด 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 หรือกับ UI คอนโซล 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)

โหนด 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))

โหนด 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)

โหนด 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":

หลาม

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

โหนด 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);