App下載

怎么使用flask將模型部署為服務(wù)?

一只窗邊的貓 2021-08-16 14:06:23 瀏覽數(shù) (2061)
反饋

我們使用機(jī)器學(xué)習(xí)進(jìn)行模型訓(xùn)練,最后會(huì)得到一個(gè)模型,怎么將這個(gè)模型部署到flask服務(wù)上呢?今天我們就來介紹一下模型的部署。

1. 加載保存好的模型

為了方便起見,這里我們就使用簡(jiǎn)單的分詞模型,相關(guān)代碼如下:model.py

import jieba


class JiebaModel:
    def load_model(self):
        self.jieba_model = jieba.lcut

    def generate_result(self, text):
        return self.jieba_model(text, cut_all=False)

說明:在load_model方法中加載保存好的模型,無論是sklearn、tensorflow還是pytorch的都可以在里面完成。在generate_result方法中定義處理輸入后得到輸出的邏輯,并返回結(jié)果。

2. 使用flask起服務(wù)

代碼如下:test_flask.py

# -*-coding:utf-8-*-
from flask import Flask, request, Response, abort
from flask_cors import CORS
# from ast import literal_eval
import time
import sys
import json
import traceback

from model import JiebaModel

app = Flask(__name__)
CORS(app) # 允許所有路由上所有域使用CORS

@app.route("/", methods=['POST', 'GET'])
def inedx():
    return '分詞程序正在運(yùn)行中'

@app.route("/split_words", methods=['POST', 'GET'])
def get_result():
    if request.method == 'POST':
        text = request.data.decode("utf-8")
    else:
        text = request.args['text']

    try:
        start = time.time()
        print("用戶輸入",text)
        res = jiebaModel.generate_result(text)
        end = time.time()
        print('分詞耗時(shí):', end-start)
        print('分詞結(jié)果:', res)
        result = {'code':'200','msg':'響應(yīng)成功','data':res}
    except Exception as e:
        print(e)
        result_error = {'errcode': -1}
        result = json.dumps(result_error, indent=4, ensure_ascii=False)
        # 這里用于捕獲更詳細(xì)的異常信息
        exc_type, exc_value, exc_traceback = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
        # 提前退出請(qǐng)求
        abort(Response("Failed!
" + '

'.join('' + line for line in lines)))
    return Response(str(result), mimetype='application/json')


if __name__ == "__main__":
    jiebaModel = JiebaModel()
    jiebaModel.load_model()
    app.run(host='0.0.0.0', port=1314, threaded=False)

說明:我們定義了一個(gè)get_result()函數(shù),對(duì)應(yīng)的請(qǐng)求是ip:port/split_words。 首先我們根據(jù)請(qǐng)求是get請(qǐng)求還是post請(qǐng)求獲取數(shù)據(jù),然后使用模型根據(jù)輸入數(shù)據(jù)得到輸出結(jié)果,并返回響應(yīng)給請(qǐng)求。如果遇到異常,則進(jìn)行相應(yīng)的處理后并返回。在__main__中,我們引入了model.py的JiebaModel類,然后加載了模型,并在get_result()中調(diào)用。

3. 發(fā)送請(qǐng)求并得到結(jié)果

代碼如下:test_request.py

import requests

def get_split_word_result(text):
    res = requests.post('http://{}:{}/split_words'.format('本機(jī)ip', 1314), data=str(text).encode('utf-8'))
    print(res.text)

get_split_word_result("我愛北京天安門")

說明:通過requests發(fā)送post請(qǐng)求,請(qǐng)求數(shù)據(jù)編碼成utf-8的格式,最后得到響應(yīng),并利用.text得到結(jié)果。

4. 效果呈現(xiàn)

(1)運(yùn)行test_flask.py

運(yùn)行結(jié)果

(2)運(yùn)行test_request.py

運(yùn)行結(jié)果

并在起服務(wù)的位置看到:

運(yùn)行結(jié)果

以上就是怎么將機(jī)器學(xué)習(xí)的模型部署到flask服務(wù)的詳細(xì)內(nèi)容,更多機(jī)器學(xué)習(xí)的學(xué)習(xí)資料請(qǐng)關(guān)注W3Cschool其它相關(guān)文章!



0 人點(diǎn)贊