การพยากรณ์ด้วย FastAPI และโมเดลที่เทรนไว้แล้ว

การ Deploy AI สู่ Production ด้วย FastAPI

Matt Eckerle

Software and Data Engineering Leader

ตั้งค่าสภาพแวดล้อม

ไลบรารีที่จำเป็น:  

  • FastAPI: เฟรมเวิร์กสำหรับสร้าง API ด้วย Python
  • uvicorn: ASGI server ที่รันเว็บแอปพลิเคชัน Python
  • joblib: สำหรับโหลดโมเดล

 

from fastapi import FastAPI
import uvicorn
import joblib
# Create the FastAPI app instance
app = FastAPI()
การ Deploy AI สู่ Production ด้วย FastAPI

โหลดโมเดลจำแนกเพนกวินที่เทรนไว้แล้ว

  • เทรนบนชุดข้อมูล 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
การ Deploy AI สู่ Production ด้วย FastAPI

Uvicorn

  • ASGI (Asynchronous Server Gateway Interface) server
  • พัฒนาโดยและสำหรับ Python
uvicorn main:app \
        --host 0.0.0.0 \
        --port 8080
import uvicorn
uvicorn.run(app, 
            host="0.0.0.0", 
            port=8080)

โลโก้ Uvicorn

การ Deploy AI สู่ Production ด้วย FastAPI

สร้าง endpoint สำหรับพยากรณ์

# 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}
การ Deploy AI สู่ Production ด้วย FastAPI

รันแอปพลิเคชัน

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

บันทึกโค้ดทั้งหมดในไฟล์ Python ชื่อ your_api_script.py

$ python3 your_api_script.py

บันทึก startup ของ Uvicorn

การ Deploy AI สู่ Production ด้วย FastAPI

ทดสอบ 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
}
การ Deploy AI สู่ Production ด้วย FastAPI

มาฝึกกันเถอะ!

การ Deploy AI สู่ Production ด้วย FastAPI

Preparing Video For Download...