인공지능

[인공지능] Firebase functions 이용하여 AI 모델 사용하기 - (feat. tensorflow)

Shong Studio 2024. 3. 30. 18:45
728x90
반응형

TensorFlow로 학습시킨 모델을 Firebase의 Functions 기능과 함께 사용하는 것은 가능합니다.

Firebase Functions는 Google Cloud Functions의 특성을 기반으로 하며, Node.js, Python, Go 등을 지원합니다.

TensorFlow 모델을 TensorFlow.js로 변환하거나, TensorFlow Serving을 사용하여 API로 모델을 제공하고, 이 API를 Firebase Functions에서 호출하는 방법으로 구현할 수 있습니다.

 

TensorFlow.js 사용

TensorFlow.js는 웹 브라우저나 Node.js 환경에서 TensorFlow 모델을 실행할 수 있게 해 줍니다. 이 방법을 사용하려면, 먼저 Python 등에서 학습한 TensorFlow 모델을 TensorFlow.js 포맷으로 변환해야 합니다.

  1. 모델 변환: TensorFlow 모델을 TensorFlow.js 포맷으로 변환합니다.
  2. Firebase Functions에 모델 배포: 변환된 모델을 Firebase Functions 프로젝트에 포함시키고, 해당 함수 내에서 모델을 불러와 예측을 실행합니다.
  3. 주기적 실행: Firebase의 pubsub 스케줄러를 사용하여 특정 시간에 함수를 실행하도록 설정합니다.

 

TensorFlow Serving + API 호출

TensorFlow Serving을 사용하여 모델을 서버에서 실행하고, HTTP 또는 gRPC API로 모델에 접근할 수 있습니다. 이 API를 Firebase Functions에서 호출하여 예측을 수행할 수 있습니다.

  1. TensorFlow Serving으로 모델 호스팅: 모델을 TensorFlow Serving을 사용하여 호스팅합니다.
  2. API 생성: 모델 서버가 제공하는 HTTP/gRPC API를 통해 외부에서 모델에 접근할 수 있습니다.
  3. Firebase Functions에서 API 호출: Firebase Functions 내에서 HTTP 요청을 사용하여 TensorFlow Serving API를 호출하고, 응답으로 받은 예측 결과를 처리합니다.
  4. 주기적 실행: 마찬가지로, pubsub 스케줄러를 사용하여 이러한 함수를 정기적으로 실행합니다.

 

코드 (TensorFlow.js를 사용하는 경우)

const functions = require('firebase-functions');
const tf = require('@tensorflow/tfjs');
const modelPath = '모델 경로'; // 모델을 저장한 경로

exports.predictStock = functions.pubsub.schedule('매일 00:00').onRun(async (context) => {
  await tf.loadLayersModel(modelPath).then(async (model) => {
    // 입력 데이터 준비
    const inputData = tf.tensor2d([/* 입력 데이터 배열 */]);
    // 모델 예측 실행
    const prediction = model.predict(inputData);
    // 예측 결과 처리
    console.log(prediction.arraySync());
  }).catch(err => console.error(err));
});

 

위와 같이 TensorFlow 모델을 Firebase Functions와 함께 사용하면 서버리스 아키텍처에서 머신 러닝 모델을 운영할 수 있어 관리할 수 있습니다.

 

다만, Firebase Functions의 실행 시간, 메모리 제한 등을 고려해야 합니다. TensorFlow 모델의 크기나 복잡성에 따라 Firebase Functions의 기본 제공 리소스로는 부족할 수 있으므로, 필요에 따라 Cloud Functions의 고급 설정을 조정하거나 다른 클라우드 서비스를 함께 사용하는 것을 고려해야 할 수도 있습니다.

728x90
반응형