HOW TO DEPLOY A MACHINE LEARNNG MODEL ON A FLASK APP AND HEROKU

In this article i will be showing you how to deploy a machine learning model with flask and heroku, I will be using an home loan dataset from kaggle which consists of several predictor variables and one target variable to identify the customers segments and predict those that are eligible for loan amount so that they can specifically target these customers. Check the report of the analysis i did on this data Here

Prerequisites

  • Familiarity with python3
  • Basic knowledge of machine learning
  • Basic understanding of flask

Environment/Tools Setup

  • ''pip install'' the following packages
    • Numpy, Pandas, Matplotlib, Sklearn
    • Flask
    • Gunicorn
  • Download and install
    • Heroku CLI
    • Git/Github

STEP1 - Train and Save the Model

I used Logistic Regression algorithm to train my model and saved it into a pickle file [model.pkl] with a .pkl extension. A PKL file is a file created by pickle. It is a Python module that enables python objects to be serialized[written to] files on disk that can be tranferred and deserialized [read back] into the python program at runtime. To get this file simply do this after training and evaluating your model


model = LogisticRegression() #define the model
model.fit(X_train, y_train) #fit the model
ypred = model.predict(X_test) #predict on test sample
evaluation = f1_score(y_test, ypred)
evaluation

import pickle
pickle.dump(model,open('model.pkl','wb'))

model = pickle.load(open('model.pkl','rb'))
print(model)

Model.pkl file will be created in your project folder

STEP 2 - Html/css

Create an HTML/CSS Web Page to get values from the user (in form of a form), this file is usually named index.html or you could get templates online. ''Note that your web page’s form names should correspond with the column names in the dataset that was used to build the model.''

STEP 3 - Deploy the Machine Learning Model on a Web Page using Flask App

Flask is a python based easy to use web framework.

Create a flask environment that will have an API endpoint which would encapsulate our trained model and enable it to receive inputs (features) through GET requests over HTTP/HTTPS and then return the output after de-serializing the earlier serialized model, make sure flask is already installed or simply type '' pip install flask'' on your command prompt.

Next, create a python file “app.py” and do the following;

import the required libraries

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

create the flask app

app = Flask(__name__)

load the pickle

model = pickle.load(open('model.pkl', 'rb'))

create a app route to render your html template as the home page

@app.route('/')
def home():
    return render_template('index.html')

create an API which will receives inputs from user through GUI and computes the predicted value based on our machine learning model. For this I de- serialized the pickled model in the form of python object. I set the main page using index.html. On submitting the form values using POST request to /predict, we get the predicted sales value.

@app.route('/predict',methods=['POST'])
def predict():

    int_features = [int(x) for x in request.form.values()]
    final_features = [np.array(int_features)]
    prediction = model.predict(final_features)

    output = round(prediction[0], 2)

    return render_template('index.html', prediction_text='PROBABILITY THAT YOUR LOAN WILL GET APPROVED IS : {}'.format(output))

@app.route('/results',methods=['POST'])
def results():

    data = request.get_json(force=True)
    prediction = model.predict([np.array(list(data.values()))])

    output = prediction[0]
    return jsonify(output)

if __name__ == "__main__":
    app.run(debug=True)

save and run this program, the output should look like

 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 175-498-075
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

If you get this kind of output, it shows that you have sucessfull built ypor app and it running on ''http://127.0.0.1:5000/''. Simply type http://127.0.0.1:5000/ on yor browser to test the app.

Notice that you can’t share your Web Application with your friends without telling them to pass through the procedure of installing flask, pickle, numpy, etc. This is where Heroku comes in.

STEP 4 - Deploy the FlaskApp to Heroku

Heroku is a container-based cloud Platform as a Service (PaaS). Developers use heroku to deploy, manage, and scale modern apps. The platform is elegant, flexible, and easy to use.

To begin visit their website and signup. After signing up, login and click on the 'new' icon on the right corner and select 'create new app'- fill in your choice app name and click on the 'create app' button to create your app dashboard.

Next, select your deployment method. Heroku has 3 deployment methods which are;

  1. Heroku Git - using Heroku CLI
  2. Github - by connecting to github
  3. Container Registry - using Heroku CLI

In this article I'll be showing you how to deploy using the methods in 1 and 2

Heroku Git

  • Install Git on your PC
  • Download and Install the Heroku CLI
  • Open the Heroku CLI and login to your heroku account
    $ heroku login
    
  • Create a new Git repository
$ cd my-project/
$ git init
$ heroku git:remote -a loanstatusprediction-app

note: 'loanstatusprediction-app' is my app name

  • Deploy your application
$ git add .
$ git commit -am "make it better"
$ git push heroku master

Github

  • Push your project folder to a repository on Github
  • Click on Github in the deployment metods menu
  • Click on search , then click the connect in front your project repository
  • On the manual deploy menu, click on the 'Deploy Branch' button and wait for all the installations to complete and your url to be created.
  • Finally you will see a page like this that shows your app was successfully deployed

Click on ''view'' to see your app and share yor url for others to see your app.

Check out my app via '' loanpredictionmodel-api.herokuapp.com ''

Here is the link to my Github repository