Abdulsamod Azeez
Abdulsamod Azeez's Blog

Abdulsamod Azeez's Blog

How to Build a Machine Learning Web App in Python Using Gradio

How to Build a Machine Learning Web App in Python Using Gradio

Abdulsamod Azeez's photo
Abdulsamod Azeez
ยทMar 31, 2022ยท

5 min read

Featured on Hashnode
Featured on daily.dev

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • Prerequisites
  • Introduction to Gradio
  • Getting started
  • Building the UI with Gradio
  • Conclusion
  • References

Data science is practiced by students and professionals from different fields, such as business management, financial services, medicine and health, agriculture, information, technology, academics, law enforcement, etc. It is critical to deploy machine learning models and create a user interface to convey the finished model to customers. However, designing user interfaces and backends requires more effort than developing machine learning models. You have to write many lines of code and a significant amount of energy and time are required. Conventional deployment frameworks like Django or Flask are well-known and most used, however, they can be difficult and time-consuming. Well, we now have multiple libraries built that simplify the deployment process. One of such packages is Gradio; a Python library that allows you to quickly and easily create a web user interface for your completed ML model. In this tutorial, I will introduce you to the Gradio library and show you how you can utilize it in your machine learning project(s).

Prerequisites

Before you begin this tutorial you'll need the following:

  • A working computer with Python (version >3) installed.
  • A code editor or Jupyter notebook (you can use Anaconda or Visual Studio Code for this)
  • Some internet connection.

Introduction to Gradio

Gradio is a Python library that is both free and open source. We can efficiently and simply develop UI interfaces in our Python notebook, share them with anyone with just a few lines of code, and display the outcomes of our completed model. Gradio makes it simple to construct customizable UI components in Colab, Jupyter notebooks, scripts, TensorFlow or PyTorch models, or even random Python functions.

To help you get started with Gradio, I have built a model that we will use to create a simple Iris flower prediction web application using the public Iris species dataset that can tell you whether an Iris flower is of the specie type setosa, versicolor, or virginica.

Getting started

Three Python libraries will be required for this demo project: Gradio, scikit-learn, and pandas. You can install them with the pip commands below:

pip install gradio
pip install sklearn
pip install pandas

Once installed successfully, you then import the packages into your Python notebook/script like so:

import gradio as gr
import sklearn
import pandas as pd

And now, we're ready to use Gradio to design a stunning user interface ๐Ÿ˜‰.

Building the UI with Gradio

The gradio.interface() function is used to establish interfaces with significant parameters such as the input, output, and callable functions. The launch() function is used to display the interface; after this, an external URL will be generated to share and run the interface in the browser easily. The code for the web application powered by Gradio will look like this:

import gradio as gr
from sklearn import datasets
from sklearn.tree import DecisionTreeClassifier

data = datasets.load_iris()
X = data.data
Y = data.target
model= DecisionTreeClassifier()
model.fit(X, Y)


def iris(sepal_length ,sepal_width, petal_length, petal_width):
    prediction = model.predict([[sepal_length ,sepal_width, 
                                petal_length, petal_width]])
     prediction= data.target_names[prediction]return prediction

#create input and output objects
#input object1
input1 = gr.inputs.Number(label="sepal length (cm)")
#input object 2
input2 = gr.inputs.Number(label="sepal width (cm)")
#input object3
input3 = gr.inputs.Number(label="petal length (cm)")
#input object 3
input4 = gr.inputs.Number(label="petal width (cm)")
#output object
output = gr.outputs.Textbox(label= "Name of Species") 

#create interface
gui = gr.Interface(fn=iris,
                   inputs=[input1, input2, input3, input4],
                   outputs=output).launch()

Now, let me explain the code above line-by-line and break it down so we understand what each line (or code block) does.

Import Libraries

In line 1-3, we import the Gradio library with gr alias and the datasets package from the scikit-learn library (sklearn) (which will be used to load the Iris dataset in line 5). Finally, we use import the DecisionTreeClassifier() method from the sklearn.tree package.

Model building

In lines 5-9, we write the actual model construction setup as described below:

  • Line 5: loads in the Iris dataset from the sklearn.datasets package and assign it to the data variable.
  • Line 6: creates the X variable containing the 4 flower features (i.e. sepal length, sepal width, petal length, and petal width) provided in data.data.
  • Line 7: creates the Y variable pertaining to the Iris class label provided in data.target.
  • Line 8: assigns the random forest classifier, particularly the DecisionTreeClassifier() function, to the model variable.
  • Line 9: trains the model via the model.fit() function by using X and Y variables as input arguments. This essentially means that a classification model will be built by training it using the four flower features (X) and class label (Y).

Model deploying

In lines 12-33, the Gradio library is used to build the user interface as described below:

  • Line 12: a function named iris is created with four arguments that correspond with the numbers and names of features used in training the model.
  • Line 13-14: the predict() function is used to predict the name of the flower and it is assigned to the prediction variable.
  • Line 15: in order for the class labels (i.e. setosa, versicolor, and virginica) to be displayed we will need to use the prediction variable as an argument inside the bracket of data.target_names[prediction].
  • Line 16: the function returns the predicted value
  • Line 18-28: the inputs and the output were labeled for more clarity.
  • Line 31-34: the interface is created using the interface() function and the launch() function is used to display the interface.

If you run the Python application, an external URL will be generated and you can access the web interface in any browser (e.g: 49508.gradio.app) as seen in the screenshot below.

A screenshot of the demo application

You should note that the public URL will expire after 72 hours from the time it was generated. If you want a permanent hosted link, then you can use HuggingFace Spaces to host your Gradio web app as seen in the demo below.

hf_demo.gif

GIF source: Gradio documentation

Conclusion

I hope this tutorial provides you with the fundamentals you need to understand the Gradio library and has helped you get started with Gradio. You can check the complete code for the demo in this GitHub repo or explore the advanced features of Gradio. Thanks for reading!

References

ย 
Share this