How to deploy machine learning model with Flask

widget

Deploying a machine learning model with Flask can be a powerful way to make your models accessible over the web. Flask is a lightweight and easy-to-learn web framework in Python, making it an excellent choice for deploying machine-learning models. Here’s a step-by-step guide on how to do it:

Step 1: Prepare your model

Before deployment, ensure a trained machine learning model is saved as a file (e.g., model.pkl). We can use popular libraries like Scikit-Learn or TensorFlow to build and train your model.

Step 2: Set up your flask application

  1. Install Flask: If you haven’t already, install Flask using pip:

pip install Flask
  1. Create a directory for your project and structure it. You might have folders for templates, static files, and the main application file.

Step 3: Build your flask web application

  1. In your Flask application file (e.g., app.py), import Flask, and create an instance of the Flask app:

from flask import Flask
app = Flask(__name__)
  1. Create routes for your application, such as a home page and a prediction page. For example:

@app.route('/')
def home():
return 'Welcome to the Machine Learning Model Deployment'
@app.route('/predict', methods=['POST'])
def predict():
# Add code to handle model prediction here

Step 4: Load your model

Inside the /predict route, load your pretrained machine learning model using libraries like pickle for Scikit-Learn models.

Step 5: Make predictions

After loading the model, use it to make predictions based on the data sent in the POST request. The input data can be obtained from request.form for form data or request.json for JSON data.

Step 6: Return predictions

Return the model’s predictions as a response, usually in JSON format, using Flask’s jsonify function.

Code example

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

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

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

@application.route('/predict',methods=['POST'])
def predict():
    int_features = [int(x) for x in request.form.values()]
    
    feature_names=['experience', 'test_score', 'interview_score']
    final_features = pd.DataFrame([int_features], columns = feature_names)
    prediction = model.predict(final_features)

    output = round(prediction[0], 2)

    return render_template('index.html', prediction_text='Employee Salary should be $ {}'.format(output))

if __name__ == "__main__":
    application.run(debug=True)
Example Flask Application

Code explanation

  • Lines 1–3: We import the needed libraries, such as numpy, flask, and pickle.

  • Line 5: This line creates a Flask application instance and names it application. This instance will be used to define and run your web application.

  • Line 6: Here, we load a machine learning model from a file named model.pkl using the pickle module. The rb mode indicates reading the file in binary mode.

  • Lines 8–10: We use the default route to display our home page.

  • Line 14: This line extracts values from the form data submitted in the POST request and converts them to integers. These values are stored in the int_features list.

  • Line 15: It creates a NumPy array from the int_features list, wrapping it in a list.

  • Line 16: This line uses the loaded machine learning model to make a prediction based on the input features.

  • Line 20: This line sends the index.html web page to the user and adds a message on it. The message shows the predicted employee salary.

Copyright ©2024 Educative, Inc. All rights reserved