Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
How to Prepare Data Before Deploying a Machine Learning Model?
Next article icon

Python – Create UIs for prototyping Machine Learning model with Gradio

Last Updated : 08 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Gradio is an open-source python library which allows you to quickly create easy to use, customizable UI components for your ML model, any API, or any arbitrary function in just a few lines of code. You can integrate the GUI directly into your Python notebook, or you can share the link to anyone.
Requirements : 
 

 

Example : 
 

We can create interfaces with Gradio using gradio.Interface() function. 
gradio.Interface(self, fn, inputs, outputs, examples=None, live=False, 
         capture_session=False, title=None, description=None)
Parameters : 
 

  • fn: (Callable)the function to wrap an interface.
  • inputs: (Union[str, List[Union[str, AbstractInput]]]) a single Gradio input component, or list of Gradio input components.
  • outputs: (Union[str, List[Union[str, AbstractOutput]]]) a single Gradio output component, or list of Gradio output components.
  • live: (bool) whether the interface should automatically reload on change.
  • capture_session: (bool) if True, captures the default graph and session (needed for Tensorflow 1.x)
  • title: (str) a title for the interface; if provided, appears above the input and output components.
  • description: (str) a description for the interface; if provided, appears above the input and output components.
  • examples: (List[List[Any]]) sample inputs for the function; if provided, appears below the UI components and can be used to populate the interface. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component.

UI for the interface can be generated by gradio.Interface, launch() function. 
gradio.Interface.launch(self, share=False)
Parameters : 
 

share: (bool) - whether to create a publicly shareable link from your computer for the interface.

There are several Input and Output Component given for the inputs and outputs parameter of gradio.Interface().
 

Input Components Output Components
Microphone Textbox Slider Checkbox CheckboxGroup Radio Dropdown Image Sketchdown Webcam Textbox Label Image Image KeyValues

Code: function which returns the factorial of a number. 
 

Python3




def factorial(integer):
    """ Returns factorial of the given integer"""
    n = int(integer)
    if n<=1:
        return 1
    fact=1
    for i in range(1, n+1):
        fact*=i
    return fact
 
 

Now, to wrap this function with gradio interface write following code in the same file.
 

Python3




import gradio
gradio.Interface(factorial, inputs="text", outputs="text").launch(share=True)
 
 

When you run the above code cells in a jupyter notebook. It will generate a UI like this: 
 

You can also copy the link and share that to anyone, it will open the same UI in the browser. Now, we’ll show you how to make an interface for a Machine Learning model. 
For the demo, we’ll load a pre-trained Inception Net Image Classification model with tensorflow. Since this is an Image Classification model we’ll use Image input interface. We’ll output a dictionary of labels and their corresponding confidence scores with the Label output interface.
Code: 
 

Python3




# imported necessary libraries
import gradio as gr
import tensorflow as tf
import numpy as np
import requests
 
# loading the model
inception_net = tf.keras.applications.InceptionV3()
 
# Download human-readable labels.
response = requests.get("https://git.io/JJkYN")
labels = response.text.split("\n")
 
def classify_image(image):
    """ Returns a dictionary with key as label and values
    as the predicted confidence for that label"""
    # reshaping the image
    image = image.reshape((-1, 299, 299, 3))
    # preprocessing the image for inception_v3
    image = tf.keras.applications.inception_v3.preprocess_input(image)
    # predicting the output
    prediction = inception_net.predict(image).flatten()
    return {labels[i]: float(prediction[i]) for i in range(1000)}
 
# initializing the input component
image = gr.inputs.Image(shape = (299, 299, 3))
# initializing the output component
label = gr.outputs.Label(num_top_classes = 3)
 
# launching the interface
gr.Interface(fn = classify_image, inputs = image,
             outputs = label, capture_session = True).launch()
 
 

When you run the above code cell it will generate the UI like this: 
 

Here you can drag and drop the image in the left section of UI and click submit you will get the result like: 
 

Also if you copy the link and paste it in your browser, your interface will look like this: 
 

It is not localhost so you can open the same link on any device. 
For more information about input and output components checkout the Gradio’s documentation.
Resource : Gradio’s documentation
 



Next Article
How to Prepare Data Before Deploying a Machine Learning Model?
author
hritikgupta7080
Improve
Article Tags :
  • AI-ML-DS
  • Machine Learning
  • python
  • Python Framework
Practice Tags :
  • Machine Learning
  • python

