How to deploy machine learning model with Flask
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
Install Flask: If you haven’t already, install Flask using
pip:
pip install Flask
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
In your Flask application file (e.g.,
app.py), import Flask, and create an instance of the Flask app:
from flask import Flaskapp = Flask(__name__)
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)
Code explanation
Lines 1–3: We import the needed libraries, such as
numpy,flask, andpickle.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.pklusing thepicklemodule. Therbmode 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
POSTrequest and converts them to integers. These values are stored in theint_featureslist.Line 15: It creates a NumPy array from the
int_featureslist, 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.htmlweb page to the user and adds a message on it. The message shows the predicted employee salary.
Free Resources