Deploy Machine Learning Model in Flask Project

Machine learning has transformed the way we solve complex problems in various industries, including real estate. Deploying a machine learning model into production can be a crucial step in making predictive insights accessible to users. In this blog, we will explore a step-by-step guide on how to deploy any machine learning model using Flask, a popular Python web framework. By the end of this guide, you’ll have a ML model web application up and running.

Prerequisites

Before we begin, ensure you have the following prerequisites:

  1. Basic knowledge of Flask and Python.
  2. A trained machine learning model in a format compatible with Python (e.g., .pkl, .h5, .joblib).

Note: To create pickle file (model.pkl) of your model, please read our blog – How to Create & Run Pickle File for Machine Learning Model

In this tutorial, we are using our ML model which we created in our blog on House Price Prediction using Linear Regression Machine Learning. We have already create a pickle file for it and you can download it from here. We have named it “linear_regression_model.pkl” which we will use in this tutorial.

How to Integrate ML Model into Website using Flask

Step 1: Create a Flask App

First, create a new directory for your project and navigate into it:

mkdir real_estate_prediction
cd real_estate_prediction

Next, create a virtual environment and activate it:

python -m venv venv
# On Windows: venv\Scripts\activate
# On macOS and Linux: source venv/bin/activate

Step 2: Install Flask

Now, install Flask within your virtual environment:

pip install flask

Step 3: Prepare the Model

Place your trained machine learning model file (e.g., model.pkl) in the project directory. For example we have linear_regression_model.pkl.

Step 4: Create the Flask App

Create a new Python file (e.g., app.py) and set up a basic Flask app:

from flask import Flask, render_template, request
import joblib

app = Flask(__name__)

# Load the trained machine learning model
model = joblib.load('model.pkl')

@app.route('/', methods=['GET', 'POST'])
def predict_price():
    prediction_result = None
    if request.method == 'POST':
        # Extract input data from the form
        bedrooms = int(request.form['bedrooms'])
        bathrooms = int(request.form['bathrooms'])
        sqft_living = int(request.form['sqft_living'])
        sqft_lot = int(request.form['sqft_lot'])
        floors = float(request.form['floors'])
        waterfront = 1 if request.form.get('waterfront') == 'on' else 0
        view = int(request.form['view'])
        condition = int(request.form['condition'])

        # Prepare the input data for prediction
        new_data = [[bedrooms, bathrooms, sqft_living, sqft_lot, floors, waterfront, view, condition]]

        # Perform prediction
        predicted_price = model.predict(new_data)[0]
        prediction_result = round(predicted_price, 2)

    return render_template('index.html', prediction_result=prediction_result)

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

Step 5: Create the HTML Template

Create a new directory named “templates” within the project directory. Inside the “templates” directory, create an HTML file named “index.html”:

<!DOCTYPE html>
<html>
<head>
    <title>Real Estate Price Prediction</title>
</head>
<body>
    <form method="post" action="/">
        <label for="bedrooms">Bedrooms:</label>
        <input type="number" name="bedrooms" required><br>
        <label for="bathrooms">Bathrooms:</label>
        <input type="number" name="bathrooms" required><br>
        <label for="sqft_living">Sqft Living:</label>
        <input type="number" name="sqft_living" required><br>
        <label for="sqft_lot">Sqft Lot:</label>
        <input type="number" name="sqft_lot" required><br>
        <label for="floors">Floors:</label>
        <input type="number" name="floors" step="0.1" required><br>
        <label for="waterfront">Waterfront:</label>
        <input type="checkbox" name="waterfront"><br>
        <label for="view">View:</label>
        <input type="number" name="view" required><br>
        <label for="condition">Condition:</label>
        <input type="number" name="condition" min="1" max="5" required><br>
        <button type="submit">Predict Price</button>
    </form>

    {% if prediction_result is not none %}
    <div>
        <h2>Predicted Price: ${{ prediction_result }}</h2>
    </div>
    {% endif %}
</body>
</html>

Step 6: Test Locally

Run the Flask app locally:

python app.py

Visit http://localhost:5000 in your web browser, input the data in the form, and see the predicted price displayed below the form on the same page.

Step 7: Deploy the Application

Before deploying the application to a production server, follow the instructions provided by your hosting provider. Platforms like Heroku or AWS Elastic Beanstalk are popular choices for deploying Flask applications.

Conclusion

Congratulations! You’ve successfully deployed a ML model in web application using Flask and a trained machine learning model. Whetheer it’s predicting financial trends, diagnosing medical conditions, or enhancing user experiences, the step-by-step guide we’ve explored allows us to serve ML models through web applications effortlessly.

Find this tutorial on Github. 

Blogs You Might Like to Read!