USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
Br
Ethiopian Birr
¥
China Yuan Renminbi
Pakistan Rupee
£
Egypt Pound
د.إ
United Arab Emirates dirham
R
South Africa Rand
ر.س
Saudi Arabia Riyal

Deploying Machine Learning Models With Flask- Implementation

Created by Vishal Verma in Articles 25 Feb 2024
Share

Building a Machine Learning Model Deployment Web App with Flask


Introduction


Machine learning models hold immense potential, and deploying them in user-friendly applications enhances their real-world utility. In this comprehensive tutorial, we will guide you through the process of developing a straightforward machine learning model using the Iris dataset and deploying it as a web application using Flask. The web application will empower users to input feature values and receive predictions about the species of an Iris flower in a seamless and interactive manner.


Project Directory Setup


Before delving into the step-by-step development, let's establish a clean and organized directory structure for our project. This structure ensures clarity and separation of concerns:


# Trained machine learning model file

├── templates/
│ └── index.html # HTML template for the web application

├── app.py # Flask application script
├── train_model.py # Script to train the machine learning model
├── predict.py # Script to load the model and make predictions

└── static/
└── (optional) # You can store static files like CSS or JavaScript here

This directory structure neatly separates the machine learning model, web application files, and potential static resources, contributing to a well-organized project.


Step 1: Train the Machine Learning Model


Our first step involves training a machine learning model using the K-Nearest Neighbors (KNN) algorithm. This model will be trained on the Iris dataset, which is a classic dataset in the machine learning community. The dataset contains measurements of sepal length, sepal width, petal length, and petal width for three different species of Iris flowers.


Code Explanation:


# train_model.py

import pickle
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score

# Load the Iris dataset
iris = datasets.load_iris()
X = iris.data # Features
y = iris.target # Target variable (species)

# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Initialize the K-Nearest Neighbors classifier
knn = KNeighborsClassifier(n_neighbors=3)

# Train the model on the training set
knn.fit(X_train, y_train)

# Save the trained model to a file using pickle
with open('model/iris_model.pkl', 'wb') as model_file:
pickle.dump(knn, model_file)

# Load the saved model
with open('model/iris_model.pkl', 'rb') as model_file:
loaded_model = pickle.load(model_file)

# Make predictions on the testing set using the loaded model
y_pred = loaded_model.predict(X_test)

# Evaluate the accuracy of the loaded model
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy of loaded model: {accuracy * 100:.2f}%")

In this script:



  1. 1. We load the Iris dataset using scikit-learn.

  2. 2. Split the dataset into training and testing sets.

  3. 3. Initialize a K-Nearest Neighbors classifier and train it on the training set.

  4. 4. Save the trained model to a file using pickle.

  5. 5. Load the saved model back.

  6. 6. Make predictions on the testing set and evaluate the accuracy of the loaded model.


This step establishes the foundation of our machine learning model.


Step 2: Develop the Flask Web Application


With our model trained, let's move on to creating a Flask web application that will serve as the user interface for interacting with the machine learning model.


Code Explanation:


# app.py

from flask import Flask, render_template, request, jsonify
import pickle
import numpy as np

app = Flask(__name__)

# Load the machine learning model
with open('model/iris_model.pkl', 'rb') as model_file:
loaded_model = pickle.load(model_file)

@app.route('/')
def home():
return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
# Get input data from the request
data = request.get_json(force=True)

# Extract input features from the data
input_data = np.array(data['input_data']).reshape(1, -1)

# Make predictions using the loaded model
prediction = loaded_model.predict(input_data)

# Map the predicted class to the corresponding species
species_mapping = {0: 'setosa', 1: 'versicolor', 2: 'virginica'}
predicted_species = species_mapping[prediction[0]]

# Return the prediction as JSON
return jsonify({'prediction': predicted_species})

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

In this Flask application:



  1. 1. We load the trained machine learning model using pickle.
  2. 2. Create a Flask web application instance.
  3. 3. Define two routes: / for rendering the HTML form and /predict for handling predictions based on user input.
  4. 4. In the /predict route, we extract input features from the JSON data sent by the frontend, make predictions using the loaded model, map the predicted class to the corresponding species, and return the result as JSON.


