Deploying Machine Learning Models With Flask

Deploying Machine Learning Models with Flask: A Comprehensive Guide

Machine Learning (ML) has proved to be a revolutionary technology, transforming numerous sectors, from healthcare to finance. However, developing an ML model is one part of the story; deploying it for real-world use is another challenge altogether. Flask, a micro web framework written in Python, makes this task easier. This comprehensive guide will dive deep into deploying ML models with Flask.


Deploying Machine Learning Models With Flask
Deploying Machine Learning Models With Flask

This article is suitable for both beginners and experienced Python enthusiasts, with explanations that are clear, engaging, and thorough. The guide will ensure a coherent flow of content while maintaining accuracy and reliability.

Table of Contents

  • Understanding Flask
  • Machine Learning Deployment
  • Building a Machine Learning Model
  • Deploying ML Model with Flask

Understanding Flask

Flask is a web framework. It’s a Python module that lets you develop web applications easily. It has a small and easy-to-extend core. It’s a microframework that doesn’t include an ORM (Object Relational Manager) or such features.

It does have many cool features like url routing, template engine. It is a lightweight WSGI web application framework.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, Flask!"

The above is a basic Flask application, that defines a single route and view.

Machine Learning Deployment

Deployment is the process of packaging an ML model so that it can be used in different environments. A model is trained to recognize patterns in data, and we deploy the model to make these patterns available for real use.

The ML model is thus packaged into an application that can send new data points to it and receive a prediction in return.

Building a Machine Learning Model

Let’s start by building our ML model. We will use the LinkedIn dataset to predict whether a profile will be ‘hired’ or ‘not hired’.

# Importing necessary libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.externals import joblib

# Load dataset
df = pd.read_csv('LinkedIn.csv')

# Features and target
features = df.drop('Job', axis=1)
target = df['Job']

# Splitting data
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=1)

# Create a RandomForestClassifier
random_forest = RandomForestClassifier(random_state=1)

# Train the model
random_forest.fit(X_train, y_train)

# Save the model as a pickle file
joblib.dump(random_forest, 'model.pkl')

print("Model trained and saved")

The joblib module is used to save the model for future use.

Deploying ML Model with Flask

With our model saved, we can now build our Flask API.

To start, we need to install Flask. From your terminal, you can install Flask via pip:

pip install Flask

Now, we can build our Flask API. In your project directory, create a app.py file and enter the following code:

from flask import Flask, jsonify, request
import traceback
import pandas as pd
from sklearn.externals import joblib

# Your Flask app
app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    if random_forest:
        try:
            json_ = request.json
            query = pd.get_dummies(pd.DataFrame(json_))
            prediction = list(random_forest.predict(query))

            return jsonify({'prediction': str(prediction)})

        except:

            return jsonify({'trace': traceback.format_exc()})
    else:
        return ('No model here to use')

if __name__ == '__main__':
    try:
        port = int(sys.argv[1]) 
    except:
        port = 12345

    random_forest = joblib.load('model.pkl')
    print ('Model loaded')
    app.run(port=port, debug=True)

Testing the prediction API:

curl -H "Content-Type: application/json" -d "[{\"experience\":\"two\",\"test_score\":8,\"interview_score\":6}]" 
http://localhost:12345/predict

And you should get a prediction back: {"prediction": "[0]"}

In conclusion, deploying your machine learning models shouldn’t be a snag. Flask, due to its evident simplicity and flexibility, provides an excellent option for sending your models into production and thus, real-world use. Understanding the ins and outs of Flask to better structure ML model deployment is therefore a valuable skill for any data scientist. Deploy your model today and turn your insights into actions.

Remember to test, monitor, and update your models, as necessary, post-deployment. Happy learning!

Please reach out in the comments section for any corrections or doubts you might have, and I will get back to you.

References:

Flask’s Official Documentation: https://flask.palletsprojects.com/en/1.1.x/

Machine Learning Deployment with Flask: https://towardsdatascience.com/machine-learning-model-deployment-with-flask-80b4f2dc73b1

Python joblib Module: https://joblib.readthedocs.io/en/latest/

Share this article:

Leave a Comment