Machine learning: Build a web app to deploy a machine learning model  with Gradio and Streamlit

Machine learning: Build a web app to deploy a machine learning model with Gradio and Streamlit

Choosing the Right Tool for Your Machine Learning UI Needs: Gradio vs. Streamlit

Gradio vs Streamlit: Which Framework Should You Use?

Gradio and Streamlit are two popular Python frameworks for building web applications. Both frameworks are easy to use and can be used to create a variety of applications, including dashboards, data visualizations, and machine-learning models. However, there are some key differences between the two frameworks that you should consider when choosing which one to use for your project.

What is Gradio?

Gradio is a Python framework for building interactive web UIs for machine learning models. It is designed to be easy to use and to provide a quick and efficient way to prototype and share machine learning models. Gradio is built on top of the popular Plotly library, which means that it can be used to create interactive plots and visualizations.

What is Streamlit?

Streamlit is a Python framework for building web applications for data science and machine learning. It is designed to be easy to use and to provide a quick and efficient way to build dashboards, data visualizations, and machine learning models. Streamlit is built on top of the popular React library, which means that it can be used to create interactive web applications.

What are the key differences between Gradio and Streamlit?

There are a few key differences between Gradio and Streamlit that you should consider when choosing which one to use for your project.

  • Gradio is specifically designed for machine learning models. If you are building a web application for a machine learning model, Gradio is a good choice. Gradio provides a number of features that make it easy to build interactive web UIs for machine learning models, such as support for input and output widgets, automatic model loading, and live predictions.

  • Streamlit is more general-purpose. If you are building a web application that is not specifically for a machine learning model, Streamlit is a good choice. Streamlit provides a wider range of features than Gradio, such as support for multiple input and output widgets, custom styling, and deployment to production.

  • Gradio is easier to learn. Gradio is a simpler framework than Streamlit. This means that it is easier to learn and to get started. If you are new to building web applications, Gradio is a good choice.

  • Streamlit is more powerful. Streamlit is a more powerful framework than Gradio. This means that it can be used to build more complex web applications. If you need to build a complex web application, Streamlit is a good choice.


Here is an example of how to build the same web app for a machine-learning model on both Gradio and Streamlit

We are going to a simple machine-learning app that helps classify images of 525 bird species.

Dataset and Model
If you want to train your how model you can find the dataset here. This is a pre-trained ResNet50 model where I perform transfer learning

This is an example of samples from the dataset :

Environnement
First, you need to install Gradio and Streamlit in your newly created environment if you have created one if not you can use tools like (conda, poetry, pipenv, virtualenv, venv) and then install packages. pip install gradio and pip install streamlit

First, let's begin with Gradio:

Create an app.py file and add importation

import tensorflow as tf
import gradio as gr
import pandas as  pd
import numpy as np

Load model and labels

model = tf.keras.models.load_model('model.h5')
birds_csv = pd.read_csv("archive/birds.csv")

labels = list(set(birds_csv.labels))

Next, create a function classify_image that takes an image as a parameter and preprocess and makes predictions

def classify_image(img):


  # Format the image 
  img = np.array(img)
  img = np.expand_dims(img, axis=0)

  # Predict bird speci
  prediction = model(img)

  # Assign prediction with labels
  prediction = prediction.numpy().tolist()
  prediction = prediction[0]
  confidences = {labels[i]: float(prediction[i]) for i in range(525)}

  return confidences

Finally, create a radio interface and pass the classify_image function,

# Create a gradio interface
gr.Interface(fn=classify_image, 
             inputs=gr.Image(shape=(224, 224)),
             outputs=gr.Label(num_top_classes=10),
             title="BIRDS 525 SPECIES IMAGE CLASSIFICATION").launch()

To run the app simply this command

gradio app.py

There is an example

With Streamlit:

Create a streamlit.py file and add importation:

import streamlit as st
import pandas as pd
import numpy as np
import tensorflow as tf
import cv2
import numpy as np

Define a function to load model

def load_model() :
    model = tf.keras.models.load_model('model.h5')
    return model

And then

if __name__ == '__main__':

    # Get the model
    model = load_model()

    # Load labels
    birds_csv = pd.read_csv("archive/birds.csv")
    labels = list(set(birds_csv.labels))


    st.title('BIRDS 525 SPECIES IMAGE CLASSIFICATION')

    with st.sidebar:
        file = st.file_uploader('Upload An Image', type=['png', 'jpg'])

    if file: 

        with st.sidebar:
            st.write("Your Image")
            st.image(file)

        # Decode image to numpy array
        img = cv2.imdecode(np.frombuffer(file.read(), np.uint8), -1)
        img = np.array(img)


         # Format the image 
        img = cv2.resize(img, (224, 224))
        img = np.expand_dims(img, axis=0)

        # Predict bird speci
        prediction = model(img)

        # Assign prediction with labels
        prediction = prediction[0]
        confidences = {labels[i]: float(prediction[i] * 100) for i in range(525)}

        # Sort the dictionary by values.
        sorted_dictionary = sorted(confidences.items(), key=lambda x: x[1], reverse=True)

        # Get the first 10 elements of the sorted dictionary.
        first_10_elements = sorted_dictionary[:10]

        # Display the most 10 labels
        st.bar_chart(dict(map(lambda x: (x[0], x[1]), first_10_elements)),
                     width=100,
                     height=500)

Run this command to launch the app

streamlit run streamlit.py

This is an example


Which framework should you use?

The best framework for you depends on your specific needs. If you are building a web application for a machine learning model and you want an easy-to-use framework, Gradio is a good choice. If you are building a web application that is not specifically for a machine learning model and you need a powerful framework, Streamlit is a good choice.

Ultimately, the best way to decide which framework is right for you is to try them out and see which one you prefer.

I hope this article has helped you understand the difference between Gradio and Streamlit. Which framework you choose depends on your specific needs.