Model Deployment
Creating a Flask Application/ API
Learning Objectives
API
Creating an API from a machine learning model using Flask
Flask
HTTP Methods
JSON and jsonify
Testing your API in Postman
You might be thinking
Now that I have built the ML model and saved it, I should be able to deploy it directly.
Well, not really.
Think about how an investor or a non data science person will be able to use your model. Will she/he be able to load it and run it?
What you’ll do in such a case is create a simple interface (possibly a web application) for the person to interact.
There are several things we need to put together for the web app.
The first two are:
Let’s get started with the 1st one in this unit.
Breaking down the whole application
In simple words, an API is a (hypothetical) contract between 2 softwares saying if the user software provides input in a pre-defined format, the latter will extend its functionality and provide the outcome to the user software.
A majority of the cloud providers, and smaller machine learning focused companies provide ready-to-use APIs. They cater to the needs of developers/businesses that do not have expertise in ML, who want to implement ML in their processes or product suites.
Google Vision API is an excellent example which provides dedicated services for Computer Vision tasks.
What are APIs?
Now, you might think what is a web service?
Web service is a form of API only that assumes that an API is hosted over a server and can be consumed.
Web API, Web Service - these terms are generally used interchangeably.
Web Service/API
Coming to Flask, it is a web service development framework or a micro-framework built in Python, which means it provides various tools and libraries for building web applications.
It is not the only one in Python, there are couple others as well such as Django, Falcon, Hug, etc.
Flask is very minimal and easy to learn and start working with—as long as you understand Python.
Flask - A web services' framework in Python
Basic benefits:
Advance benefits:
It’s okay if you don’t understand some of the terms above. You’ll appreciate Flask as you use it.
Why Flask
Pipeline for deployment of a Machine Learning model
You can download Sublime from here.
Some points to be noted
If you downloaded the Anaconda distribution, you already have Flask installed. Otherwise, you will have to install it yourself with:
Installing Flask
For serving your model with Flask, you will do the following two things:
Creating an API from a machine learning model using Flask
A Flask application is nothing but a Python file (a file saved with .py extension) that utilises Flask.
The basic template of any Flask file is like:
Let’s get started
In order to test Flask installation, type the following code in the editor and save it as ‘app.py’. Note that the underscores being used are double underscores and not single.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!’
if __name__ == '__main__':
app.run(debug=True)
For running the file, if you’re in sublime, you can simply do Ctrl+B.
Otherwise, you can type python app.py or flask run in the terminal.
Let’s get started
You will see an output like this:
Copy the link displayed and paste it in your browser. (The default port will be 5000 unless you specify it otherwise).
Let’s get started
And you’ll be able to see this on the link:
Did we just create a basic functioning website? Yes we did!!
If you want the website to stop running, you can press Ctrl+C in the terminal or simply close the window.
Let’s get started
Let’s understand the components of our Flask application briefly. We don’t need to go into much detail at the moment.
It has the syntax:
app.route(rule, options)
In our example, ‘/’ URL is bound with hello_world() function. Hence, when the home page of web server is opened in browser, the output of this function will be rendered(displayed).
Understanding the code
For understanding how route triggers different functions on different URLs, let’s take the example of the DPhi website.
@app.route('/')
def home():
@app.route('/learn')
def learn():
Similarly, many other routes can be defined. These are also called endpoints.
Did you get it now how different routes can perform different tasks?
Understanding the code
Its syntax is as follows:
app.run(host, port, debug, options)
All parameters are optional
A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application.
The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.
app.run(debug=True)
Understanding the code
HTTP Methods
HTTP protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol.
The following table summarizes different HTTP methods −
HTTP Methods
In short, when a user loads your website, a GET request will occur. Whereas, when a user submits some input to get a predicted output, POST request will occur.
The default request Flask responds to is GET request. However, this preference can be altered by providing methods argument to route().
JSON and Jsonify
Remember that we learned about JSON in one of our previous units? Python supports JSON through a built-in package called json.
flask.request.form
In any web app, you’ll have to process incoming request data from users. Flask, like any other web framework, allows you to access the request data easily.
Flask extracts the data from the form with the flask.request.form functionality, which works like a dictionary. We can grab the data we want from the form by referring it to the name. This name will be set in our HTML template, later on.
Testing your API in Postman
In order to test your API, you will need some kind of API client.
Postman is undoubtedly one of the best ones out there. You can easily download Postman from here. This is how the Postman application will look like:
Testing your API in Postman
In order to start providing input in the form of GET or POST request, you need to click on ‘Create a request’ under the “Start something new” section.
The most basic structure of a Flask app looks like this:
webapp/
├── model/
│ └── saved_model.pkl
├── templates/
│ └── index.html
└── app.py
Basic Structure of a Flask web app
The structure of all the files that’ll be used in creating the application for predicting Bengaluru’s Home Prices will be somewhat like this:
webapp/
├── server/
│ ├── artifacts/
│ │ ├── banglore_home_prices_model.pickle
│ │ └── columns.json
│ ├── server.py
│ └── util.py
├── client/
│ ├── app.html
│ ├── app.css
│ └── app.js
└── model/
└── model.ipynb
Creating the model folder is completely optional as that won’t be required in your application. We’ll mainly be working with the server folder in this unit.
Artifacts are nothing but the model you saved as a pickle and the column names you saved as a json file.
The directory structure
Writing the main logic
We now know how to create a basic Flask app now and have some knowledge about HTTP Methods. We are also equipped with Postman - a tool that’ll help us test the API we create.
Now, you’ll be completely able to follow along the next video that covers writing the actual Python code that will load our model, get user input from a web form, do predictions and return results. You’ll even be testing that out with Postman.
Unless you do it along and create the website on your own, you won’t be able to understand it properly. If you get stuck anywhere, we are there to help you out.
You can find all the files created and used in the tutorial here:
https://github.com/dphi-official/Micro-Courses/tree/master/Introduction_Model_Deployment/server
Writing the main logic
The functions in util.py can also be incorporated inside server.py itself. A separate file was created just to make things more organised.
Okay, so what does our API do?
Writing the main logic
Note: You always need to pre-process any input data in the same way you processed your training data.
That is, if you performed scaling on the train data, make sure you scale the inputs as well.
Writing the main logic
Congratulations! You just built your first ever machine learning API.
Your API can predict the price of a house in Bengaluru given their total square feet area, location, bhk and no. of bathrooms.
Next, you’ll call it from your front-end code and process the output of the API into something fascinating.
References
Slide Download Link
You can download this unit from the below link:
https://docs.google.com/presentation/d/1QdT83slDrJM__SB7IYUmwi6BfGQMKsjIA7_k5bbAn4I/edit?usp=sharing
That’s it for this unit. Thank you!
Feel free to post any queries on Discuss.