Firebase コンソール、または Firebase Admin Python SDK か Firebase Admin Node.js SDK を使用して、カスタムモデルと AutoML でトレーニングされたモデルをデプロイして管理できます。モデルをデプロイしてたまに更新するだけの場合は、通常、Firebase コンソールを使用するのが最も簡単です。Admin SDK は、ビルド パイプラインと統合したり、Colab ノートブックまたは Jupyter ノートブックや他のワークフローを操作したりする場合に便利です。
Firebase コンソールでモデルをデプロイして管理する
TensorFlow Lite モデル
Firebase コンソールを使用して TensorFlow Lite モデルをデプロイするには:
- Firebase コンソールで Firebase ML カスタムモデル ページを開きます。
 - [カスタムモデルを追加](または [別のモデルを追加])をクリックします。
 - Firebase プロジェクトでモデルを識別するための名前を指定し、TensorFlow Lite モデルファイル(拡張子は通常 
.tfliteまたは.lite)をアップロードします。 
モデルをデプロイすると、カスタムページに表示されます。そこから、新しいファイルでモデルを更新する、モデルをダウンロードする、プロジェクトからモデルを削除するなどのタスクを完了できます。
Firebase Admin SDK を使用してモデルをデプロイして管理する
このセクションでは、Admin SDK を使用して一般的なモデルのデプロイタスクと管理タスクを行う方法について説明します。詳細については、Python または Node.js の SDK リファレンスをご覧ください。
SDK の使用例については、Python クイックスタート サンプルと Node.js クイックスタート サンプルをご覧ください。
始める前に
Firebase プロジェクトをまだ作成していない場合は、Firebase コンソールで新しいプロジェクトを作成します。次に、プロジェクトを開いて次の操作を行います。
[設定] ページで、サービス アカウントを作成し、サービス アカウントキー ファイルをダウンロードします。このファイルはプロジェクトへの管理者アクセスを許可するため、安全に保管してください。
[ストレージ] ページで、Cloud Storage を有効にします。バケット名をメモしておいてください。
モデルファイルを Firebase プロジェクトに追加する際に、モデルファイルを一時的に保存する Cloud Storage バケットが必要です。Blaze プランをご利用の場合は、この目的のためにデフォルト以外のバケットを作成して使用できます。
Firebase ML を有効にしていない場合は、Firebase ML ページで [始める] をクリックします。
Google API Console で Firebase プロジェクトを開き、Firebase ML API を有効にします。
- 
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 を使用すると、1 ステップでモデルを 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 モデルを使用している場合も、1 ステップで、モデルを TensorFlow Lite に変換してアップロードできます。HDF5 ファイルに保存された Keras モデルを使用できます。
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 モデル
AutoML Cloud API または Google Cloud コンソール UI を使用してトレーニングした Edge モデルは、Admin SDK を使用して Firebase にデプロイできます。
この場合、モデルのリソース ID を指定する必要があります。リソース ID は、次の例に示したような文字列になります。
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 から取得した、モデルの ID。 | 
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_modeldisplay_name != example_model
 display_name : experimental_*
      接頭辞の一致のみがサポートされています。  | 
  
tags | 
    
      tags: face_detectortags: face_detector AND tags: experimental
     | 
  
state.published | 
    
      state.published = truestate.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);
モデルを非公開または削除する
モデルを非公開または削除するには、モデル ID を非公開メソッドまたは削除メソッドに渡します。モデルを非公開にすると、プロジェクトには残りますが、アプリでダウンロードすることはできません。モデルを削除すると、プロジェクトから完全に削除されます(モデルの非公開は標準のワークフローでは想定されていませんが、誤って公開してまだどこにも使用されていない新しいモデルをすぐに非公開にする場合や、モデルが見つからないというエラーが発生するよりも「悪い」モデルをユーザーがダウンロードしないようにすることが重要な場合に使用できます)。
モデル オブジェクトへの参照がまだない場合は、フィルタを使用してプロジェクトのモデルを一覧表示してモデル ID を取得する必要があります。たとえば、「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);