fastapi框架之Web部署机器学习模型
随着机器学习的广泛应用,如何高效的把训练好的机器学习的模型部署在Web端。
效果展示
fastapi之Web部署机器学习模型
安装第三方库
pip install fastapi -i https://pypi.tuna.tsinghua.edu.cn/simple some-package pip install sklearn -i https://pypi.tuna.tsinghua.edu.cn/simple some-package pip install jinja2 -i https://pypi.tuna.tsinghua.edu.cn/simple some-package pip install uvicorn -i https://pypi.tuna.tsinghua.edu.cn/simple some-package pip install python-multipart -i https://pypi.tuna.tsinghua.edu.cn/simple some-package pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
训练模型
做了个小例子。用numpy随机生成训练集,使用线性回归进行训练,使用pickle库保存model模型。如下图所示
makeModel.py
import pickle import numpy as np from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt #创建数据 x=np.linspace(0,1,100).reshape(-1,1) y=[i*np.random.uniform(0.5,0.7) for i in np.linspace(0,1,100)] y=np.array(y) model=LinearRegression() model.fit(x,y) y_pred=model.predict(x) plt.plot(x,y) plt.plot(x,y_pred) plt.show() with open('model.pickle', 'wb') as file: pickle.dump(model, file)
app.py
from fastapi import FastAPI,Form,Request import uvicorn from fastapi.templating import Jinja2Templates import pickle import numpy as np app = FastAPI() templates = Jinja2Templates(directory="templates") @app.get('/') def index(request: Request): return templates.TemplateResponse("index.html",{"request": request,'y':''}) @app.post('/') def yPred(request: Request,argument=Form(...)): argument = argument lis = [[argument]] lis = np.array(lis).reshape(-1, 1) with open('model.pickle', 'rb') as f: model=pickle.load(f) y_pred=model.predict(lis) return templates.TemplateResponse("index.html",{"request": request,'y':{'x':argument,'y_pred':y_pred[0]}}) if __name__ == '__main__': uvicorn.run('app:app', port=8000)
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/" method="post"> <input name="argument"> <button>提交</button> {{y}} </form> </body> </html>
项目完整代码请点击我的云盘
提取码:6a1k
如有任何问题,欢迎在下方留言,谢谢!