Simple Way To Create A Machine Learning Web App With Flask

Alamin Musa Magaga
Analytics Vidhya
Published in
5 min readMay 18, 2021

--

the simple and easiest way of creating machine learning web app using flask and w3css framework

magtech dihub

web-apps provide the pragmatic concept of artificial intelligence and data science by giving an opportunity to learners, data scientists, and researchers to deploy and test their algorithms/models and channel their solutions into real-world scenarios and practice.

parts of the tutorial :

1-create and Train a model
2-create web app using Flask framework.
3-Run and Test the app

Here is the web app link https://titanic-model1.herokuapp.com,i used w3css to style my app but you can use bootstrap, CSS, or other CSS frameworks to make it look more presentable. you can download the files from my github repo https://github.com/alaminmagaga/titanic-web-app

STEP 1: Create a model

//model name:titanic.pyimport pandas as pd
import numpy as np
import pickle
df=pd.read_csv('titanic_train.csv')
df.drop('Cabin',axis=1,inplace=True)
df['Age']=df['Age'].fillna(df['Age'].mode()[0])
df['Embarked']=df['Embarked'].fillna(df['Embarked'].mode()[0])
sex_mapping={'male':1,'female':2}
df['Sex']=df['Sex'].map(sex_mapping)
embark_mapping={'S':1,'C':2,'Q':3}
df['Embarked']=df['Embarked'].map(embark_mapping)
survival_mapping={1:'survived',0:'Did not survived'}
df['Survival']=df['S'].map(embark_mapping)
df.drop(['PassengerId','Name','Ticket','Survived'],axis=1,inplace=True)
x=df.drop('Survival',axis=1)
y=df.Survival
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler()
x=scaler.fit_transform(x)

Train the Model

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=42)
from sklearn.ensemble import RandomForestClassifier
rfc_classifier = RandomForestClassifier()
rfc_classifier.fit(x_train, y_train)

we now save the model as titanic_classifier.pkl using pickle

pickle.dump(rfc_classifier,open('titanic_classifier.pkl','wb'))
model=pickle.load(open('titanic_classifier.pkl','rb'))

the titanic_classifier.pkl file which will be used later.

STEP 2: Create a web app using the Flask framework

there are other python frameworks that can be used to create web apps but we are using flask because it is very flexible and easier to use. in this stage we are going to create three files:

  • index.html
  • result.html
  • app.py

the index.html and result.html file is our home and result(prediction) page that contains HTML templates and the styling of the web app while the app.py contains the flask API and the predicted values of the model.

now, let’s write our index.html and result.html files

index.html

<!DOCTYPE html>
<html >

<head>
<meta charset="UTF-8">
<title>ML API</title>

<link rel="stylesheet" href="{{ url_for('static', filename='w3.css') }}">
<style type="text/css">

.mySlides {display:none;}
</style>
</head>
<body><div class='w3-padding w3-teal w3-center'><h1>Titanic prediction model</h1></div>
<div class="w3-container">
<div class="w3-padding-18 w3-content w3-section w3-threequarter">
<img class="mySlides" src="{{url_for('static', filename='a1.jpg')}}" style="width:100%;height: 400px;">
<img class="mySlides" src="{{url_for('static', filename='a2.jpg')}}" style="width:100%;height: 400px;">
<img class="mySlides" src="{{url_for('static', filename='a3.jpg')}}" style="width:100%;height: 400px;">
<img class="mySlides" src="{{url_for('static', filename='a4.jpg')}}" style="width:100%;height: 400px;">
</div>
<div class="w3-container w3-padding-24 w3-quarter"><div class="w3-card-4 w3-padding-32" style="width:100%;height: 100%;" >
<header class="w3-container w3-center">
<h5 class="w3-center">Alamin Magaga</h5>
</header>
<div class="w3-container">

