自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何使用Flask輕松部署機器學習模型?

譯文
人工智能 機器學習
本文旨在讓你開始使用Flask API將經(jīng)過訓練的機器學習模型部署到生產(chǎn)環(huán)境。

如何使用Flask輕松部署機器學習模型?

【51CTO.com快譯】數(shù)據(jù)科學家/機器學習工程師使用Scikit-Learn、TensorFlow、Keras或PyTorch等開發(fā)機器學習模型時,最終目標是將其部署到生產(chǎn)環(huán)境。從事機器學習項目時,我們常常過于關注探索性數(shù)據(jù)分析(EDA)、特征工程和超參數(shù)調(diào)整等,卻往往忘了主要目標:從模型預測中提取實際價值。

部署機器學習模型或?qū)⒛P筒渴鸬缴a(chǎn)環(huán)境意味著將模型提供給最終用戶或系統(tǒng)。然而,部署機器學習模型存在復雜性。本文旨在讓你開始使用Flask API將經(jīng)過訓練的機器學習模型部署到生產(chǎn)環(huán)境。

我將利用線性回歸,使用利率和前兩個月的銷售額來預測第三個月的銷售額。

什么是線性回歸?

線性回歸模型的目的是找到一個或多個特征(獨立變量)與連續(xù)目標變量(獨立變量)之間的關系。如果只有特征,名為單變量線性回歸;如果有多個特征,名為多變量線性回歸。

線性回歸假設

線性回歸模型可用下列方程式加以表示:

  • Y是預測值
  • θ₀是偏項。
  • θ₁,…,θn是模型參數(shù)
  • x 1,x 2,…,x n是特征值。

圖1. 線性回歸圖解

為什么使用Flask?

  • 易于使用。
  • 內(nèi)置的開發(fā)服務器和調(diào)試器。
  • 集成的單元測試支持。
  • 充分利用REST的請求分派。
  • 豐富的說明文檔。

項目結構

該項目有四個部分:

  1. model.py——這包含機器學習模型基于頭兩個月的銷售額預測第三個月銷售額的代碼。
  2. app.py——這包含通過GUI或API調(diào)用接收銷售明細,基于我們的模型計算預測值并返回的Flask API。
  3. request.py —這使用請求模塊來調(diào)用app.py中定義的API,并顯示返回值。
  4. HTML/CSS——這包含讓用戶可以輸入銷售明細并顯示第三個月預測銷售額的HTML模板和CSS樣式。

圖2. 部署機器學習模型的管道

環(huán)境和工具

  1. scikit-learn
  2. pandas
  3. numpy
  4. flask

代碼在哪里?

不妨先從代碼開始入手。Github上的整個項目可以在這里(https://github.com/abhinavsagar/Machine-Learning-Deployment-Tutorials)找到。

先從使用HTML構建前端以便用戶輸入值入手。用戶需要填三個字段:利率、第一個月的銷售額和第二個月的銷售額。

  1. <!DOCTYPE html> 
  2. <html > 
  3. <head> 
  4.   <meta charset="UTF-8"
  5.   <title>Deployment Tutorial 1</title> 
  6.   <link href='https://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'
  7. <link href='https://fonts.googleapis.com/css?family=Arimo' rel='stylesheet' type='text/css'
  8. <link href='https://fonts.googleapis.com/css?family=Hind:300' rel='stylesheet' type='text/css'
  9. <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'
  10. <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}"
  11.    
  12. </head> 
  13.  
  14. <body style="background: #000;"
  15.  <div class="login"
  16.     <h1>Sales Forecasting</h1> 
  17.  
  18.      <!-- Main Input For Receiving Query to our ML --> 
  19.     <form action="{{ url_for('predict')}}"method="post"
  20.         <input type="text" name="rate" placeholder="rate" required="required" /> 
  21.         <input type="text" name="sales in first month" placeholder="sales in first month" required="required" /> 
  22.         <input type="text" name="sales in second month" placeholder="sales in second month" required="required" /> 
  23.         <button type="submit" class="btn btn-primary btn-block btn-large">Predict sales in third month</button> 
  24.     </form> 
  25.  
  26.    <br> 
  27.    <br> 
  28.    {{ prediction_text }} 
  29.  
  30.  </div> 
  31. </body> 
  32. </html>  

接下來我使用CSS,為輸入按鈕、登錄按鈕和背景構建一些樣式。

  1.     @import url(https://fonts.googleapis.com/css?family=Open+Sans); 
  2.      
  3.     html { width: 100%; height:100%; overflow:hidden; } 
  4.      
  5.     body {  
  6.         width: 100%; 
  7.         height:100%; 
  8.         font-family: 'Helvetica'
  9.         background: #000; 
  10.         color: #fff; 
  11.         font-size: 24px; 
  12.         text-align:center; 
  13.         letter-spacing:1.4px; 
  14.      
  15.     } 
  16.     .login {  
  17.         position: absolute
  18.         top: 40%; 
  19.         left: 50%; 
  20.         margin: -150px 0 0 -150px; 
  21.         width:400px; 
  22.         height:400px; 
  23.     } 
  24.      
  25.     .login h1 { color: #fff; text-shadow: 0 0 10px rgba(0,0,0,0.3); letter-spacing:1px; text-align:center; } 
  26.      
  27.     input {  
  28.         width: 100%;  
  29.         margin-bottom: 10px;  
  30.         background: rgba(0,0,0,0.3); 
  31.         border: none; 
  32.         outline: none; 
  33.         padding: 10px; 
  34.         font-size: 13px; 
  35.         color: #fff; 
  36.         text-shadow: 1px 1px 1px rgba(0,0,0,0.3); 
  37.         border: 1px solid rgba(0,0,0,0.3); 
  38.         border-radius: 4px; 
  39.         box-shadow: inset 0 -5px 45px rgba(100,100,100,0.2), 0 1px 1px rgba(255,255,255,0.2); 
  40.         -webkit-transition: box-shadow .5s ease; 
  41.         -moz-transition: box-shadow .5s ease; 
  42.         -o-transition: box-shadow .5s ease; 
  43.         -ms-transition: box-shadow .5s ease; 
  44.         transition: box-shadow .5s ease; 
  45.     } 
  46. view rawstyle.css hosted with ❤ by GitHub 
  47.  

我為這個項目創(chuàng)建了自定義銷售數(shù)據(jù)集,它有四列:利率、第一個月的銷售額、第二個月的銷售額和第三個月的銷售額。 

 

rate

sales_in_first_month

sales_in_second_month

sales_in_third_month

   

2

500

300

   

4

300

650

 

four

600

200

400

 

nine

450

320

650

 

seven

600

250

350

 

five

550

200

700

view rawsales.csv hosted with by GitHub

現(xiàn)在,不妨構建一個機器學習模型來預測第三個月的銷售額。首先,不妨使用Pandas處理缺失的值。如果沒有為一個或多個項提供任何信息,數(shù)據(jù)會丟失。如果未提供值,我將在利率這列填充零,將在第一個月的銷售額這列填充該列的平均值。我使用線性回歸作為機器學習算法。

序列化/反序列化

簡而言之,序列化是一種在磁盤上寫入Python對象(對象可以傳輸?shù)饺魏蔚胤?,以后由Python腳本反序列化(讀回)的方法。

圖3. 序列化和反序列化

我使用pickling將Python對象這種形式的模型轉(zhuǎn)換成字符流。其想法是,該字符流含有用另一個Python腳本重新構建對象必需的所有信息。

  1.     import numpy as np 
  2.     import matplotlib.pyplot as plt 
  3.     import pandas as pd 
  4.     import pickle 
  5.      
  6.     dataset = pd.read_csv('sales.csv'
  7.      
  8.     dataset['rate'].fillna(0, inplace=True
  9.      
  10.     dataset['sales_in_first_month'].fillna(dataset['sales_in_first_month'].mean(), inplace=True
  11.      
  12.     X = dataset.iloc[:, :3] 
  13.      
  14.     def convert_to_int(word): 
  15.         word_dict = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 
  16.                     'nine':9, 'ten':10, 'eleven':11, 'twelve':12, 'zero':0, 0: 0} 
  17.         return word_dict[word] 
  18.      
  19.     X['rate'] = X['rate'].apply(lambda x : convert_to_int(x)) 
  20.      
  21.     y = dataset.iloc[:, -1] 
  22.      
  23.     from sklearn.linear_model import LinearRegression 
  24.     regressor = LinearRegression() 
  25.      
  26.     regressor.fit(X, y) 
  27.      
  28.     pickle.dump(regressor, open('model.pkl','wb')) 
  29.      
  30.     model = pickle.load(open('model.pkl','rb')) 
  31.     print(model.predict([[4, 300, 500]])) 
  32. view rawmodel.py hosted with ❤ by GitHub  

下一個部分是構建這樣一個API:通過GUI收到銷售明細后,基于我們的模型來計算預測的銷售額。為此,我反序列了Python對象這種形式的pickled模型。我使用index.html設置主頁面。一旦使用POST將表單值提交給/predict,我們就獲得了預測銷售額。

只要對/results提出另一個POST請求,即可顯示結果。它收到JSON輸入,使用經(jīng)過訓練的模型來進行預測,并返回使用JSON格式的該預測,它可通過API端點來訪問。

  1. import numpy as np 
  2. from flask import Flask, request, jsonify, render_template 
  3. import pickle 
  4.  
  5. app = Flask(__name__) 
  6. model = pickle.load(open('model.pkl''rb')) 
  7.  
  8. @app.route('/'
  9. def home(): 
  10.     return render_template('index.html'
  11.  
  12. @app.route('/predict',methods=['POST']) 
  13. def predict(): 
  14.  
  15.     int_features = [int(x) for x in request.form.values()] 
  16.     final_features = [np.array(int_features)] 
  17.     prediction = model.predict(final_features) 
  18.  
  19.     output = round(prediction[0], 2) 
  20.  
  21.     return render_template('index.html', prediction_text='Sales should be $ {}'.format(output)) 
  22.  
  23. @app.route('/results',methods=['POST']) 
  24. def results(): 
  25.  
  26.     data = request.get_json(force=True
  27.     prediction = model.predict([np.array(list(data.values()))]) 
  28.  
  29.     output = prediction[0] 
  30.     return jsonify(output
  31.  
  32. if __name__ == "__main__"
  33.     app.run(debug=True
  34. view rawapp.py hosted with ❤ by GitHub  

最后,我使用請求模塊來調(diào)用app.py中定義的APP。它顯示了第三個月的返回銷售額。

  1. import requests  
  2. url = 'http://localhost:5000/results'  
  3. r = requests.post(url,json={'rate':5, 'sales_in_first_month':200, 'sales_in_second_month':400})  
  4. print(r.json())  
  5. view rawrequest.py hosted with ❤ by GitHub  

結果

使用該命令運行這個Web應用程序。

  1. $ python app.py 

圖4

在Web瀏覽器中打開http://127.0.0.1:5000/,應該會出現(xiàn)如下所示的GUI。

圖5. 圖形用戶界面

結束語

本文演示了部署機器學習模型的一個很簡單的方法。我利用線性回歸,使用利率和前兩個月的銷售額來預測第三個月的銷售額。你可以利用本文中學到的知識構建一些很酷的模型,并將它們部署到生產(chǎn)環(huán)境中,以便別人享受到成果。

原文標題:How to Easily Deploy Machine Learning Models Using Flask,作者:Abhinav Sagar

【51CTO譯稿,合作站點轉(zhuǎn)載請注明原文譯者和出處為51CTO.com】

 

責任編輯:龐桂玉 來源: 51CTO
相關推薦

2024-09-09 11:45:15

ONNX部署模型

2024-10-12 08:00:00

機器學習Docker

2023-02-07 16:36:34

機器學習Docker無服務器

2021-01-25 09:00:00

機器學習人工智能算法

2020-12-31 08:00:00

機器學習人工智能工程師

2017-07-07 14:41:13

機器學習神經(jīng)網(wǎng)絡JavaScript

2021-11-02 09:40:50

TensorFlow機器學習人工智能

2019-08-08 08:00:00

深度學習機器學習神經(jīng)網(wǎng)絡

2025-02-17 08:00:00

機器學習開發(fā)Docker

2022-03-28 18:59:02

DockerFlask深度學習

2017-10-23 15:46:37

2024-02-20 15:17:35

機器學習模型部署

2022-09-07 08:00:00

機器學習MLFlow工具

2020-07-10 10:39:04

Python開發(fā)工具

2018-01-08 09:09:46

機器學習模型NET

2018-11-07 09:00:00

機器學習模型Amazon Sage

2017-03-24 15:58:46

互聯(lián)網(wǎng)

2017-07-13 10:12:58

機器學習

2020-09-22 14:59:52

機器學習人工智能計算機

2022-06-02 15:42:05

Python機器學習
點贊
收藏

51CTO技術棧公眾號