Building an API to predict the real estate price using the saved model

Now that we have seen how  Flask works, we need to implement an API to serve the model we built previously. Start a new Jupyter Notebook and follow these steps:

  1. Import the required Python modules and create a Flask app instance:
from flask import Flask, request 
from keras.models import load_model
from keras import backend as K

import numpy
app = Flask(__name__)
  1. Create Index page for the RESTful API using the route() decorator:
@app.route('/') 
def hello_world():
return 'Index page'
  1. Create a POST API to predict house price using the route() decorator. This accepts a JSON object with all the features required to predict the house or real estate price:
@app.route('/predict', methods=['POST']) 
def add():
req_data = request.get_json()
bizprop = req_data['bizprop']
rooms = req_data['rooms']
age = req_data['age']
highways = req_data['highways']
tax = req_data['tax']
ptratio = req_data['ptratio']
lstat = req_data['lstat']
# This is where we load the actual saved model into new variable.
deep_and_wide_net = load_model('deep_and_wide_net.h5')
# Now we can use this to predict on new data
value = deep_and_wide_net.predict_on_batch(numpy.array([[bizprop, rooms, age , highways , tax , ptratio , lstat]], dtype=float))
K.clear_session()

return str(value)

Save the Python notebook and use the File menu to download the notebook as a Python file. Place the Python file in the same directory as the model file.

Start a new command terminal and traverse to the folder with this Python file and the model. Make sure to activate the conda environment and run the following to start a server that runs the simple API:

  • If you are using Windows, enter the following:
set FLASK_APP=predict_api
  • If you aren't using Windows, use this:
export FLASK_APP= predict_api

Then type the following:

flask run

Next, we will use curl to access the POST API that predicts house prices. Open a new terminal and enter the following curl command to test the /predict API. We can pass the features to be used as input for the model as a JSON object:

curl -i -X POST -H "Content-Type: application/json" -d "{"bizprop":"1","rooms":"2","age":"1","highways":"1","tax":"1","ptratio":"1","lstat":"1"}" http://127.0.0.1:5000/predict

This will output the house price for the features provided using our prediction model:

That's it! We just built an API to serve our prediction model and tested it using curl. The complete code for the prediction API is available as a Python notebook named predict_api.ipynb and as a Python file named simple_api.py.

Next, we are going to see how to make a mobile app that will use the API that hosts our model. We will start by creating an Android app that uses the prediction API and then repeat the same task on an iOS app.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset