Complete Machine Learning solution(Part 1|3): Create Flask Application

Complete Machine Learning solution(Part 1|3): Create Flask ApplicationAmardeep ChauhanBlockedUnblockFollowFollowingJan 29Source — https://hackersandslackers.

com/tag/flask/While learning Machine Learning I used to practice on Python Notebook environment and always used to think about how can we make our solution usable by end-user.

Since I already have worked on Client/Server applications so I knew that, one way can be to implement our solution and build the model in such a way that we can make it usable via API calls and these APIs can be used by various user facing platforms.

This entire approach is know as API-First Approach.

I did some more research and learned about Python Virtual Environment and Package management and decided to come up with a complete solution covering from Python Virtual Environment setup to final deployment of the Flask application containing Machine Learning solution for a popular classification problem ‘Titanic Survival Prediction’.

Since this is going to be a complete solution and so many things will come in our way, so I am going to cover it in 3 blog posts explaining below operations in detail:Flask application CreationCreation and Management of Machine Learning Classification ModelDeployment of Flask Application on AWS Elastic BeanstalkIn this post, I will just talk about the Flask Virtual Environment setup and Flask application creation.

I have divide this post into further sub-parts:Python Virtual Environment SetupProject ArchitectureConfiguring Flask Server and API CreationPython Virtual Environment SetupIt must be clear from name Virtual Environment that its nothing but a separate custom Python environment where our application is going to live, means here we can maintain the package dependency irrespective of the system where our application is placed in.

If you have any Node.

js background like I have then you can think of it as a similar environment provided by Node Package Manager(NPM), we just have more control over here.

The good thing about Python’s Virtual Environment setup is that we have so many options available to perform this task, ranging from virtualenv, pipenv, venv to virtualenvwrapper.

I am going to prefer venv here, however you can check out below link for comparison and you can choose any other if you want as per requirement, it will take some different commands and way of setting up the virtual environment and once done you can catch up from Project Architecture section.

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?virtualenv is a very popular tool that creates isolated Python environments for Python libraries.

If you’re not…stackoverflow.

comAlso, note that I am using Windows 10 system with Python 3.

6, you may have to use different commands at some places if you are on Unix or MacOS.

 Steps to setup Virtual Environment using venv:python -m venv titanic-survival-complete-ml-solution && cd titanic-survival-complete-ml-solution — Create Virtual Environment.

Scriptsactivate.

bat — Activate script to use this environment.

Once activated you must see the application name in brackets before current directory path.

Now whenever you will run any pip command it will work specifically for this environment and whenever you want to quit this environment just use the command deactivate.

pip install dill Flask Jinja2 numpy pandas scikit-learn scipy sklearn xgboost — Install a few required packages that we will be using in our code.

Project ArchitectureIf you have done Virtual Environment setup successfully using venv then you must be having below file architecture.

├───Include├───Lib│ ├───site-packages│ │ ├───pip│ │ └ .

│ └───tcl8.

6├───Scripts└───pyvenv.

cfgOnce we are done with all implementation, our application architecture will look like:├───Data│ ├───test.

csv│ └───train.

csv├───Include├───Lib│ ├───site-packages│ │ ├───click│ │ ├───dateutil│ │ ├───dill│ │ ├───flask│ │ ├───itsdangerous│ │ ├───jinja2│ │ ├───markupsafe│ │ ├───numpy│ │ ├───pandas│ │ ├───pandas-0.

23.

4.

dist-info│ │ ├───pip│ │ ├───pkg_resources│ │ ├───pytz│ │ ├───scipy│ │ ├───werkzeug│ │ └───xgboost│ └───tcl8.

6├───Scripts├───Src│ ├───api│ │ └───predict.

py│ ├───ml-model│ │ └───voting_classifier_v1.

pk│ ├───notebook │ │ └───Titanic Survival Solution Notebook.

ipynb│ ├───templates│ │ └───index.

html│ └───utils│ ├───__init__.

py│ ├───ClassificationModelBuilder.

py│ └───DataPreparation.

py├───xgboost└───application.

pyWhere,Data — Will contain data-sets.

api — Will contain all the APIs we are going to have.

ml-model — Will contain the trained model instance.

notebook — Will contain the python notebook file containing the solution of our business problem.

templates — Will contain HTML template files that we want to have in our application.

utils — Will contain data-set pre-processing and ML classification model related code.

application.

py — Will contain Flask Server configuration and is the entry point of our application.

Configuring Flask Server and API CreationLet’s create /application.

py to configure our server.

application.

pyfrom flask import Flask, jsonify, request, render_template, abort# from Src.

utils import ClassificationModelBuilder # Uncomment only if you want to re-train your modelfrom Src.

api.

predict import predict_apifrom jinja2 import TemplateNotFoundapplication = Flask(__name__ , template_folder='.

/Src/templates')application.

register_blueprint(predict_api, url_prefix='/titanic-survival-classification-model')# Loading home page@application.

route('/', defaults={'page': 'index'})@application.

route('/<page>')def show(page):try: print('home route') return render_template(f'{page}.

html', app_name='Titanic Survival: Classification Problem')except TemplateNotFound: abort(404)# Handling 400 Error@application.

errorhandler(400)def bad_request(error=None): message = { 'status': 400, 'message': 'Bad Request: ' + request.

url + '–> Please check your data payload.

', } resp = jsonify(message) resp.

status_code = 400 return resp# run applicationif __name__ == "__main__": application.

run()In above code, we have configured Flask server and kept it’s instance in application variable, variable name should not differ otherwise you will face difficulty during deployment.

We have also configured our home page, so that at later stage, after deployment, we can cross-check if we are getting our welcome page or not.

Srcapipredict.

pyfrom flask import Blueprint, jsonify, requestpredict_api = Blueprint(“predict_api”, __name__)@predict_api.

route(‘/predict’, methods=[‘POST’])def apicall(): return (‘It works ;)’)In above code, we have created a route /predict using Flask Blueprint.

Blueprint provides a modular way of creating APIs.

For now this API returns a simple ‘It works ;)’ message, later we will append this code to utilize prepared model to make and return predictions.

Now run python application.

py after activating virtual environment and if everything you have done correctly then you should get a welcome page on localhost:5000/ and ‘It works ;)’ response while making POST request on localhost:5000/titanic-survival-classification-model/predict API.

Congrats, you have created the Flask application with basic code.

I will continue on same application and will explain about the Machine Learning model building and configurations in my next blog post.

Let me know if you face any issue or have any suggestions.

Thanks.

Happy Learning ;).

. More details

Leave a Reply