机器学习项目是如何开发和部署的?

本文以一个小项目带你弄清ML的项目流程

这周做作业查资料时,无意中看到一个GitHub项目ML-web-app,它以PyTorch训练MNIST文字识别模型为例,介绍了从模型训练部署上线的整个流程。是非常好的学习项目!下图是效果图:

笔者浏览了项目的代码,以学习为目的,简单解读下这个项目。

模型训练

模型训练是相对独立的部分,可以由算法工程师来做。总结起来就是调用PyTorch接口,建立一个神经网络,然后利用MNIST数据进行训练,最后把训练好的模型文件存储起来,后面部署的时候要用到

服务部署

该项目使用Flask框架部署服务,为了方便阅读,笔者对代码进行了精简

下面的代码中,通过加载预训练好的模型数据,得到模型实例,可以进行预测:

# initialize flask application
app = Flask(__name__)

# Read model to keep it ready all the time
model = MyModel('./ml_model/trained_weights.pth', 'cpu')

核心预测API路由,路径是/predict

@app.route('/predict', methods=['GET','POST'])
def predict():
    results = {"prediction" :"Empty", "probability" :{}}

    input_img = BytesIO(base64.urlsafe_b64decode(request.form['img']))

    res =  model.predict(input_img)
    return json.dumps(results)

请求过程

默认主页是通过模板渲染的,在index.js中定义了两个核心函数:

  1. onRecognition函数通过Ajax向/predict API路由发送POST请求,请求中封装了要识别的图片,然后获取模型预测结果。
// post data to server for recognition
function onRecognition() {
    $.ajax({
            url: './predict',
            type:'POST',
            data : {img : cvsIn.toDataURL("image/png").replace('data:image/png;base64,','') },

        }).done(function(data) {
            showResult(JSON.parse(data))
        })
}
  1. showResult函数把结果渲染出来。
function showResult(resultJson){
    // show predict digit
    divOut.textContent = resultJson.prediction;
    // show probability
    document.getElementById("probStr").innerHTML =
        "Probability : " + resultJson.probability.toFixed(2) + "%";
}

总结

这个项目麻雀虽小,五脏俱全。可以帮助非算法类程序员一窥ML从建模到上线部署整个流程,透过火爆的趋势看清本质。

文章持续更新,可以微信搜索「 机器学习与系统 」阅读最新内容,回复资料内推考研获取我为你准备的惊喜~

猜你喜欢

转载自www.cnblogs.com/quantalk/p/12984693.html
今日推荐