Table of Contents
- Introduction
- Prerequisites
- Setup
- Building a Machine Learning Model
- Creating a Flask Application
- Deploying the Model
- Conclusion
Introduction
In this tutorial, we will learn how to deploy machine learning models using Python and Flask. Machine learning models can be powerful tools for making predictions and gaining insights from data. However, to make these models accessible to others or use them in real-world applications, we need to deploy them in a way that allows users to interact with them through a web interface. Flask, a popular Python web framework, provides an excellent platform for building and deploying machine learning applications.
By the end of this tutorial, you will have a clear understanding of how to deploy a machine learning model using Flask. We will cover the entire process, from building the model to creating a Flask application and deploying it. So let’s get started!
Prerequisites
To follow this tutorial, you should have a basic understanding of Python programming and machine learning concepts. Familiarity with Flask or web development in general would be beneficial but is not required. You will need the following software installed on your machine:
- Python 3.x
- Flask
Setup
Before we begin, let’s make sure we have a clean environment to work with. We will create a new directory for our project and set up a virtual environment.
-
Open a terminal or command prompt.
-
Create a new directory for your project:
mkdir flask-ml-deployment cd flask-ml-deployment
-
Create a virtual environment:
python3 -m venv venv
-
Activate the virtual environment:
-
On macOS and Linux:
source venv/bin/activate
-
On Windows:
venv\Scripts\activate
-
-
Install Flask:
pip install Flask
With the project directory and virtual environment set up, we are ready to proceed.
Building a Machine Learning Model
Before we can deploy a machine learning model, we need to build one. For the sake of simplicity, let’s create a basic model using scikit-learn.
-
Open a new Python file called
model.py
in your project directory. -
Import the necessary libraries:
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score
-
Load the dataset:
df = pd.read_csv("data.csv")
Replace
"data.csv"
with the path to your dataset file. -
Split the dataset into training and testing sets:
X = df.drop("target", axis=1) y = df["target"] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
-
Create and train the model:
model = LogisticRegression() model.fit(X_train, y_train)
-
Make predictions on the test set:
y_pred = model.predict(X_test)
-
Evaluate the model’s accuracy:
accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy: {accuracy}")
This will print the accuracy of the model.
Congratulations! You have built a machine learning model using scikit-learn. Next, we will create a Flask application to deploy this model.
Creating a Flask Application
Flask makes it easy to create web applications in Python. We will now set up a basic Flask application that will serve our machine learning model.
-
In your project directory, create a new Python file called
app.py
. -
Import the necessary libraries:
from flask import Flask, jsonify, request import joblib
-
Load the trained model:
model = joblib.load("model.joblib")
Replace
"model.joblib"
with the path to your trained model file. -
Create a Flask application:
app = Flask(__name__)
-
Define a route for making predictions:
@app.route("/predict", methods=["POST"]) def predict(): data = request.json prediction = model.predict([data])[0] response = {"prediction": prediction} return jsonify(response)
This route expects the input data in JSON format and returns the predicted value.
-
Start the Flask development server:
export FLASK_APP=app.py export FLASK_ENV=development flask run
-
Once the server is running, you can make POST requests to
http://localhost:5000/predict
with JSON data to get predictions.
Congratulations! You have created a basic Flask application that can serve predictions from your machine learning model. Now let’s see how to deploy this application.
Deploying the Model
There are various ways to deploy a Flask application, depending on your requirements and infrastructure. In this tutorial, we will cover the simplest method using a cloud platform like Heroku.
-
Sign up for a free account on Heroku if you don’t have one already.
-
Install the Heroku CLI by following the instructions provided on the official documentation.
-
Open a terminal or command prompt and log in to Heroku:
heroku login
-
Create a new Heroku app:
heroku create flask-ml-app
Replace
flask-ml-app
with a unique name for your app. -
Add a new remote repository for Heroku:
heroku git:remote -a flask-ml-app
-
Commit your code changes:
git add . git commit -m "Initial commit"
-
Push your code to Heroku:
git push heroku master
-
Once the deployment is complete, you can open the app in your browser:
heroku open
This will open the deployed Flask application.
Congratulations! You have successfully deployed your machine learning model using Flask and Heroku. Users can now access your application and make predictions through the provided API endpoint.
Conclusion
In this tutorial, we learned how to deploy machine learning models using Python and Flask. We started by building a basic machine learning model using scikit-learn. Then, we created a Flask application that served the model’s predictions. Finally, we deployed the application to a cloud platform like Heroku.
By following this tutorial, you should now have a good understanding of the entire process of deploying machine learning models with Python and Flask. You can use this knowledge to deploy your own models and provide access to them through web APIs. Happy deploying!