FastAPI와 TensorFlow를 연동하여 딥러닝 모델 배포하기

딥러닝 모델을 실제 서비스로 배포하기 위해서는 웹 애플리케이션 프레임워크와 딥러닝 프레임워크 사이의 연동이 필요합니다.

이번 포스트에서는 FastAPI 웹 프레임워크와 TensorFlow 딥러닝 프레임워크를 연동하여 딥러닝 모델을 배포하는 방법을 알아보겠습니다.

FastAPI란?

FastAPI는 Python 기반의 빠르고 (Fast) 간단한 (API) 웹 애플리케이션 프레임워크입니다.

장점:

TensorFlow란?

TensorFlow는 딥러닝을 위한 오픈소스 프레임워크로서, 다양한 딥러닝 모델을 구축하고 훈련시킬 수 있습니다.

장점:

FastAPI와 TensorFlow 연동하기

  1. 필요한 패키지 설치하기

FastAPI와 TensorFlow 패키지를 설치합니다.

pip install fastapi tensorflow
  1. FastAPI 애플리케이션 작성하기

FastAPI를 사용하여 간단한 애플리케이션을 작성합니다.

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def hello():
    return {"message": "Hello, World!"}
  1. 딥러닝 모델 로딩하기

TensorFlow를 사용하여 딥러닝 모델을 로딩합니다.

import tensorflow as tf

model = tf.keras.models.load_model("model.h5")
  1. 모델 예측하기

FastAPI 엔드포인트에서 입력 데이터를 받아 모델을 이용하여 예측합니다.

@app.post("/predict")
def predict(data: List[float]):
    data = tf.expand_dims(data, axis=0)
    pred = model.predict(data)
    return {"prediction": pred}
  1. FastAPI 서버 실행하기

FastAPI 애플리케이션을 실행하고, 브라우저나 API 클라이언트를 통해 모델에 대한 예측을 요청할 수 있습니다.

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

위와 같은 방법으로 FastAPI와 TensorFlow를 연동하여 딥러닝 모델을 배포할 수 있습니다.

딥러닝 모델을 웹 애플리케이션에 통합함으로써 쉽고 편리하게 모델을 사용하고, API를 통해 예측 결과를 손쉽게 얻을 수 있습니다.

#FastAPI #TensorFlow