FirebaseコンソールまたはFirebaseAdminPythonおよびNode.jsSDKのいずれかを使用して、カスタムモデルとAutoMLトレーニング済みモデルをデプロイおよび管理できます。モデルをデプロイして時々更新したい場合は、通常、Firebaseコンソールを使用するのが最も簡単です。 Admin SDKは、ビルドパイプラインとの統合、ColabまたはJupyterノートブックの操作、およびその他のワークフローで役立ちます。
Firebaseコンソールでモデルをデプロイして管理する
TensorFlowLiteモデル
Firebaseコンソールを使用してTensorFlowLiteモデルをデプロイするには:
- FirebaseコンソールでFirebaseMLカスタムモデルページを開きます。
- [カスタムモデルの追加](または[別のモデルの追加])をクリックします。
- Firebaseプロジェクトでモデルを識別するために使用する名前を指定してから、TensorFlow Liteモデルファイル(通常は
.tflite
または.lite
で終わる)をアップロードします。
モデルをデプロイした後、カスタムページでモデルを見つけることができます。そこから、新しいファイルでモデルを更新する、モデルをダウンロードする、プロジェクトからモデルを削除するなどのタスクを完了することができます。
Firebase AdminSDKを使用してモデルをデプロイおよび管理する
このセクションでは、AdminSDKを使用して一般的なモデルの展開および管理タスクを完了する方法を示します。追加のヘルプについては、 PythonまたはNode.jsのSDKリファレンスを参照してください。
使用中のSDKの例については、 PythonクイックスタートサンプルとNode.jsクイックスタートサンプルを参照してください。
あなたが始める前に
Firebaseプロジェクトをまだお持ちでない場合は、 Firebaseコンソールで新しいプロジェクトを作成してください。次に、プロジェクトを開き、次の手順を実行します。
[設定]ページで、サービスアカウントを作成し、サービスアカウントキーファイルをダウンロードします。このファイルは、管理者にプロジェクトへのアクセスを許可するため、安全に保管してください。
[ストレージ]ページで、クラウドストレージを有効にします。バケット名をメモします。
モデルファイルをFirebaseプロジェクトに追加するときに一時的に保存するには、CloudStorageバケットが必要です。 Blazeプランを使用している場合は、この目的のためにデフォルト以外のバケットを作成して使用できます。
Firebase MLをまだ有効にしていない場合は、[FirebaseML]ページで[開始]をクリックします。
Google APIコンソールで、Firebaseプロジェクトを開き、Firebase MLAPIを有効にします。
SDKを初期化するときに、モデルの保存に使用するサービスアカウントのクレデンシャルとCloudStorageバケットを指定します。
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();
モデルを展開する
TensorFlowLiteファイル
モデルファイルからTensorFlowLiteモデルをデプロイするには、それをプロジェクトにアップロードしてから公開します。
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に変換し、それをクラウドストレージバケットにワンステップでアップロードできます。次に、TensorFlowLiteファイルをデプロイするのと同じ方法でデプロイします。
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に変換して、1つのステップでアップロードすることもできます。 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 TensorFlowLiteモデル
AutoML CloudAPIまたはGoogleCloud Console UIを使用してEdgeモデルをトレーニングした場合は、AdminSDKを使用してモデルをFirebaseにデプロイできます。
モデルのリソース識別子を指定する必要があります。これは、次の例のような文字列です。
projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
PROJECT_NUMBER | モデルを含むCloudStorageバケットのプロジェクト番号。これは、Firebaseプロジェクトまたは別のGoogleCloudプロジェクトである可能性があります。この値は、Firebaseコンソールの[設定]ページまたはGoogle CloudConsoleダッシュボードで確認できます。 |
STORAGE_LOCATION | モデルを含むCloudStorageバケットのリソースの場所。この値は常にus-central1 です。 |
MODEL_ID | AutoML CloudAPIから取得したモデルの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_model display_name != example_model 接頭辞が 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);
モデルの非公開または削除
モデルを非公開または削除するには、モデルIDを非公開または削除メソッドに渡します。モデルを非公開にすると、モデルはプロジェクトに残りますが、アプリでダウンロードすることはできません。モデルを削除すると、プロジェクトから完全に削除されます。 (標準のワークフローではモデルの非公開は期待されていませんが、誤って公開してまだどこにも使用されていない新しいモデルをすぐに非公開にするために使用できます。または、ユーザーが「不良」をダウンロードするのが悪い場合に使用できます。モデルが見つからないエラーを取得するよりもモデル。)
Modelオブジェクトへの参照がまだない場合は、プロジェクトのモデルをフィルターで一覧表示して、モデル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);