Flask — Host Your Python Machine Learning Model On Web

Flask — Host Your Python Machine Learning Model On WebLearn How To Make A Business Out Of Your Machine Learning Model Using Python FlaskFarhad MalikBlockedUnblockFollowFollowingJun 5Once your machine learning model is predicting accurate results, you can expose it to the outside world.

This article presents the easy-to-follow steps which we can follow to host a machine learning model to the outside world.

Public can then access your work via their web browsers.

It is an important step for anyone who wants to make a business out of their machine learning models.

We are going to use the Flask web micro-framework.

Once we have trained a machine learning model, we can easily create a web application and host it to the outside world and let the model start forecasting for wider audience.

Please read FinTechExplained disclaimer.

Photo by Elijah Hiett on UnsplashBefore We Begin, Let’s Understand Flask QuicklyWhat Is Flask?Flask is a web micro-framework developed by Armin Ronacher.

Flask is written in Python programming language.

Flask is made for Python applications.

Flask helps in implementing a machine learning application in Python that can be easily plugged, extended and deployed as a web application.

Flask is based on two key components: WSGI toolkit and Jinja2 template engine.

WSGI is a specification for web applications and Jinja2 renders web pages.

Linkedin, Pinterest use the Flask framework.

Flask Provides A Glue Layer To Your Python ApplicationThink of Flask as a collection of software packages which can help you easily create a web application.

These components can be assembled and further extended.

Flask makes it easier for embedding an existing Python applicationFlask ExtensionsFlask offers a range of extensions for:Object relation mappingUploading filesAuthenticationForms validationMail, SQLAlchemy, jquery integration.

Photo by Serghei Trofimov on UnsplashIf you are new to Python programming language, then read this article.

It explains everything you need to know about Python:Everything About Python — Beginner To AdvancedEverything You Need To Know In One Articlemedium.

comLet’s Use Flask To Expose A Machine Learning ModelThe first phase is to host your machine learning model to your local machine.

The last phase is to host the model from local to an external web server.

Follow these steps:1.

Build Machine Learning ModelLet’s assume you have implemented a machine learning model that takes in an input and outputs a variable.

For the sake of simplicity, let’s consider that you have implemented a Stock Price Forecaster.

The machine learning model takes in an input e.

g.

Year and gives you the predicted value of your stock.

If you are new to machine learning then have a look at this article:End To End Guide For Machine Learning ProjectExplains How To Build A Successful Machine Learning Model In Simple Stepsmedium.

comHence the machine learning model does:input_year = 20190606 #inputpredicted_value = my_trained_model.

predict(input_year) #outputYou now want to expose this functionality to the external world.

I will be using the code above to demonstrate how we can expose it externally.

2.

1 Install FlaskInstalling Flask is straight-forward.

Go to the Python terminal and use the pip command:pip install flask3.

Create a Folder Structureapp.

py: This Python file will contain the Flask specific code.

Templates folder: This folder will contain the HTML files.

These HTML files will be rendered on the web browser.

You can also store js, css and other python files if they are required.

4.

Embed Flask Into Your Application app.

pyCreate a file app.

py and perform following steps.

4.

1 Import Flask librariesfrom flask import Flask, render_template, request4.

2 Instantiate Flaskmy_app = Flask('stock_pricer')4.

3 Set up RoutesWe are going to use Python decorators to decorate a function so that the URL is mapped to a function:@app.

route('/')def show_predict_stock_form(): return render_template('predictorform.

html')@app.

route('/results', methods=['POST'])def results(): form = request.

form if request.

method == 'POST': #write your function that loads the model model = get_model() #you can use pickle to load the trained model year = request.

form['year'] predicted_stock_price = model.

predict(year) return render_template('resultsform.

html', year=year, predicted_price=predicted_stock_price)In the example above, “/” URL is now mapped to the show_predict_stock_form() function.

Therefore if a user visits “/”, then Flask will render predictorform.

html on the web browser of the user.

Flask will look for the html file in the templates folder.

Flask is based on Jinja2 template engine.

The render_template() function renders the template and expects it to be stored in the Templates folder on the same level as the app.

py file.

/results is now mapped to results() function which will load the pre-trained model.

Subsequently, it will then get the forecasted stock price and display the predicted value on the web page by rendering the resultsform.

html file.

Note how we are passing year and predicted_price to the render_template() function.

I will explain later how we will display these values on the webpages.

request.

Form is a dictionary object.

You can pass key/value pairs as parameters to the function.

Note, I am using pickle package to load the previously trained model.

Have a look at my article to understand how you can save and load pre-trained machine learning models.

How To Save Trained Machine Learning Models?Save & Reload Your Trained Machine Learning Models In Pythonmedium.

com4.

4 Run the moduleif __name__ == '__main__': my_app.

run("localhost", "9999", debug=True)When the app.

run() is executed then the application will start running.

It will run on the host “localhost” which is your local machine on the port number 9999.

The debug flag is used during development so that the Flask server can reload the code without restarting the application.

It also outputs useful debugging information.

Therefore, when the user will visit http://localhost:9999/, Flask will render the predictorform.

html page.

Photo by Benjamin Davies on Unsplash5.

Implement html webpages5.

1 Implement predictorform.

html<html> <body> <form action = "http://localhost:9999/result" method = "POST"> <p>Year <input type = "text" name = "Year" /></p> </form> </body></html>The key to note is the name attribute.

It is set to “Year”.

5.

2 Implement resultsform.

html<!doctype html><html> <head> <title>Stock Pricer</title> </head> <body> <h3>Year:</h3> <div>{{ year }}</div> <h3>Stock Price:</h3> <div>This is the predicted stock price <strong>{{ predicted_price }}</strong>%).

</div> </div> </div> </body></html>You may notice that we used the {{ year }} and {{ predicted_price }} placeholders.

These containers will display the value of the Year and the value of the predicted stock price.

These values will be passed in via the render_template() function in the app.

py file.

Photo by Anastasia Petrova on Unsplash7.

Run The ApplicationWithin a Python termination, type inpython app.

pyThis will now run your python application using Flask micro framework on your local machine.

Flask will run the application on port 9999 therefore navigate to:http://localhost:9999/Our machine learning model is now running as a web application on our local machine.

Photo by Robert V.

Ruggiero on Unsplash8.

Deploy the application to public serverCongratulations, now your model is running on a web browser on your machine.

The last task is to deploy it on an external server so that the public can access it.

Firstly, disable debug mode:my_app.

run()There are a number of external web servers available.

Have a look at webfaction, Heroku, dotcloud and PythonAnywhere.

These web application hosting sites can let you easily import your code and start running your machine learning model on the server so that the public can access your code.

Do read the license and terms and conditions of the hosting sites beforehand.

It is as simple as that folks!Photo by Daniel Wiadro on UnsplashSummaryThis article explained how we can host a machine learning model to external world.

This is one of the key steps involved to make a business out of your machine learning model.

Let me know if you have any feedback.

Hope it helps.

.

. More details

Leave a Reply