Flask with Colab-Machine Learning ( Iris Classification )

Devesh Surve
7 min readJun 10, 2020

--

Alright, so now the you know how to setup a flask application using google colab, let’s get to some more fun stuff. In case, you have not seen the first tutorial I would definitely recommend checking it out.

So let’s get started !

First of all here’s what we are going to do :

  1. Build a Machine Learning Classification Model for Iris Data set
  2. Integrate the Prediction Function of the Model with Flask APIs
  3. Build basic Html CSS bootstrap front end to interact with our model and get predictions

Let us begin by building our IRIS classification model. Now, if you don’t have any prerequisite knowledge about Machine Learning, I shall be explaining the basics as we go along.

Aim :

Create a model which can classify different species of the Iris flower given certain details.

Problem solving:

Now, here are the basic steps we perform when we are creating a Machine Learning Model.

  1. Create a dataset.
  2. Build a model
  3. Train the model
  4. Make predictions.

Iris Flower:

So we shall be classifying iris into 3 species :

Dataset

Since we are using scikit-learn over here, we do get an in-built dataset for the iris classification problem.

Here’s a sample of our dataset :

We can see that we have 4 features and 3 labels over here :

Labels :Iris setosa, Iris virginica and Iris versicolor
Features : Sepal length,Sepal width,Petal length,Petal Width in cm

First we load the Iris dataset as follows :

from  sklearn import  datasets
iris=datasets.load_iris()

Now, we assign the data and target to separate variables where x contains the features and y contains the labels

x=iris.data
y=iris.target

Splitting the dataset;

Now, we split the dataset into 2 parts; Training data and Testing data. This is done in order for our model to be trained on one and then its predictions to be tested on another.

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.5)

Build the model

from sklearn import neighbors
classifier=neighbors.KNeighborsClassifier()

There we have the model. We are going to be using the KNeighbours Classifier Algorithm. I am using this mostly for efficiency but feel free to chose whatever you like. Keep in mind, we have created the model, however we cannot predict stuff yet.

For that we Train the Model

Training our Model.

We can train the model with fit function.

classifier.fit(x_train,y_train)

Now the model is ready to make predictions

Making predictions:

Predictions can be done with predict function

predictions=classifier.predict(x_test)

And now we find out how accurate our model was :

from sklearn.metrics import accuracy_score
print(accuracy_score(y_test,predictions))

Code for referral :

from  sklearn import  datasets
iris=datasets.load_iris()
x=iris.data
y=iris.target
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.5)
from sklearn import tree
from sklearn import neighbors
classifier=neighbors.KNeighborsClassifier()
predictions=classifier.predict(x_test)
from sklearn.metrics import accuracy_score
print(accuracy_score(y_test,predictions))

Now let us modify the iris code a little bit, for our futher use. We shall create a score function, wherein you pass a list of 4 values namely the Sepal length,Sepal width,Petal length,Petal Width in cm and you get the prediction.

def score(sample):
import numpy as np
np_sample = np.array(sample)
pred = classifier.predict(np_sample.reshape(1, -1)).tolist()
return ['setosa', 'versicolor', 'virginica'][pred[0]]

Your Colab notebook should be looking somewhat like this

Cool, Now we have created our Model, trained our Model and have a function which predict the IRIS Species given 4 values.

Time to make our Flask App now !

Building the Flask App

Now to those who have seen the previous article, you already know the drill. To those who haven’t I’ll still explain in short.

We begin by exposing our 5000 port as a proxy

from google.colab.output import eval_js
print(eval_js("google.colab.kernel.proxyPort(5000)"))

Then we define our Flask Application, the template path and our home page to be displayed.

from flask import Flask, render_template, request
app = Flask(__name__, template_folder='drive/My Drive/templates')
@app.route("/")
def home():
return render_template('home.html')
@app.route("/iris")
def iris():
pass
if __name__ == "__main__":
app.run()

