WebApp for prediction using Deployed ML Model

Saket Srivastawa
6 min readSep 28, 2021

--

Machine Learning | MLOps | WebApp | ML Model Deployment| Python Backend | HTML Frontend | Flask | Linear Regression | Python Pickle

Source : https://www.c-sharpcorner.com/blogs/mlops

Hi everyone! Welcome to my new article, and I’ll try my best to explain it in the easiest way possible. I hope it helps! :)

As the title suggests, we’ll be creating a WebApp which will take the input from an HTML page (Frontend - User Interface) hosted on our created Python Flask server (Backend), call an already deployed Machine Learning (ML) Model (in our case, Linear Regression Model created on Dummy data) for prediction and return the Predicted value back on the Webpage.

In business context, deploying a ML Model in production is of utmost importance followed by creating a WebApp for Real-time Prediction or Batch Prediction. Without the same, business of any domain won’t ever get benefitted. The result after the API call is what makes sense for any business and helps in decision making. For example:

1. For Retail Industry, creating a Model for Promotion Effectiveness is not enough unless until a Promotion Effectiveness tool is created for business to understand the impact of different types of promotions in the future and thus helping with stock inventory as well as increased sales.

2. For any Smart Speakers, creating a NLP (Natural Language Processing) Model is not enough unless it’s deployed, thus making it available for general audience.

3. For Automated Asset maintenance, creating an Image Classification Model to classify images into Defective or Good categories is not enough for automated asset maintenance, unless until it’s deployed into Production and all New Images go through it in batch-process making it an automated process instead of manual.

If we talk about a day-to-day use, there are various ML Models that are deployed without our knowledge and used by us in various different applications we use. Such as:

1. Recommendation Systems of any OTT platform (such as Netflix etc.) which suggests new movie recommendation to us depending on our previous views.

2. Market-basket analysis which suggests what to buy along with something we just put in our Cart on any e-commerce websites (such as Flipkart etc.). For example, once we put coffee in out Cart, it suggests you to buy sugar or milk powder along with it.

3. Google Fit sets or suggests Goals for us by noticing our walking pattern and predicting the goal which is achievable by us.

4. Forecasting Models for Weather Forecasting helps us prepare accordingly for the day/week.

5. Prediction of the Electricity Bill for the upcoming month is one of the simplest example we could notice in our day-to-day life.

As we can see, we interact with different types of ML Models without even having a knowledge about it. It’s because even if we get access to those models, it won’t make any sense to us. What makes sense is the output those models generate. That’s what makes sense for business as well.

If we talk about the technical context, we have various types of Models available under the umbrella of Machine Learning. But we’ll NOT be focusing on developing the Best possible model; instead we’ll be focusing on Deploying a model and then making a call to it for Prediction.

This article talks about only one part of the complete MLOps cycle, which is deployment. We will be deploying/saving a ML Model on our local system and use it for Prediction on a WebApp to show the importance of the MLOps cycle and see a live example which will help us understand how Machine Learning actually works.

Now that we have basic understanding of why Model Deployment to Production and having a WebApp making calls to those Models is important, we will now go ahead with the implementation/coding for everyone to get hands-on experience.

Firstly, we’ll be creating a complete architecture of the flow:

Let’s get started with the implementation now:

  1. Creating a Dummy CSV file.
    height will be our dependent variable (the input we give on UI)
    weight will be our independent variable (the one model will predict with help of our given input height)
    NOTE : I’ve kept the difference between the two columns as 100 for all rows, so that we can easily understand the output on WebApp and test how the model works for different inputs.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import pickle

2. Creating a Linear Regression ML Model (Linear_Regression_Model_Building.ipynb)

id_numbers = input_df['Id']
input_df = input_df.drop('Id',axis=1)
y = input_df['Weight']
input_df = input_df.drop('Weight',axis=1)
X_train, X_test, y_train, y_test = train_test_split(input_df, y, test_size=0.33, random_state=42)lr = LinearRegression()lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)
res = y_test.to_frame('Actual Value')
res.insert(0, 'Predicted Value', y_pred)
res = id_numbers.to_frame().join(res, how='inner')
print(res)
plt.scatter(X_test, y_test)
plt.plot(X_test, y_pred, color='red')
plt.show()
# regression coefficients
print('Coefficients: ', lr.coef_)

# variance score: 1 means perfect prediction
print('Variance score: {}'.format(lr.score(X_test, y_test)))

3. Deploying/Saving the ML Model in a local directory

# save the model to disk
filename = 'Linear_Regression_model.sav'
pickle.dump(lr, open(filename, 'wb'))

4. Creating the Frontend:
A HTML template (index.html and place it inside templates folder) having an input-text box (to take X-variable as input) and a submit button to make a call to python backend

<html>
<head>
<title>Server</title>
<body>
<h1>My Website</h1>
<form method ="post" action="/submit">
<h3>POST Method - Check URL for understanding</h3>
<input type="text" name="search_term" placeholder="Enter Height (Dependent Variable)..">
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</script>
</body>
</head>
</html>

5. Creating the Backend:
A python Flask server (server.py) to host the HTML page and call the python script (logic.py) which internally loads the model, does our prediction for given input and returns the output back which is rendered back to UI.

from flask import Flask, render_template, request
import logic
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/submit',methods=['POST'])
def submit():
print ('I got clicked!')
x = int(request.form['search_term'])
test = [[x]]
output = logic.predict_and_return_data(test)
#return output
return output.to_html(header="true", table_id="table")
#return 'Clicked by %s' % name
if __name__ == '__main__':
app.run(debug=True)

6. Creating the logic.py file which does the prediction and returns the output

import pandas as pd
import numpy as np
import pickle
def process_data(dependent_variable):
# load the model from disk
filename = 'Linear_Regression_model.sav'
loaded_model = pickle.load(open(filename, 'rb'))
result = loaded_model.predict(dependent_variable)
# result = loaded_model.score(X_test, Y_test)
print(result)
res = [[dependent_variable, result]]
result_df = pd.DataFrame(res, columns = ['Height', 'Weight'])
return result_df
def predict_and_return_data(dependent_variable):
output = process_data(dependent_variable)
return output

7. Screenshot of the data directory

8. Go to cmd (Command Line) at this directory and start the server by running server.py script

Open URL http://127.0.0.1:5000/ (as mentioned on cmd) on Google Chrome

In “Enter Height” input field, give a height, here as 180 and click “Submit”

Input

and observe the output.

Output

Press Ctrl+C on cmd to shut down the server.

As we can see, the output changes with the given input. It gives quite an insight on how ML actually works.

FUN FACT :
With Linear Regression model, for inputs 180 and 190, we get output back as 80 and 90 respectively.
Try replacing it with the Decision Tree model in the logic.py script, you’ll observe the difference in output as compared to the previous model’s results.

Any idea Why? Time to wake up the Data Scientist within you. 😉
Let me know your answers in comments.

Github URL : https://github.com/Mr-Saket/WebApp_for_prediction_using_Deployed_ML_Model

Link to previous article : https://medium.com/@saket.srivastawa/image-classification-using-transfer-learning-49411ececf5d

Hoping this was helpful to someone. Please let me know in comments how I could improve this article, or any upcoming ones so that it becomes helpful for the readers.

--

--

Saket Srivastawa

Data Scientist | GCP Certified Professional ML Engineer | AI | ML | DL | NLP | Conversation AI