
使用NestJS和Prisma構建REST API:身份驗證
import numpy as np
from sklearn.ensemble import RandomForestClassifier
# 訓練一個簡單的模型
model = RandomForestClassifier()
X = np.random.randn(100, 4)
y = np.random.randint(0, 2, 100)
model.fit(X, y)
# 保存模型到bentoml
bentoml.sklearn.save_model(
"iris_classifier",
model,
signatures={
"predict": {"batchable": True}
}
)
接下來,我們創建一個服務類來包裝我們的模型:
import bentoml
import numpy as np
from bentoml.io import NumpyNdarray
# 加載保存的模型
iris_clf_runner = bentoml.sklearn.get("iris_classifier:latest").to_runner()
# 創建服務
svc = bentoml.Service("iris_classifier", runners=[iris_clf_runner])
# 創建API端點
@svc.api(input=NumpyNdarray(), output=NumpyNdarray())
async def predict(input_array: np.ndarray) -> np.ndarray:
result = await iris_clf_runner.predict.async_run(input_array)
return result
寫好Service后,我們可以把它保存成service.py
,然后用命令行啟動服務:
bentoml serve service:svc
接下來就可以用curl或者Python請求這個服務了:
import requests
import numpy as np
# 準備測試數據
test_data = np.random.randn(1, 4)
# 發送請求
response = requests.post(
"http://localhost:3000/predict",
json=test_data.tolist()
)
print(response.json())
bentoml還支持很多高級功能,比如模型版本管理和API文檔自動生成:
import bentoml
from bentoml.io import JSON, NumpyNdarray
from pydantic import BaseModel
class IrisInput(BaseModel):
sepal_length: float
sepal_width: float
petal_length: float
petal_width: float
svc = bentoml.Service(
"iris_classifier_advanced",
runners=[iris_clf_runner]
)
@svc.api(
input=JSON(pydantic_model=IrisInput),
output=JSON(),
description="預測鳶尾花品種"
)
async def predict_species(input_data: IrisInput):
input_array = np.array([[
input_data.sepal_length,
input_data.sepal_width,
input_data.petal_length,
input_data.petal_width
]])
result = await iris_clf_runner.predict.async_run(input_array)
return {"predicted_species": int(result[0])}
--port
參數修改bentoml models list
查看所有保存的模型bentoml.Service
中可以設置多個runners,實現模型ensemble試試看:把你之前訓練的任意一個機器學習模型用bentoml包裝成服務,并嘗試用不同的方式(curl、Python requests、Swagger UI)來調用它。
提示:訪問http://localhost:3000/docs
可以看到自動生成的API文檔和在線測試界面。
小伙伴們,今天的Python學習之旅就到這里啦!記得動手敲代碼,有問題隨時在評論區問阿圖哦。bentoml真的是機器學習部署的神器,掌握了它,你的模型就能輕松上線啦!祝大家學習愉快,Python學習節節高!
本文章轉載微信公眾號@月光下的阿圖