Dự đoán với FastAPI dùng mô hình đã huấn luyện

Triển khai AI vào môi trường sản xuất với FastAPI

Matt Eckerle

Software and Data Engineering Leader

Thiết lập môi trường

Thư viện cần có:  

  • FastAPI: framework xây dựng API với Python
  • uvicorn: máy chủ ASGI nhanh chạy ứng dụng web Python
  • joblib: để tải mô hình

 

from fastapi import FastAPI
import uvicorn
import joblib
# Tạo instance ứng dụng FastAPI
app = FastAPI()
Triển khai AI vào môi trường sản xuất với FastAPI

Tải bộ phân loại chim cánh cụt đã huấn luyện

  • Được huấn luyện trên bộ dữ liệu Palmer Penguins
  • Dự đoán loài chim cánh cụt dựa trên 4 đặc trưng: độ dài mỏ, độ sâu mỏ, độ dài vây, và khối lượng cơ thể
  • Đầu ra: Adelie, Chinstrap, hoặc Gentoo
import joblib

# Tải mô hình đã huấn luyện
model = joblib.load('penguin_classifier.pkl')
# Kiểm tra kiểu dữ liệu của mô hình để xác nhận đã tải
print(type(model))
<class 'sklearn.pipeline.Pipeline'>
1 https://huggingface.co/SIH/penguin-classifier-sklearn
Triển khai AI vào môi trường sản xuất với FastAPI

Uvicorn

  • Máy chủ ASGI (Asynchronous Server Gateway Interface)
  • Xây dựng bằng và cho Python
uvicorn main:app \
        --host 0.0.0.0 \
        --port 8080
import uvicorn
uvicorn.run(app, 
            host="0.0.0.0", 
            port=8080)

Logo Uvicorn

Triển khai AI vào môi trường sản xuất với FastAPI

Tạo endpoint dự đoán

# Endpoint dự đoán với FastAPI
@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}
Triển khai AI vào môi trường sản xuất với FastAPI

Chạy ứng dụng

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

Lưu toàn bộ mã vào một tệp python - your_api_script.py

$ python3 your_api_script.py

Log khởi động Uvicorn

Triển khai AI vào môi trường sản xuất với FastAPI

Kiểm thử 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
}
Triển khai AI vào môi trường sản xuất với FastAPI

Cùng luyện tập nào!

Triển khai AI vào môi trường sản xuất với FastAPI

Preparing Video For Download...