本文可以讓你把訓練好的機器學習模型使用Flask API 投入生產環境。
本文旨在讓您把訓練好的機器學習模型通過Flask API 投入到生產環境 。當數據科學或者機器學習工程師使用Scikit-learn、Tensorflow、Keras 、PyTorch等框架部署機器學習模型時,最終的目的都是使其投入生產。通常,我們在做機器學習項目的過程中,將注意力集中在數據分析,特徵工程,調整參數等方面。但是,我們往往會忘記主要目標,即從模型預測結果中獲得實際的價值。部署機器學習模型或者將模型投入生產,意味著將模型提供給最終的用戶或系統使用。然而機器學習模型部署具有一定的複雜性,本文可以讓你把訓練好的機器學習模型使用Flask API 投入生產環境。我將使用線性回歸,通過利率和前兩個月的銷售額來預測第三個月的銷售額。線性回歸模型的目標是找出一個或多個特徵(自變量)和一個連續目標變量(因變量)之間的關係。如果只有一個特徵,則稱為單變量線性回歸;如果有多個特徵,則稱為多元線性回歸。容易上手使用
內置開發工具和調試工具
集成單元測試功能
平穩的請求調度
詳盡的文檔
1. model.py -- 包含機器學習模型的代碼,用於根據前兩個月的銷售額預測第三個月的銷售額。2. app.py – 包含用於從圖形用戶界面(GUI)或者API調用獲得詳細銷售數據的Flask API,Flask API根據我們的模型計算預測值並返回。3. request.py -- 使用requests模塊調用app.py中定義的API並顯示返回值。4. HTML/CSS – 包含HTML模板和CSS風格代碼,允許用戶輸入銷售細節並顯示第三個月的預測值。代碼在哪裡呢?
從代碼開始,完整的項目可以在github上找到(https://github.com/abhinavsagar/Machine-Learning-Deployment-Tutorials)。我們使用HTML構建前端,讓用戶輸入數據。這裡有三個區域需要用戶去填寫—利率,第一個月的銷售額以及第二個月的銷售額。<!DOCTYPE html><html ><head> <meta charset="UTF-8"> <title>Deployment Tutorial 1</title> <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"></head><body style="background: #000;"> <div><h1>Sales Forecasting </h1> <!-- Main Input For Receiving Query to our ML --> <form action="{{ url_for('predict')}}"method="post"> <input type="text" name="rate" placeholder="rate" required="required" /> <input type="text" name="sales in first month" placeholder="sales in first month" required="required" /> <input type="text" name="sales in second month" placeholder="sales in second month" required="required" /> <button type="submit" class="btn btn-primary btn-block btn-large">Predict sales in third month</button> </form> <br> <br> {{ prediction_text }} </div> </body> </html>接下來,使用CSS對輸入按鈕、登錄按鈕和背景進行了一些樣式設置。
@import url(https://fonts.googleapis.com/css?family=Open+Sans);html { width: 100%; height:100%; overflow:hidden; }body {width: 100%;height:100%;font-family: 'Helvetica';background: #000;color: #fff;font-size: 24px;text-align:center;letter-spacing:1.4px;}.login {position: absolute;top: 40%;left: 50%;margin: -150px 0 0 -150px;width:400px;height:400px;}login h1 { color: #fff; text-shadow: 0 0 10px rgba(0,0,0,0.3); letter-spacing:1px; text-align:center; }input {width: 100%; margin-bottom: 10px; background: rgba(0,0,0,0.3); border: none; outline: none; padding: 10px; font-size: 13px; color: #fff; text-shadow: 1px 1px 1px rgba(0,0,0,0.3); border: 1px solid rgba(0,0,0,0.3); border-radius: 4px; box-shadow: inset 0 -5px 45px rgba(100,100,100,0.2), 0 1px 1px rgba(255,255,255,0.2); -webkit-transition: box-shadow .5s ease; -moz-transition: box-shadow .5s ease; -o-transition: box-shadow .5s ease; -ms-transition: box-shadow .5s ease; transition: box-shadow .5s ease; }我為這個項目創建了一個定製的銷售數據集,它有四列——利率、第一個月的銷售額、第二個月的銷售額和第三個月的銷售額。我們現在構建一個機器學習模型來預測第三個月的銷售額。首先使用Pandas解決缺失值問題,當一項或多項指標沒有信息時,就會有缺失值發生。使用0填充利率這一列的缺失值,平均值填充第一個月銷售額中的缺失值,採用線性回歸的機器學習算法。簡而言之,序列化是一種在磁碟上寫入python對象的方法,該對象可以傳輸到任何地方,然後通過python腳本反序列化(讀)回去。使用Pickling將是python對象形式的模型轉為字符流形式,其思想是這個字符流中包含了在另一個python腳本中重建這個對象所需的所有信息。import numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport pickledataset = pd.read_csv('sales.csv')dataset['rate'].fillna(0, inplace=True)dataset['sales_in_first_month'].fillna(dataset['sales_in_first_month'].mean(), inplace=True)X = dataset.iloc[:, :3]def convert_to_int(word): word_dict = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9, 'ten':10, 'eleven':11, 'twelve':12, 'zero':0, 0: 0} return word_dict[word]X['rate'] = X['rate'].apply(lambda x : convert_to_int(x))y = dataset.iloc[:, -1]from sklearn.linear_model import LinearRegressionregressor = LinearRegression()
regressor.fit(X, y)pickle.dump(regressor, open('model.pkl','wb'))model = pickle.load(open('model.pkl','rb'))print(model.predict([[4, 300, 500]]))下一部分是構建一個API,反序列化這個模型為python對象格式,並通過圖形用戶界面(GUI)獲取詳細銷售數據,根據模型計算預測值。我使用index.html設置主頁,並在使用POST請求方式提交表單數據時,獲取預測的銷售值。可以通過另一個POST請求將結果發送給results並展示出來。它接收JSON格式的輸入,並使用訓練好的模型預測出可以被API端點接受的JSON格式的預測值。import numpy as npfrom flask import Flask, request, jsonify, render_templateimport pickleapp = Flask(__name__)model = pickle.load(open('model.pkl', 'rb'))@app.route('/')def home(): return render_template('index.html') @app.route('/predict',methods=['POST']) def predict(): int_features = [int(x) for x in request.form.values()] final_features = [np.array(int_features)] prediction = model.predict(final_features) output = round(prediction[0], 2) return render_template('index.html', prediction_text='Sales should be $ {}'.format(output))@app.route('/results',methods=['POST'])def results(): data = request.get_json(force=True) prediction = model.predict([np.array(list(data.values()))]) output = prediction[0] return jsonify(output)if __name__ == "__main__":app.run(debug=True)最後使用requests模塊調用在app.py中定義的APIs,它的結果是第三個月銷售額的預測值。import requestsurl = 'http://localhost:5000/results'r = requests.post(url,json={'rate':5, 'sales_in_first_month':200, 'sales_in_second_month':400})print(r.json()) Results在web瀏覽器中打開http://127.0.1:5000/,將顯示如下所示的GUI.How to Easily Deploy Machine Learning Models Using Flaskhttps://www.kdnuggets.com/2019/10/easily-deploy-machine-learning-models-using-flask.html譯者簡介:申利彬,研究生在讀,主要研究方向大數據機器學習。目前在學習深度學習在NLP上的應用,希望在THU數據派平臺與愛好大數據的朋友一起學習進步。
END
轉自:數據派THU 公眾號;
版權聲明:本號內容部分來自網際網路,轉載請註明原文連結和作者,如有侵權或出處有誤請和我們聯繫。
合作請加QQ:365242293
數據分析(ID : ecshujufenxi )網際網路科技與數據圈自己的微信,也是WeMedia自媒體聯盟成員之一,WeMedia聯盟覆蓋5000萬人群。