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

คุณสามารถทำให้และจัดการโมเดลที่กำหนดเองและโมเดลที่ฝึกด้วย AutoML ได้โดยใช้ คอนโซล Firebase หรือ SDK ของ Python และ Node.js ของผู้ดูแลระบบ Firebase หากคุณ ต้องการทำให้โมเดลใช้งานได้และอัปเดตเป็นครั้งคราว วิธีการที่ง่ายที่สุดคือ ใช้คอนโซล 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 ให้เปิด 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.)
# ...

โมเดล TensorFlow Lite ของ AutoML

หากคุณฝึกโมเดล Edge ด้วย AutoML Cloud API หรือด้วย UI ของคอนโซล Google Cloud คุณสามารถทำให้โมเดลใช้งานได้กับ Firebase โดยใช้ Admin 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);

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

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

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