Similar Reads

  • Machine Learning Tutorial
    Machine learning is a branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data without being explicitly programmed for every task. In simple words, ML teaches the systems to think and understand like humans by learning from the data. It ca
    5 min read
  • Prerequisites for Machine Learning

    • Python for Machine Learning
      Welcome to "Python for Machine Learning," a comprehensive guide to mastering one of the most powerful tools in the data science toolkit. Python is widely recognized for its simplicity, versatility, and extensive ecosystem of libraries, making it the go-to programming language for machine learning. I
      6 min read
    • SQL for Machine Learning
      Integrating SQL with machine learning can provide a powerful framework for managing and analyzing data, especially in scenarios where large datasets are involved. By combining the structured querying capabilities of SQL with the analytical and predictive capabilities of machine learning algorithms,
      6 min read
    • Getting Started with Machine Learning

      • Advantages and Disadvantages of Machine Learning
        Machine learning (ML) has revolutionized industries, reshaped decision-making processes, and transformed how we interact with technology. As a subset of artificial intelligence ML enables systems to learn from data, identify patterns, and make decisions with minimal human intervention. While its pot
        3 min read
      • Why ML is Important ?
        Machine learning (ML) has become a cornerstone of modern technology, revolutionizing industries and reshaping the way we interact with the world. As a subset of artificial intelligence (AI), ML enables systems to learn and improve from experience without being explicitly programmed. Its importance s
        4 min read
      • Real- Life Examples of Machine Learning
        Machine learning plays an important role in real life, as it provides us with countless possibilities and solutions to problems. It is used in various fields, such as health care, financial services, regulation, and more. Importance of Machine Learning in Real-Life ScenariosThe importance of machine
        13 min read
      • What is the Role of Machine Learning in Data Science
        In today's world, the collaboration between machine learning and data science plays an important role in maximizing the potential of large datasets. Despite the complexity, these concepts are integral in unraveling insights from vast data pools. Let's delve into the role of machine learning in data
        9 min read
      • Top Machine Learning Careers/Jobs
        Machine Learning (ML) is one of the fastest-growing fields in technology, driving innovations across healthcare, finance, e-commerce, and more. As companies increasingly adopt AI-based solutions, the demand for skilled ML professionals is Soaring. This article delves into the Type of Machine Learnin
        10 min read
      geeksforgeeks-footer-logo
      Corporate & Communications Address:
      A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
      Registered Address:
      K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
      GFG App on Play Store GFG App on App Store
      Advertise with us
      • Company
      • About Us
      • Legal
      • Privacy Policy
      • In Media
      • Contact Us
      • Advertise with us
      • GFG Corporate Solution
      • Placement Training Program
      • Languages
      • Python
      • Java
      • C++
      • PHP
      • GoLang
      • SQL
      • R Language
      • Android Tutorial
      • Tutorials Archive
      • DSA
      • Data Structures
      • Algorithms
      • DSA for Beginners
      • Basic DSA Problems
      • DSA Roadmap
      • Top 100 DSA Interview Problems
      • DSA Roadmap by Sandeep Jain
      • All Cheat Sheets
      • Data Science & ML
      • Data Science With Python
      • Data Science For Beginner
      • Machine Learning
      • ML Maths
      • Data Visualisation
      • Pandas
      • NumPy
      • NLP
      • Deep Learning
      • Web Technologies
      • HTML
      • CSS
      • JavaScript
      • TypeScript
      • ReactJS
      • NextJS
      • Bootstrap
      • Web Design
      • Python Tutorial
      • Python Programming Examples
      • Python Projects
      • Python Tkinter
      • Python Web Scraping
      • OpenCV Tutorial
      • Python Interview Question
      • Django
      • Computer Science
      • Operating Systems
      • Computer Network
      • Database Management System
      • Software Engineering
      • Digital Logic Design
      • Engineering Maths
      • Software Development
      • Software Testing
      • DevOps
      • Git
      • Linux
      • AWS
      • Docker
      • Kubernetes
      • Azure
      • GCP
      • DevOps Roadmap
      • System Design
      • High Level Design
      • Low Level Design
      • UML Diagrams
      • Interview Guide
      • Design Patterns
      • OOAD
      • System Design Bootcamp
      • Interview Questions
      • Inteview Preparation
      • Competitive Programming
      • Top DS or Algo for CP
      • Company-Wise Recruitment Process
      • Company-Wise Preparation
      • Aptitude Preparation
      • Puzzles
      • School Subjects
      • Mathematics
      • Physics
      • Chemistry
      • Biology
      • Social Science
      • English Grammar
      • Commerce
      • World GK
      • GeeksforGeeks Videos
      • DSA
      • Python
      • Java
      • C++
      • Web Development
      • Data Science
      • CS Subjects
      @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
      We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
      Lightbox
      Improvement
      Suggest Changes
      Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
      geeksforgeeks-suggest-icon
      Create Improvement
      Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
      geeksforgeeks-improvement-icon
      Suggest Changes
      min 4 words, max Words Limit:1000

      Thank You!

      Your suggestions are valuable to us.

      What kind of Experience do you want to share?

      Interview Experiences
      Admission Experiences
      Career Journeys
      Work Experiences
      Campus Experiences
      Competitive Exam Experiences