使用預訓練模型的 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(Asynchronous Server Gateway Interface)伺服器
  • 為 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)

將所有程式碼存成 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...