如何用FastAPI构建模型推理服务?
中等
答题要点
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import numpy as np
app = FastAPI()
# 启动时加载模型
model = None
@app.on_event("startup")
async def load_model():
global model
model = joblib.load("model.pkl")
class PredictRequest(BaseModel):
features: list[float]
@app.post("/predict")
async def predict(request: PredictRequest):
features = np.array(request.features).reshape(1, -1)
prediction = model.predict(features)
return {
"prediction": prediction[0].tolist(),
"model_version": "v1.0"
}
@app.get("/health")
async def health():
return {"status": "ok"}
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题