Firebase Console 또는 Firebase Admin Python, Node.js SDK를 사용하여 커스텀 모델 및 AutoML 학습 모델을 배포하고 관리할 수 있습니다. 모델을 배포하고 경우에 따라 업데이트하려는 경우 일반적으로 Firebase Console을 사용하는 것이 가장 간단합니다. Admin SDK는 빌드 파이프라인과 통합하고 Colab 또는 Jupyter 메모장 및 기타 워크플로로 작업할 때 유용할 수 있습니다.
Firebase Console에서 모델 배포 및 관리
TensorFlow Lite 모델
Firebase Console을 사용하여 TensorFlow Lite 모델을 배포하려면 다음 안내를 따르세요.
- Firebase Console에서 Firebase ML 커스텀 모델 페이지를 엽니다.
- 커스텀 모델 추가 또는 다른 모델 추가를 클릭합니다.
- Firebase 프로젝트에서 모델을 식별하는 데 사용할 이름을 지정한 다음 일반적으로 .tflite또는.lite로 끝나는 TensorFlow Lite 모델 파일을 업로드합니다.
배포된 모델을 커스텀 페이지에서 찾을 수 있습니다. 커스텀 페이지에서는 모델 새 파일 업데이트, 모델 다운로드, 프로젝트에서 모델 삭제 등의 작업을 완료할 수 있습니다.
Firebase Admin SDK로 모델 배포 및 관리
이 섹션에서는 Admin SDK로 일반적인 모델 배포 및 관리 작업을 완료하는 방법을 설명합니다. 추가 도움말은 Python 또는 Node.js에 대한 SDK 참조를 확인하세요.
SDK 사용 예시는 Python 빠른 시작 샘플 및 Node.js 빠른 시작 샘플을 참조하세요.
시작하기 전에
- Firebase 프로젝트가 아직 없으면 Firebase Console에서 새 프로젝트를 만듭니다. 그런 다음 프로젝트를 열고 다음을 수행합니다. - 설정 페이지에서 서비스 계정을 만들고 서비스 계정 키 파일을 다운로드합니다. 이 파일로 프로젝트에 대한 관리자 액세스 권한을 부여할 수 있으므로 파일을 안전한 곳에 보관하세요. 
- 스토리지 페이지에서 Cloud Storage를 사용 설정합니다. 버킷 이름을 기록해 둡니다. - 모델 파일을 Firebase 프로젝트에 추가하는 동안 임시로 저장하려면 Cloud Storage 버킷이 필요합니다. Blaze 요금제를 사용 중이면 이 목적으로 기본값 이외의 버킷을 만들고 사용할 수 있습니다. 
- Firebase ML을 아직 사용 설정하지 않은 경우 Firebase ML 페이지에서 시작하기를 클릭합니다. 
 
- Google API 콘솔에서 Firebase 프로젝트를 열고 Firebase ML API를 사용 설정합니다. 
- 
SDK를 초기화할 때 모델을 저장하는 데 사용할 서비스 계정 사용자 인증 정보와 Cloud Storage 버킷을 지정합니다. Pythonimport 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.jsconst 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로 변환하고 단일 단계로 업로드할 수도 있습니다. 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 Console UI로 Edge 모델을 학습한 경우 Admin SDK를 사용하여 Firebase에 모델을 배포할 수 있습니다.
다음 예시와 유사한 문자열로 모델의 리소스 식별자를 지정해야 합니다.
projects/PROJECT_NUMBER/locations/STORAGE_LOCATION/models/MODEL_ID
| PROJECT_NUMBER | 모델이 포함된 Cloud Storage 버킷의 프로젝트 번호입니다. Firebase 프로젝트 또는 다른 Google Cloud 프로젝트일 수 있습니다. Firebase Console 또는 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);