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

คุณปรับใช้และจัดการโมเดลที่กำหนดเองและโมเดลที่ฝึกโดย 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 และ ตัวอย่างการเริ่มต้นอย่างรวดเร็วของ Node.js

ก่อนที่คุณจะเริ่มต้น

  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',
      })
    

    โหนด 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 หรือ Google Cloud Console UI คุณจะปรับใช้โมเดลกับ Firebase ได้โดยใช้ Admin SDK

คุณจะต้องระบุตัวระบุทรัพยากรของโมเดล ซึ่งเป็นสตริงที่มีลักษณะดังตัวอย่างต่อไปนี้:

projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER หมายเลขโปรเจ็กต์ของที่เก็บข้อมูล Cloud Storage ที่มีโมเดล นี่อาจเป็นโครงการ Firebase ของคุณหรือโครงการ Google Cloud อื่น คุณสามารถค้นหาค่านี้ได้ในหน้าการตั้งค่าของคอนโซล Firebase หรือแดชบอร์ด Google Cloud Console
STORAGE_LOCATION ตำแหน่งทรัพยากรของที่เก็บข้อมูล Cloud Storage ที่มีโมเดล ค่านี้จะเป็น us-central1 เสมอ
MODEL_ID 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);

ยกเลิกการเผยแพร่หรือลบโมเดล

หากต้องการยกเลิกการเผยแพร่หรือลบโมเดล ให้ส่งรหัสโมเดลไปยังวิธีการยกเลิกการเผยแพร่หรือลบ เมื่อคุณยกเลิกการเผยแพร่โมเดล โมเดลจะยังคงอยู่ในโปรเจ็กต์ของคุณ แต่แอปของคุณจะไม่สามารถดาวน์โหลดได้ เมื่อคุณลบโมเดล โมเดลนั้นจะถูกลบออกจากโปรเจ็กต์ของคุณโดยสมบูรณ์ (ไม่คาดว่าจะยกเลิกการเผยแพร่โมเดลในเวิร์กโฟลว์มาตรฐาน แต่คุณสามารถใช้เพื่อยกเลิกการเผยแพร่โมเดลใหม่ที่คุณเผยแพร่โดยไม่ตั้งใจและยังไม่ได้ใช้งานในที่ใดๆ ได้ทันที หรือในกรณีที่ผู้ใช้ดาวน์โหลด "ไม่ดี" รุ่นกว่าจะได้รับข้อผิดพลาดที่ไม่พบรุ่น)

หากคุณยังไม่มีการอ้างอิงถึงออบเจกต์โมเดล คุณอาจต้องได้รับ ID โมเดลโดยแสดงรายการโมเดลของโครงการด้วยตัวกรอง ตัวอย่างเช่น หากต้องการลบโมเดลทั้งหมดที่มีแท็ก "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);