사전 학습 모델을 활용한 FastAPI 예측

FastAPI로 AI 프로덕션 배포하기

Matt Eckerle

Software and Data Engineering Leader

환경 설정

필수 라이브러리:  

  • FastAPI: Python으로 API를 구축하는 프레임워크
  • uvicorn: Python 웹 앱을 실행하는 고속 ASGI 서버
  • joblib: 모델 로드에 사용

 

from fastapi import FastAPI
import uvicorn
import joblib
# Create the FastAPI app instance
app = FastAPI()
FastAPI로 AI 프로덕션 배포하기

사전 학습된 펭귄 분류기 로드

  • Palmer Penguins 데이터셋으로 학습
  • 4가지 특징으로 펭귄 종 예측: 부리 길이, 부리 깊이, 지느러미 길이, 체질량
  • 출력: Adelie, Chinstrap, Gentoo
import joblib

# Load the pre-trained model
model = joblib.load('penguin_classifier.pkl')
# Check data type of model to verify model loading
print(type(model))
<class 'sklearn.pipeline.Pipeline'>
1 https://huggingface.co/SIH/penguin-classifier-sklearn
FastAPI로 AI 프로덕션 배포하기

Uvicorn

  • ASGI(비동기 서버 게이트웨이 인터페이스) 서버
  • Python을 위해 Python으로 개발
uvicorn main:app \
        --host 0.0.0.0 \
        --port 8080
import uvicorn
uvicorn.run(app, 
            host="0.0.0.0", 
            port=8080)

Uvicorn 로고

FastAPI로 AI 프로덕션 배포하기

예측 엔드포인트 생성

# FastAPI prediction endpoint
@app.post("/predict")
def predict(culmen_length_mm, culmen_depth_mm, 
            flipper_length_mm, body_mass_g):

    features = [[culmen_length_mm, culmen_depth_mm,
                 flipper_length_mm, body_mass_g]]

    prediction = model.predict(features)[0]
    return {"predicted_species": prediction}
FastAPI로 AI 프로덕션 배포하기

애플리케이션 실행

if __name__ == "__main__":
    uvicorn.run(
      app, 
      host="0.0.0.0", 
      port=8080)

모든 코드를 파이썬 파일로 저장합니다 - your_api_script.py

$ python3 your_api_script.py

Uvicorn 시작 로그

FastAPI로 AI 프로덕션 배포하기

API 테스트

curl \

-X POST "http://localhost:8080/predict" \
-H "Content-Type: application/json" \
-d '{"culmen_length_mm": 39.1, "culmen_depth_mm": 18.7, "flipper_length_mm": 181, "body_mass_g": 3750}'
{
    "prediction": "Adelie",
    "confidence": 0.87
}
FastAPI로 AI 프로덕션 배포하기

연습해 봅시다!

FastAPI로 AI 프로덕션 배포하기

Preparing Video For Download...