Deploy Machine Learning Model Using Flask



Deploying a Machine Learning Model Using Flask

Machine learning (ML) models are powerful tools for solving real-world problems. However, for them to be useful, they need to be deployed so that users can interact with them via a web interface or API. Flask, a lightweight web framework in Python, is a great option for deploying ML models due to its simplicity and flexibility.

This guide provides a step-by-step approach to deploying an ML model using Flask.

You have trained a machine learning model for a specific task, such as image classification, sentiment analysis, or predictive analytics. Now, you have to make this model accessible via a web application so users can input data and receive predictions.

Approaches to Deployment

There are multiple ways to deploy an ML model:

  • Using Flask: A simple approach ideal for small to medium-scale applications.
  • Using Django: A more structured framework suitable for larger applications.
  • Deploying on Cloud Platforms: Services like AWS, Google Cloud, or Azure provide scalable deployment options.

Step-by-Step Guide to Deploying a Machine Learning Model Using Flask

Step 1: Install Dependencies

Ensure you have Python installed, then install the required libraries:
pip install flask pandas numpy scikit-learn joblib

Step 2: Train and Save the Machine Learning Model

For this tutorial, let's assume we have a simple logistic regression model trained on a dataset.

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import joblib

# Load dataset
data = pd.read_csv("data.csv")
X = data.drop("target", axis=1)
y = data["target"]

# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train the model
model = LogisticRegression()
model.fit(X_train, y_train)

# Save the model
joblib.dump(model, "model.pkl")

Step 3: Create a Flask Application

Create a file app.py and set up a basic Flask application.

from flask import Flask, request, jsonify
import joblib
import numpy as np

app = Flask(__name__)

# Load the trained model
model = joblib.load("model.pkl")

@app.route("/predict", methods=["POST"])
def predict():
    data = request.get_json()
    features = np.array(data["features"]).reshape(1, -1)
    prediction = model.predict(features)
    return jsonify({"prediction": int(prediction[0])})

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

Step 4: Run the Flask Application

python app.py

Step 5: Testing the API

Use a tool like Postman or cURL to send a POST request to test the API:

{
"features": [5.1, 3.5, 1.4, 0.2]
}

If successful, you should receive a JSON response with the model's prediction.

Deploying to a Cloud Platform

To make the Flask API accessible online, deploy it using Heroku, AWS Lambda, or Google Cloud Run.

Deploying on Heroku

 1. Install the Heroku CLI:

pip install gunicorn

 2. Create a Procfile in the project directory:

web: gunicorn app:app

 3. Initialize a Git repository and push it to Heroku:

git init
heroku create
git add .
git commit -m "Initial commit"
git push heroku master

Conclusion

Deploying a machine learning model using Flask is an effective way to make predictions accessible via an API. By following this guide, you can train a model, create an API, and deploy it for real-world use. For large-scale deployment, consider cloud platforms like AWS, GCP, or Azure.

Amar Kumar
Amar Kumar

Developer

Updated on: 2025-01-31T19:49:48+05:30

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements