Deploying a machine learning model on the Web using Flask and Python.

Soumya Gupta
Analytics Vidhya
Published in
4 min readDec 2, 2019

--

Creating a machine learning model and doing predictions for real-world problems sounds cool. But, that’s not very useful for anyone other than the creator of the model since it’s only available on their machine.

In this post, we’ll go over how to use Flask, a microframework for building websites and APIs in Python, to build our Web API

Let’s start the process by building a simple Linear Regression model in Python

Step1. Importing all the necessary Libraries required for building a Linear Regression Model using Scikit Learn

Here I am using homeprices.csv file for training our model which has two features, area and house price.

Step2. Reading the data using pandas and defining our variables for training

Step3. Training our model

Step4. Calculating the score along with coefficients and doing prediction on a certain value of the area variable.

Now our simple linear regression model is ready, let’s go towards model persistence and save the above as .pkl file

Now our model is saved and can be reused by loading the same again anytime.

Let’s build a Web API using Flask and understand the process to achieve the same in a simple manner.

A Very Brief Introduction to Flask

If you downloaded the Anaconda distribution, you already have Flask installed, otherwise, you will have to install it yourself with — pip install flask.

Flask is very minimal since you only bring in the parts as you need them. To demonstrate this, here’s the Flask code to create a very simple web server.

from flask import Flaskapp = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run(debug=True)

Once executed, you can navigate to the web address, which is shown the terminal, and observe the expected result.

Let’s review what the executed code is doing.

After importing, we create an instance of the Flask class and pass in the __name__ variable that Python fills in for us. This variable will be "__main__", if this file is being directly run through Python as a script. If we import the file instead, the value of __name__ will be the name of the file where we did the import. For instance, if we had test.py and run.py, and we imported test.py into run.py the __name__ value of test.py will be test.

Above our hello method definition, there’s the @app.route("/") line. The @ denotes a decorator, which allows the function, property, or class it’s precedes to be dynamically altered.

The hello method is where we put the code to run whenever the route of our app or API hits the top level route: /.

If our __name__ variable is __main__, indicating that we ran the file directly instead of importing it, then it will start the Flask app which will run and wait for web requests until the process ends.

Creating the API

Prediction API

The prediction API is quite simple. We give it our data, the area of the house, and pass that into our predict method of our model.

There are quite a few things going on here, so let’s break it down.

Similar to the code above that introduced Flask, we’re calling the @app.route decorator.

In our route method definition, we restrict the request methods to be GET/POST and if so, we get the JSON of the request body so we can access its data. With that variable, we access the key of the data we want — area and parse it into a float. We also load our model into memory from the persisted file.

If there were no errors parsing the data then we pass the parsed variable into the predict method of our linear regression model; the variable was pulled into memory when we loaded our Flask app at startup. Next, we have to change the output of the predict method to a list since, without it, we’d get an error: Object of type 'ndarray' is not JSON serializable. We then call the [jsonify](http://flask.pocoo.org/docs/0.12/api/#flask.json.jsonify) method of Flask to send the response data as JSON.

Now we can run our API (in PyCharm you can just right-click anywhere in the script and click “Run”). With our API running we can execute thecode to call it.

Finally, we can see the output on our terminal.

In this post, we learned what Flask is, how to use it to create APIs, and most importantly how to apply this knowledge to create APIs for interacting with machine learning models.

I hope you found this tutorial useful, Thank you for reading till here. I’m curious about what you think so hit me with some comments.
You can also get in touch with me directly through email.

--

--