用機器學習分析韓國流行音樂 4 - 生產模型

注:你可以在文末找到指向整個 GitHub 倉庫的鏈接。

在本教程中,我將向你展示如何將模型投入生產環境中(即模型部署)。

什麼是模型部署?模型部署就是將機器學習模型集成到現有的生產環境中,以便基於數據做出實際的業務決策。

我們將使用帶有 FLASK 的 Python web API 來部署模型。因此,我們的最終目標是創建一個網站,一旦用戶在網站上輸入值,該網站就會給你預測的結果。

從 GitHub 下載我的文件

首先,到我的 GitHub 頁面上的 K-pop 倉庫下載模型部署文件夾

我們將使用名爲 GitZip 的網站,它可以讓你下載 repo 中的特定文件夾。你所需要做的就是將連接複製並粘貼到我的模型部署文件夾。

複製並在此處粘貼我的文件夾鏈接

你可以隨意命名文件夾。我將文件夾命名爲“K-pop Model Deployment”。

使用 Spyder IDE

在本教程中,我們將使用 Spyder IDE。

如果你還沒有安裝 Spyder IDE 的話,可以從這裏下載(你需要從 Anaconda 網站下載),請務必下載版本 7.3,因爲這是最新版本。

安裝 Anaconda(Python 3.7)

安裝後,打開 Spyder IDE,導航到“File Explorer”,然後選擇剛剛下載的文件夾。

在 templates 文件夾下打開 app.py、k_pop_model_building.py 和 index.html。

Spyder 中的 File Explorer

只選擇連續變量

在上一部教程中,我們使用了 .pd.get_dummies(df_model) 將類別變量轉換爲虛擬變量/指標變量。我意識到,這樣做會產生太多額外變量,我認爲這樣對用戶不太友好(我們並不希望用戶輸入 73 個答案)。因此,我們只選擇連續變量,這樣,用戶只需輸入 5 個變量(“yr_listened”、“daily_MV_hr”、“yr_merch_spent”、“age”、“num_gr_like”)即可預測他們每天聽歌的小時數:“daily_music_hr”。

df_real = df[[“yr_listened”, “daily_music_hr”, “daily_MV_hr”,
              “yr_merch_spent”, “age”, “num_gr_like”]]

然後,進行訓練並在此測試分離。

from sklearn.model_selection import train_test_split
X = df_real.drop('daily_music_hr', axis = 1)
y = df_real.daily_music_hr.values
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                   test_size = 0.2,
                                   random_state = 1)

運行 XGBoost 模型

在上一部教程中,我們看到,XGBoost 模型是最好的一個。因此,我們將部署這個模型。

import xgboost as xgb
# initialize the linear regression model
xgb_clf = xgb.sklearn.XGBClassifier(nthread = -1, seed = 1)
# train the model
xgb_clf.fit(X_train, y_train)
# Tune XGBoost using GridSearchCV
from sklearn.model_selection import GridSearchCV
params = {'min_child_weight': [5], 'gamma': [1],
          'subsample': [0.8, 1.0],
          'colsample_bytree': [0.6, 0.8],
          'max_depth': [1,2]}
gs_xgb = GridSearchCV(xgb_clf, params ,
                      scoring = 'neg_mean_absolute_error',
                      cv = 10)
gs_xgb.fit(X_train, y_train)
gs_xgb.best_score_
xgb_best = gs_xgb.best_estimator_
xgb_best
xgb_best.fit(X_train, y_train)

保存訓練模型

我們可以使用 pickle 將經過訓練的模型保存到磁盤中。然後,它在以後重新加載後,可以完全使用,就像我們已經訓練過它一樣。

# save the model to disk
with open('model.pkl', 'wb') as file:
    pickle.dump(xgb_best, file)

使用 FLASK 創建 Web 應用程序

首先,我們需要這兩樣東西來創建一個 Web 應用程序。

  1. Pythono 腳本將加載經過訓練的模型,要求用戶將輸入值放到網站上,執行預測,並返回結果。
  2. HTML 模板,即網站的格式。這將允許用戶輸入他們的數據並顯示結果。

結構如下所示:

web app/
├── model/
│ └── model.pkl — trained model
├── templates/
│ └── index.html — format of the website
└── app.py — to host the model

創建 app.py 以託管模型

app.py 將成爲 Web 應用程序的基礎。它將發送網頁,從用戶哪裏獲取數據來執行預測。

