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.
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.
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
Inside the /predict
route, load your pretrained machine learning model using libraries like pickle
for Scikit-Learn models.
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.
Return the model’s predictions as a response, usually in JSON format, using Flask’s jsonify
function.
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)
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.
Free Resources