事前学習済みモデルによる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))


----CODE_GLUE----
```out

<class 'sklearn.pipeline.Pipeline'>
1 https://huggingface.co/SIH/penguin-classifier-sklearn
FastAPI を使った AI のプロダクション環境へのデプロイ

Uvicorn

  • ASGI(非同期サーバーゲートウェイインターフェース)サーバー
  • 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)

すべてのコードをPythonファイルに保存します - 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...