This sets the stage for creating the user interface.


Step 3: Create the HTML Form


Now, let's create a simple HTML form to capture user input. This form will serve as the interface for users to input feature values for prediction.


Frontend HTML Script with Styles:


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Machine Learning Model Deploymenttitle>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}

h1 {
color: #333;
}

form {
display: flex;
flex-direction: column;
align-items: center;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
margin-top: 20px;
}

label {
margin-bottom: 10px;
width: 100%;
}

input {
width: 100%;
padding: 8px;
margin-bottom: 15px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
}

.button-container {
display: flex;
gap: 10px;
width: 100%;
padding: 2px;
margin-top: 10px;
}

button,
input[type="reset"] {
flex: 1;
background-color: #4CAF50;
color: white;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
}

button:hover,
input[type="reset"]:hover {
background-color: #45a049;
}

#predictionResult {
margin-top: 20px;
font-weight: bold;
}
style>
head>

<body>
<h1>Welcome to our Machine Learning App Deployment Tutorialh1>

<form id="predictionForm">
<label for="feature1">Sepal length:label>
<input type="text" id="feature1" name="feature1" placeholder="Enter Feature 1" required>

<label for="feature2">Sepal width:label>
<input type="text" id="feature2" name="feature2" placeholder="Enter Feature 2" required>

<label for="feature3">Petal length:label>
<input type="text" id="feature3" name="feature3" placeholder="Enter Feature 3" required>

<label for="feature4">Petal width:label>
<input type="text" id="feature4" name="feature4" placeholder="Enter Feature 4" required>

<div class="button-container">
<button type="button" onclick="predict()">Predictbutton>
div>
<div class="button-container">
<input type="reset" value="Reset" onclick="resetPrediction()">
div>
form>

<p id="predictionResult">p>
<script> </script>
<body>

html>

This HTML script includes the head section with meta tags, style tags for CSS styling, body content with the form, and a script tag for JavaScript functions handling form submission and resetting.


Step 4: Implement JavaScript for User Interaction


To enhance the user experience, we'll implement JavaScript code to handle form submission and resetting. This JavaScript code will facilitate communication with the Flask server for making predictions.


JavaScript Function:


// JavaScript code for handling form submission and resetting
function predict() {
// Get input data from the form
var feature1 = document.getElementById("feature1").value.trim();
var feature2 = document.getElementById("feature2").value.trim();
var feature3 = document.getElementById("feature3").value.trim();
var feature4 = document.getElementById("feature4").value.trim();

// Validate input data
if (!feature1 || !feature2 || !feature3 || !feature4) {
alert("All

fields are required"
);
return;
}

// Send input data to the Flask server for prediction
fetch('/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'input_data': [parseFloat(feature1), parseFloat(feature2), parseFloat(feature3), parseFloat(feature4)]
}),
})
.then(response => response.json())
.then(data => {
// Display the prediction result on the webpage
document.getElementById("predictionResult").innerHTML = "Predicted species: " + data.prediction;
})
.catch(error => {
console.error('Error:', error);
});

}

function resetPrediction() {
// Reset the prediction result
document.getElementById("predictionResult").innerHTML = "";
document.getElementById("predictionForm").reset();
}

These JavaScript functions are crucial for handling form submissions, validating input data, and communicating with the Flask server to obtain predictions. The results are then displayed on the webpage, enriching the user experience.


Step 5: Run the Flask App


With the machine learning model trained, Flask app developed, HTML form created, and JavaScript implemented, we are ready to run the Flask app locally.


Running the Flask App:


python app.py

Visit http://localhost:5000 in your web browser to interact with the machine learning model through the web application.


Do predictions:


GitHub Repository URL: Python Flask Tutorial - Model Deployment

Congratulations! You've successfully built and deployed a machine learning model using Flask, providing users with a user-friendly web interface for making predictions. This tutorial lays the groundwork for more complex models and applications.

Follow Vishal Verma for more such interesting contents!

Comments (0)

Share

Share this post with others

GDPR

When you visit any of our websites, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and manage your preferences. Please note, that blocking some types of cookies may impact your experience of the site and the services we are able to offer.