<hr>
<img src="{{url_for('static', filename='a5.jpg')}}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px">
<p>Founder of Magtech Dihub,Data scientist,and Web developer</p><br>
</div>
<button class="w3-button w3-block w3-dark-grey"><a href="twitter.com" target="_blank" style="text-decoration:none">+ Connect</a></button>
</div>
</div>
</div>
<div class="w3-container">
<form class="w3-container w3-card-2" action="{{ url_for('predict')}}"method="POST" style="width: 100%">
<h2 class="w3-text-blue w3-center w3-text-teal" >Input Form</h2>
<p>
<label class="w3-text-teal"><b>Pclass</b></label>
<input id="id1" class="w3-input w3-border" name="Pclass" placeholder="Pclass" required="required" type="number" ></p>
<p>
<label class="w3-text-teal"><b>Sex</b></label>
<input id="id1" class="w3-input w3-border" name="Sex" type="number" placeholder="1:female 0:male" required="required" max="1" min="0"></p>
<label class="w3-text-teal"><b>Age</b></label>
<input id="id1" class="w3-input w3-border" name="Age" type="number" placeholder="Age" required="required"></p>
<p>
<label class="w3-text-teal"><b>SibSp</b></label>
<input id="id1" class="w3-input w3-border" name="SibSp" placeholder="SibSp" type="number" required="required"></p>
<label class="w3-text-teal"><b>Parch</b></label>
<input id="id1" class="w3-input w3-border" name="Parch" placeholder="Parch" type="number" required="required"></p>
<p>
<label class="w3-text-teal"><b>Fare</b></label>
<input id="id1" class="w3-input w3-border" name="Fare" placeholder="Fare" type="number" required="required"></p>
<p>
<label class="w3-text-teal"><b>Embarked</b></label>
<input id="id1" class="w3-input w3-border" name="Embarked" placeholder="Embarked" type="number" required="required"></p>



<button onclick="myFunction()" type="submit" class="btn btn-primary btn-block btn-large w3-text-teal w3-border-teal" style="width:100%;">Predict</button>
</form>
</div>
</div><script>
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 2000); // Change image every 2 seconds



}
</script>
</body>
</html>

result.html

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='w3.css') }}">
</head>
<body>
<div class="w3-card-4 w3-teal w3-center w3-padding-32 w3-xxlarge w3-animate-bottom">Titanic Survival Result</div>

</div>
<br>
<div class="w3-card-4 w3-opacity w3-hover-opacity-off w3-animate-top">
<img class="mySlides" src="{{url_for('static', filename='a2.jpg')}}" style="width:100%">
</div>
<br>
<div class="w3-center w3-card-4 w3-teal w3-xxlarge w3-padding-24 w3-text-black" >
<h2>{{ prediction_text }}</h2></div>



</div>
</body>
</html>

let us also create app.py file

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__)
model = pickle.load(open('titanic_classifier.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
def predict():
'''
For rendering results on HTML GUI
'''
int_features = [int(x) for x in request.form.values()]
final_features = [np.array(int_features)]
prediction = model.predict(final_features)
return render_template('result.html', prediction_text='The Passenger {}'.format(prediction[0]))if __name__ == "__main__":
app.run(debug=True)

Results:

the titanic-web is my main folder containing the static and template subfolders and also the app.py,titanic.py,titanic_classifier, and the dataset. the titanic_classifier.pkl file was created from the model(titanic.py)

the static folder contains the images and the w3css file which is used for styling the web app

magtech dihub

the templates folder contain the index.html and result.html file

Run the web application using anaconda command prompt.

python app.py

copy and paste this URL:http://127.0.0.1:5000/ in your browser

magtech dihub

Here is the Web App:

magtech dihub
magtech dihub

https://medium.com/analytics-vidhya/identifying-cleaning-and-replacing-outliers-titanic-dataset-20182a062893

https://medium.com/analytics-vidhya/natural-language-processing-nlp-and-process-modeling-in-precision-medicine-a55fa9ec9818

https://medium.com/analytics-vidhya/3-main-challenges-for-training-algorithm-in-medical-field-f2cf29d4eecc

--

--

Alamin Musa Magaga
Analytics Vidhya

Data Scientist | Developer | Embedded System Engineer | Zindi Ambassador | Omdena Kano Lead | Youth Opportunities Ambassador | CTO YandyTech