如何部署 ML 训练模型?

时间:2021-08-01 02:01:03

标签: python html machine-learning flask

我正在从事一个机器学习项目信用卡欺诈检测。我已经使用随机森林分类器训练了模型。本项目中使用的 dataset 取自 Kaggle。它包含 31 个特征,最后一个特征用于对交易是否欺诈进行分类。现在我想使用 Flask 部署模型。为此,我正在关注 this 教程。但不是在输入字段中输入数据,我希望用户上传带有单个记录的 CSV 文件。那么,应该在代码中进行哪些更改?

app.py

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)
# prediction function 
def ValuePredictor(to_predict_list): 
    to_predict = np.array(to_predict_list).reshape(1, 30) 
    loaded_model = pickle.load(open("model.pkl", "rb")) 
    result = loaded_model.predict(to_predict) 
    return result[0]     
    
@app.route('/')
def home():
    return render_template("index.html")

@app.route('/predict',methods=['POST','GET'])
def predict():
    if request.method == 'POST':
        to_predict_list = request.form.to_dict() 
        to_predict_list = list(to_predict_list.values()) 
        to_predict_list = list(map(float, to_predict_list))
        result = ValuePredictor(to_predict_list)
    if int(result)== 1:
        prediction ='Given transaction is fradulent'
    else:
        prediction ='Given transaction is NOT fradulent'            
    return render_template("index.html", prediction_text = prediction_text) 
    
if __name__ == "__main__":
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html >
<!--From https://codepen.io/frytyler/pen/EGdtg-->
<head>
  <meta charset="UTF-8">
  <title>ML API</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>
 <div class="login">
    <h1>Credit Card Fraud Detection</h1>

     <!-- Main Input For Receiving Query to our ML -->
    <form action="{{ url_for('predict')}}"method="post">
        <label for="file">Choose file to upload</label>
    <input type="file" name="file" accept=".csv">
        
    <button type="submit" class="btn btn-primary btn-block btn-large">Predict</button>
    </form>

   <br>
   <br>
   {{ prediction_text }}

 </div>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

请参考: https://python-bloggers.com/2021/01/practical-guide-build-and-deploy-a-machine-learning-web-app/ 这是创建网络应用的指南,该应用将 CSV 文件作为输入并返回带有预测的 CSV 文件。