You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3.2 KiB

<html> <head> </head>

___

Copyright by Pierian Data Inc. For more information, visit us at www.pieriandata.com

Serving a Model as an API

NOTE: While we show this inside a Jupyter Notebook, you would probably never deploy something as a notebook in a real-world setting. Everything here is in one cell to reflect that this should be a .py file. We also included a duplicate .py file in this folder.


NOTE: You will need to install Flask to serve the API: https://flask.palletsprojects.com/en/2.0.x/installation/

pip install flask

or

conda install flask


api.py (Run this as a script as shown in the video, NOT from within a Jupyter Cell)

In [ ]:
############################
######## IMPORTS ##########
##########################
from flask import Flask, request, jsonify
import joblib
import pandas as pd

# Create Flask App
app = Flask(__name__)


# Create API routing call
@app.route('/predict', methods=['POST'])
def predict():
    
    # Get JSON Request
    feat_data = request.json
    # Convert JSON request to Pandas DataFrame
    df = pd.DataFrame(feat_data)
    # Match Column Na,es
    df = df.reindex(columns=col_names)
    # Get prediction
    prediction = list(model.predict(df))
    # Return JSON version of Prediction
    return jsonify({'prediction': str(prediction)})

        

if __name__ == '__main__':

    # LOADS MODEL AND FEATURE COLUMNS
    model = joblib.load("final_model.pkl") 
    col_names = joblib.load("column_names.pkl") 

    app.run(debug=True)

JSON Post Request

  1. POST to: http://127.0.0.1:5000/predict
  2. Select Body
  3. Select Raw
  4. Select JSON(application/json)
  5. Supply JSON for Features: [{"TV":230.1,"radio":37.8,"newspaper":69.2}]
</html>