Firebase Console 또는 Firebase Admin Python 및 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 콘솔 에서 Firebase 프로젝트를 열고 Firebase ML API를 활성화합니다.
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', })
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 모델을 배포하려면 프로젝트에 업로드한 다음 게시합니다.
파이썬
# 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 파일을 배포하는 것과 동일한 방식으로 배포합니다.
파이썬
# 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로 변환하고 한 번에 업로드할 수도 있습니다. HDF5 파일에 저장된 Keras 모델을 사용할 수 있습니다.
파이썬
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 모델
AutoML Cloud API 또는 Google Cloud Console UI를 사용하여 Edge 모델을 교육한 경우 Admin SDK를 사용하여 모델을 Firebase에 배포할 수 있습니다.
다음 예제와 같은 문자열인 모델의 리소스 식별자를 지정해야 합니다.
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 | AutoML Cloud API에서 가져온 모델의 ID입니다. |
파이썬
# 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);
프로젝트 모델 나열
프로젝트의 모델을 나열하고 선택적으로 결과를 필터링할 수 있습니다.
파이썬
# 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
모델 파일을 업데이트할 수 있습니다.
파이썬
# 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" 태그가 지정된 모든 모델을 삭제하려면:
파이썬
# 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);