Now we will mount our drive if you haven’t already and we shall create a folder called templates within which we shall have this home.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>Iris Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<style>
body {
text-align: center;
}
form {
display: inline-block;
}
</style>
<header>
<div class="container">
<h1 class="logo">Iris Flask App</h1>
<strong><nav>
<ul class="menu">
<li><a href="{{ url_for('iris') }}">Iris Classification</a></li>
</ul>
</nav></strong>
</div>
</header>

{% block content %}
{% endblock %}
</body>
</html>

Just in case it starts getting confusing, here is how my colab notebook looked right about now

Now click on the generated proxy link and should be able to see something like this

Now on click of that link we open another html file we take in a form the 4 values that we shall be needing for the calculation.

Now, alter the flask definition cell as follows :

from flask import Flask, render_template, request
app = Flask(__name__, template_folder='drive/My Drive/templates')
@app.route("/")
def home():
return render_template('home.html')
@app.route("/iris")
def iris():
return render_template('iris.html')

if __name__ == "__main__":
app.run()

And add an iris.html file in drive > My Drive > templates > iris.html

Here’s the code for iris.html

<html>
<head>
<title>Iris Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
{% extends "home.html" %}
{% block content %}
<div>
<style>
body {
text-align: center;
}
form {
display: inline-block;
}
</style>
<form action = "https://yue74mfyp1-496ff2e9c6d22116-5000-colab.googleusercontent.com/predict" class="form-group" method = "post">
<div class="row">
<p>Enter sepal length (cm):</p>
<p><input class="form-control" type = "text" name = "sl" /></p>
</div >
<div class="row">
<p>Enter sepal width (cm):</p>
<p><input class="form-control" type = "text" name = "sw" /></p>
</div >
<div class="row">
<p>Enter petal length (cm):</p>
<p><input class="form-control" type = "text" name = "pl" /></p>
</div >
<div class="row">
<p>Enter petal width (cm):</p>
<p><input class="form-control" type = "text" name = "pw" /></p>
</div >
<p><input class="btn btn-primary" type = "submit" value = "submit" /></p>
</div>
</form>
{% endblock %}
</body>
</html>

NOTE : Remember to edit the form action in this one and Change the url as per proxy generated by you.

Here’s how my Colab notebook looks right now for reference.

Execute the cells and open the link. Click on iris application and here’s what you shall see

Now, we have our link we have our form. Once we press submit, we shall have our values ! The only thing that shall remain will be the prediction.

Now, add another predict api to the flask cell.

from flask import Flask, render_template, request
app = Flask(__name__, template_folder='drive/My Drive/templates')
@app.route("/")
def home():
return render_template('home.html')
@app.route("/iris")
def iris():
return render_template('iris.html')
@app.route('/predict',methods = ['POST', 'GET'])
def predict():
if request.method == 'POST':
sl = request.form['sl']
sw = request.form['sw']
pl = request.form['pl']
pw = request.form['pw']
sample = [int(sl),int(sw),int(pl),int(pw)]
pred = score(sample)
return render_template("pred.html", value=pred)

if __name__ == "__main__":
app.run()

and pred.html to the templates folder. Here’s the html file

<html>
<head>
<title>Iris Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div>
<style>
body {
text-align: center;
}
form {
display: inline-block;
}
</style>
{% extends "home.html" %}
{% block content %}
<div class="jumbotron">
<p>The Prediction is as follows : {{ value }}</p>
</div>
{% endblock %}
</body>
</html>

Put in the values and hit submit button to get your results !

And finally, here’s how our colab notebook looks like :

And that’s all there is ! Thanks a lot if you have read it till the end. And please suggest any tutorials you wish me to create related to flask or machine learning .

--

--

Devesh Surve
Devesh Surve

Written by Devesh Surve

Grad student by day, lifelong ML/AI explorer by night. I dive deep, then share easy-to-understand, step-by-step guides to demystify the complex.

Responses (1)