100天搞定機(jī)器學(xué)習(xí) 番外:使用FastAPI構(gòu)建機(jī)器學(xué)習(xí)API
↓↓↓點(diǎn)擊關(guān)注,回復(fù)資料,10個(gè)G的驚喜
100天搞定機(jī)器學(xué)習(xí):模型訓(xùn)練好了,然后呢?
FastAPI
FastAPI 是一個(gè)高性能 Web 框架,用于構(gòu)建 API。

FastAPI 建立在 Starlette 和 Pydantic 之上。
Starlette:輕量級(jí)的 ASGI 框架和工具包,用來構(gòu)建高性能的 asyncio 服務(wù) Pydantic:Python中用于數(shù)據(jù)接口schema定義與檢查的庫。通過它,可以更為規(guī)范地定義和使用數(shù)據(jù)接口。
想要深入學(xué)習(xí)這兩個(gè)庫,可以移步對(duì)應(yīng)官方文檔:
https://pydantic-docs.helpmanual.io/
https://www.starlette.io/
實(shí)際應(yīng)用中,F(xiàn)astAPI 需要與Uvicorn一起使用,Uvicorn主要用于加載和提供應(yīng)用程序的服務(wù)器。
FastAPI和Uvicorn的使用方法
使用之前先安裝
pip?install?fastapi
pip?install?uvicorn
看一個(gè)小例子,感受一下FastAPI 多方便,多簡(jiǎn)單:
from?typing?import?Optional
from?fastapi?import?FastAPI
import?uvicorn
#創(chuàng)建FastAPI實(shí)例
app?=?FastAPI()
#創(chuàng)建訪問路徑
@app.get("/")
def?read_root():#定義根目錄方法
????return?{"message":?"Hello?World"}#返回響應(yīng)信息
#定義方法,處理請(qǐng)求
@app.get("/items/{item_id}")
async?def?read_item(item_id:?int):
????return?{"item_id":?item_id}
#運(yùn)行
if?__name__?==?'__main__':
????uvicorn.run(app,?host="127.0.0.1",?port=8000)
uvicron服務(wù)器運(yùn)行之后可以嘗試訪問
http://127.0.0.1:8000/items/666,返回:
也可進(jìn)在文檔中調(diào)試
打開交互文檔(Swagger UI):http://127.0.0.1:8000/docs也可以訪問API文檔(ReDoc):http://127.0.0.1:8080/redoc

FastAPI部署機(jī)器學(xué)習(xí)模型
第一步:準(zhǔn)備模型
import?numpy?as?np
import?os
from?sklearn.linear_model?import?LogisticRegression
from?sklearn.pipeline?import?Pipeline
import?joblib
from?sklearn?import?datasets
def?main():
????clf?=?LogisticRegression()
????p?=?Pipeline([('clf',?clf)])
????print('Training?model...')
????p.fit(X,?y)
????print('Model?trained!')
????filename_p?=?'IrisClassifier.pkl'
????print('Saving?model?in?%s'?%?filename_p)
????joblib.dump(p,?filename_p)
????print('Model?saved!')
if?__name__?==?"__main__":
????print('Loading?iris?data?set...')
????iris?=?datasets.load_iris()
????X,?y?=?iris.data,?iris.target
????print('Dataset?loaded!')
????main()
第二步:創(chuàng)建FastAPI實(shí)例
import?uvicorn
from?fastapi?import?FastAPI?
import?joblib
from?os.path?import?dirname,?join,?realpath
from?typing?import?List
app?=?FastAPI(
????title="Iris?Prediction?Model?API",
????description="A?simple?API?that?use?LogisticRegression?model?to?predict?the?Iris?species",
????version="0.1",
)
#?load??model
with?open(
????join(dirname(realpath(__file__)),?"models/IrisClassifier.pkl"),?"rb"
)?as?f:
????model?=?joblib.load(f)
def?data_clean(str):
????arr?=?str.split(',')
????arr?=?list(map(float,arr))
????return?arr
????
#?Create?Prediction?Endpoint
@app.get("/predict-result")
def?predict_iris(request):
????#?perform?prediction
????request?=?data_clean(request)
????prediction?=?model.predict([request])
????output?=?int(prediction[0])
????probas?=?model.predict_proba([request])
????output_probability?=?"{:.2f}".format(float(probas[:,?output]))
????
????#?output?dictionary
????species?=?{0:?"Setosa",?1:?"Versicolour",?2:"Virginica"}
????
????#?show?results
????result?=?{"prediction":?species[output],?"Probability":?output_probability}
????return?result
if?__name__?==?'__main__':
????uvicorn.run(app,?host="127.0.0.1",?port=8001)
第三步:傳入?yún)?shù)
我們用模型預(yù)測(cè)屬性為以下值時(shí)Iris應(yīng)該屬于哪一類,并輸出預(yù)測(cè)概率。
sepal_length=7.233
sepal_width=4.652
petal_length=7.39
petal_width=0.324
打開網(wǎng)址,傳入?yún)?shù)?
http://127.0.0.1:8001/predict-result?request=7.233%2C4.652%2C7.39%2C0.324

bingo!
推薦閱讀
用Python學(xué)線性代數(shù):自動(dòng)擬合數(shù)據(jù)分布 Python 用一行代碼搞事情,機(jī)器學(xué)習(xí)通吃 Github 上最大的開源算法庫,還能學(xué)機(jī)器學(xué)習(xí)! JupyterLab 這插件太強(qiáng)了,Excel靈魂附體 終于把 jupyter notebook 玩明白了 一個(gè)超好用的 Python 標(biāo)準(zhǔn)庫,666? 幾百本編程中文書籍(含Python)持續(xù)更新 100天搞定機(jī)器學(xué)習(xí)|Day63 徹底掌握 LightGBM
好文點(diǎn)個(gè)在看吧!
