import numpy as np
from sklearn.ensemble import RandomForestClassifier

# 訓(xùn)練一個(gè)簡(jiǎn)單的模型
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}
}
)

創(chuàng)建Service類

接下來,我們創(chuàng)建一個(gè)服務(wù)類來包裝我們的模型:

import bentoml
import numpy as np
from bentoml.io import NumpyNdarray

# 加載保存的模型
iris_clf_runner = bentoml.sklearn.get("iris_classifier:latest").to_runner()

# 創(chuàng)建服務(wù)
svc = bentoml.Service("iris_classifier", runners=[iris_clf_runner])

# 創(chuàng)建API端點(diǎn)
@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,然后用命令行啟動(dòng)服務(wù):

bentoml serve service:svc

接下來就可以用curl或者Python請(qǐng)求這個(gè)服務(wù)了:

import requests
import numpy as np

# 準(zhǔn)備測(cè)試數(shù)據(jù)
test_data = np.random.randn(1, 4)

# 發(fā)送請(qǐng)求
response = requests.post(
"http://localhost:3000/predict",
json=test_data.tolist()
)

print(response.json())

高級(jí)功能展示

bentoml還支持很多高級(jí)功能,比如模型版本管理和API文檔自動(dòng)生成:

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="預(yù)測(cè)鳶尾花品種"
)
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])}

小貼士

  1. 1. bentoml默認(rèn)使用3000端口,可以通過--port參數(shù)修改
  2. 2. 生產(chǎn)環(huán)境部署時(shí)記得配置CORS和認(rèn)證
  3. 3. 可以用bentoml models list查看所有保存的模型
  4. 4. 在bentoml.Service中可以設(shè)置多個(gè)runners,實(shí)現(xiàn)模型ensemble

實(shí)戰(zhàn)小練習(xí)

試試看:把你之前訓(xùn)練的任意一個(gè)機(jī)器學(xué)習(xí)模型用bentoml包裝成服務(wù),并嘗試用不同的方式(curl、Python requests、Swagger UI)來調(diào)用它。

提示:訪問http://localhost:3000/docs可以看到自動(dòng)生成的API文檔和在線測(cè)試界面。

小伙伴們,今天的Python學(xué)習(xí)之旅就到這里啦!記得動(dòng)手敲代碼,有問題隨時(shí)在評(píng)論區(qū)問阿圖哦。bentoml真的是機(jī)器學(xué)習(xí)部署的神器,掌握了它,你的模型就能輕松上線啦!祝大家學(xué)習(xí)愉快,Python學(xué)習(xí)節(jié)節(jié)高!

本文章轉(zhuǎn)載微信公眾號(hào)@月光下的阿圖

上一篇:

AnalyticDB向量檢索+AI 實(shí)戰(zhàn): 聲紋識(shí)別

下一篇:

AGI|一文識(shí)別LangChain中ChatOpenAI 和OpenAI的區(qū)別
#你可能也喜歡這些API文章!

我們有何不同?

API服務(wù)商零注冊(cè)

多API并行試用

數(shù)據(jù)驅(qū)動(dòng)選型,提升決策效率

查看全部API→
??

熱門場(chǎng)景實(shí)測(cè),選對(duì)API

#AI文本生成大模型API

對(duì)比大模型API的內(nèi)容創(chuàng)意新穎性、情感共鳴力、商業(yè)轉(zhuǎn)化潛力

25個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)

#AI深度推理大模型API

對(duì)比大模型API的邏輯推理準(zhǔn)確性、分析深度、可視化建議合理性

10個(gè)渠道
一鍵對(duì)比試用API 限時(shí)免費(fèi)