# use flask to host the model
import flask
import pickle
import pandas as pd
# Use pickle to load in the pre-trained model
with open(f'model.pkl', 'rb') as f:
    model = pickle.load(f)
# initialize the flask app
app = flask.Flask(__name__, template_folder='templates')
# set up the main route
@app.route('/', methods=['GET', 'POST'])
def main():
    if flask.request.method == 'GET':
        # rendering the initial form, to get input
        return(flask.render_template('index.html'))

    if flask.request.method == 'POST':
        # extracting the input values
        yr_listened = flask.request.form['yr_listened']
        daily_MV_hr = flask.request.form['daily_MV_hr']
        yr_merch_spent = flask.request.form['yr_merch_spent']
        age = flask.request.form['age']
        num_gr_like = flask.request.form['num_gr_like']

        # making dataframe for model
        input_variables = pd.DataFrame([[yr_listened, daily_MV_hr, yr_merch_spent, age, num_gr_like]],
                                       columns=['yr_listened', 'daily_MV_hr', 'yr_merch_spent', 'age', 'num_gr_like'],
                                       dtype=float,
                                       index=['input'])

        # get the model's prediction
        prediction = model.predict(input_variables)[0]
        output = float(round(prediction, 2))

        # render the form again, but add in the prediction and remind user of the values they input before
        return flask.render_template('index.html',
                                     original_input={'yr_listened':yr_listened,
                                                     'daily_MV_hr':daily_MV_hr,
                                                     'yr_merch_spent':yr_merch_spent,
                                                     'age':age,
                                                     'num_gr_like':num_gr_like},
                                     result=float(output)
                                     )

if __name__ == "__main__":
    app.run(debug=True)

創建 index.html 對網站進行格式化

這是該項目的前端部分。它要求用戶輸入值,執行預測並給出輸出結果。這是一種非常基本的樣式。我當時試着用 CSS,但無法真正讓它工作起來。如果你熟悉 CSS 或者想使用樣式,請隨意使用。

<!doctype html>
<html>
<style>
form {
    margin: auto;
    width: 35%;
}
.result {
    margin: auto;
    width: 35%;
    border: 1px solid #ccc;
}
</style>
<head>
    <title>Predicting Daily K-Pop Listening Hours</title>
</head>
<form action="{{ url_for('main') }}" method="POST">
    <fieldset>
        <legend>Input values:</legend>
        Number of years you listened to K-Pop:
        <input name="yr_listened" type="number" step=".01" required>
        <br>
        <br> Number of hours you watch K-Pop MV per day:
        <input name="daily_MV_hr" type="number" step=".01" required>
        <br>
        <br> How much money you spend on K-Pop merchandise a year:
        <input name="yr_merch_spent" type="number" step=".01" required>
        <br>
        <br> Your age:
        <input name="age" type="number" step=".01" required>
        <br>
        <br> Number of groups you like:
        <input name="num_gr_like" type="number" step=".01" required>
        <button type="submit" class="btn btn-primary btn-block btn-large">Predict!</button>
    </fieldset>
</form>
<br>
<div class="result" align="center">
    {% if result %}
     {% for variable, value in original_input.items() %}
      <b>{{ variable }}</b> : {{ value }}
     {% endfor %}
  <br>
     <br> Predicted Daily K-Pop Listening Hours:
     <p style="font-size:50px" step=".01">{{ result }}</p>
    {% endif %}
</div>
</html>

運行 Web 應用程序

現在,我們終於可以進行測試了,看看是否一切都按照我們設想的方式運行。

  1. 轉到 Anaconda 提示符。
  2. 將目錄切換到你的工作文件夾(即 cd Desktop → cd k-pop Model Deployment)。
  3. 運行 app.py(即 python app.py)
  4. 將獲得的鏈接複製並粘貼到瀏覽器。
  5. 輸入值並檢查它給出了預測結果。

Anaconda 提示符命令示例:

cd Desktop
cd K-Pop Model Deployment
python app.py

我們完成了!希望這篇教程對你有所啓發!

在下一個教程中,我將想你展示如何通過創建一個組合網站來記錄這個項目!敬請關注。

我的 GitHub 倉庫這裏

作者介紹

Jaemin Lee,專攻數據分析與數據科學,數據科學應屆畢業生。

原文鏈接

https://towardsdatascience.com/analyzing-k-pop-using-machine-learning-part-4-productionizing-the-model-model-deployment-a9fc2e703d95

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章