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.

120 lines
3.2 KiB

2 years ago
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"___\n",
"\n",
"<a href='http://www.pieriandata.com'><img src='../Pierian_Data_Logo.png'/></a>\n",
"___\n",
"<center><em>Copyright by Pierian Data Inc.</em></center>\n",
"<center><em>For more information, visit us at <a href='http://www.pieriandata.com'>www.pieriandata.com</a></em></center>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Serving a Model as an API\n",
"\n",
"**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.**\n",
"\n",
"\n",
"---\n",
"\n",
"**NOTE: You will need to install Flask to serve the API: https://flask.palletsprojects.com/en/2.0.x/installation/**\n",
"\n",
" pip install flask\n",
" \n",
" or\n",
" \n",
" conda install flask\n",
"\n",
"---\n",
"\n",
"\n",
"## api.py (Run this as a script as shown in the video, NOT from within a Jupyter Cell)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"############################\n",
"######## IMPORTS ##########\n",
"##########################\n",
"from flask import Flask, request, jsonify\n",
"import joblib\n",
"import pandas as pd\n",
"\n",
"# Create Flask App\n",
"app = Flask(__name__)\n",
"\n",
"\n",
"# Create API routing call\n",
"@app.route('/predict', methods=['POST'])\n",
"def predict():\n",
" \n",
" # Get JSON Request\n",
" feat_data = request.json\n",
" # Convert JSON request to Pandas DataFrame\n",
" df = pd.DataFrame(feat_data)\n",
" # Match Column Na,es\n",
" df = df.reindex(columns=col_names)\n",
" # Get prediction\n",
" prediction = list(model.predict(df))\n",
" # Return JSON version of Prediction\n",
" return jsonify({'prediction': str(prediction)})\n",
"\n",
" \n",
"\n",
"if __name__ == '__main__':\n",
"\n",
" # LOADS MODEL AND FEATURE COLUMNS\n",
" model = joblib.load(\"final_model.pkl\") \n",
" col_names = joblib.load(\"column_names.pkl\") \n",
"\n",
" app.run(debug=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# JSON Post Request\n",
"\n",
"1. POST to: http://127.0.0.1:5000/predict\n",
"2. Select Body\n",
"3. Select Raw\n",
"4. Select JSON(application/json)\n",
"5. Supply JSON for Features:\n",
" [{\"TV\":230.1,\"radio\":37.8,\"newspaper\":69.2}]\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}