A complete guide on feature selection techniques with Python code
2022-06-03
Understanding Contiguous vs Non-Contiguous Tensors in PyTorch
2022-06-15
Show all

Deploying and sharing Machine Learning projects easily using Gradio

7 mins read

Students or Professionals from other streams, like business studies, practice and excel in data science. But when it comes to the deployment of models and representation, developing UI and the backend takes quite more effort than building machine learning models. It nearly requires the knowledge that a software engineer has, you have to write long lines of code and much amount of energy is wasted. But deploying the ML models and creating a user interface to represent the finished model to clients is important.

We have multiple libraries built to solve this problem, and one of them is Gradio —a python library that helps generate UI for your complete model representation in a quick and easy manner. In this tutorial, we will explore the Gradio library and how it can be used in Machine learning and Image Classification problems.

What is Gradio?

Gradio is a free and open-source python library. We can quickly and easily create UI interfaces within our python notebook, or share with anyone with just a few lines of code and demonstrate our finished model results. Gradio helps quickly create customizable UI components within colab, Jupyter notebook or scripts and around TensorFlow or PyTorch models, or even arbitrary Python functions.

Setup

Gradio installation is fast and easy to set up. You can install Gradio using the pip command.

pip install gradio

Once Installed, import gradio to your python notebook.

import gradio as gr 

And here we go ready to use gradio and create the beautiful UI interface. Now, how do we create an interface?

Creating an Interface

gradio.interface () function is used to create interfaces that have input, output, and callable function as important parameters. Let’s go with a simple example, I will create an Interface where we will input a name of a person in text format and output the function to greet him.

#define a function to process your input and output
def greet(name):
   return "Hello 👋: " + name + "!"

After defining the function, create an interface and specify the parameters for the callable function, input, and output. So far we have only created an interface instance. How do we display it?
launch() method is used to display the interface. We can use the external URL generated to easily share and run the interface in the browser. [Running on External URL: https://17129.gradio.app ]

#create interface object
gui = gr.Interface(fn=greet, #callable function
                   inputs="text", #input format
                   outputs="text") #output format
#display the interface
gui.launch()

When we have complex functions with multiple parameters, we can add multiple entries in input simply by configuring the objects, below example has 2 text input objects and 1 output object.

#define a function to process your input and output
def greet(fname ,lname):
   return "Hello 👋: " + fname + " " + lname + "!"#create input and output objects
#input object1
input1 = gr.inputs.Textbox(placeholder="Enter First Name")
#input object 2
input2 = gr.inputs.Textbox(placeholder="Enter Last Name")
#output object
output = gr.outputs.Textbox() 
#create interface
gui = gr.Interface(fn=greet,
                   inputs=[input1, input2],
                   outputs=[output])

Gradio is simply awesome, we can customize the inputs and outputs entries with gradio easily. We can create textboxes, radio buttons, checkboxes, Images, video or audio, dropdown lists, slide bars, and many more. Even the image interface has multiple options to edit images. If you are interested in using these components, here’s a link to the code.

Machine Learning Example

Now that we have learned and understand the basics of how to use gradio, Let’s see how Gradio works with a few machine learning examples.

Linear Regression:
Predicting the score of a student based on the number of hours they study.

import gradio as gr
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import accuracy_score

#load the dataset to pandas dataframe
URL = "http://bit.ly/w-data"
student_data = pd.read_csv(URL)

#Prepare data
X = student_data.copy()
y = student_data['Scores']
del X['Scores']

#create a machine learning model and train it
lineareg = LinearRegression()
lineareg.fit(X,y)
print('Accuracy score : ',lineareg.score(X,y),'\n')

#function to predict the input hours
def predict_score(hours):
    hours = np.array(hours) #process input 
    pred_score = lineareg.predict(hours.reshape(-1,1)) #prediction
    return np.round(pred_score[0], 2)


input = gr.inputs.Number(label='Number of Hours studied')
output = gr.outputs.Textbox(label='Predicted Score')

gr.Interface( predict_score,
              input,
              output,live=True).launch();

Converting RGB image to sketch using OpenCV

#import libraries
import gradio as gr
import cv2 #to work on image processing
import gradio as gr #create UI to display images and test the function
#function to perform image processing to convert rgb image to sketch

def convert_photo_to_Sketch(image):
  img = cv2.resize(image, (256, 256))

  #convert image to RGB from BGR
  RGB_img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

  #convert imge to grey
  grey_img=cv2.cvtColor(RGB_img, cv2.COLOR_BGR2GRAY)

  #invert grey scale image
  invert_img=255-grey_img

  #Gaussian fun to blur the image
  blur_img=cv2.GaussianBlur(invert_img, (21,21),0)

  #invert the blur image
  inverted_blurred_img = 255 - blur_img

  #skecth the image
  sketch_img=cv2.divide(grey_img,inverted_blurred_img, scale=256.0)
  rgb_sketch=cv2.cvtColor(sketch_img, cv2.COLOR_BGR2RGB)
  
  #return the final sketched image
  return rgb_sketch

imagein = gr.inputs.Image(label='Original Image')
imageout =  gr.outputs.Image(label='Sketched Image',type='pil')

gr.Interface(fn=convert_photo_to_Sketch, inputs=imagein, outputs=imageout,title='Convert RGB Image to Sketch').launch();

Image Classification

try:
  #used model trained using vgg16 as it performed well on both train and test data
  labels = ['Daisy','Dadelion','Rose','Sunflower','Tulip'] #classes

  def classify_image(inp):
    img = inp.reshape((-1,224,224,3)) #reshape input image
    prediction = model_from_vgg16.predict(img).flatten() #prediction
    return {labels[i]: float(prediction[i]) for i in range(5)} #return classes

  image = gr.inputs.Image(shape=(224, 224))
  label = gr.outputs.Label(num_top_classes=1)

  gr.Interface(fn=classify_image, inputs=image, outputs=label, capture_session=True).launch(debug=True,share=True)

except KeyboardInterrupt:
      # do nothing here
      pass

Here I have implemented a CNN model using transfer learning on the VGG16 pre-trained model. The model recognizes the images from five classes [‘Daisy’, ’Dandelion’, ’Rose’, ’Sunflower’, ’Tulip’]. The try-except block around the code to create and display the interface helps ignore the keyboard interrupt runtime error when we manually stop the radio. To check the complete code check this github repro.

Few helpful function parameters that make Gradio more flexible :

  • title = ‘Title for Your Interface’, parameter in interface() lets you assign a title to the interface above the input and output components.
  • layout (str ), the parameter for interface() lets you arrange the components ‘horizontal’ or ‘vertical’ form.
  • debug=True, the parameter for launch() helps you debug the code with errors.
  • share = True, the parameter for launch() helps create a publicly shareable link for your interface
  • inbrowser =True, the parameter for launch() allows to automatically launch the interface in a new tab on the default browser

We can also create hosted version of an interface i.e get a permanent link using the github repo. More info is available here.

Conclusion

Hope this short tutorial gave you a comprehensive overview of the Gradio library and how to use it. You can explore advanced features on gradio. If you have any questions, please do write them in the comments.

Source:

https://medium.com/@kalyaniavhale7/tutorial-on-gradio-library-ecb8055923a1

Amir Masoud Sefidian
Amir Masoud Sefidian
Machine Learning Engineer

Comments are closed.