Streamlit and Machine Learning: Build Interactive Web Apps Easily

Updated on Mar 20,2025

Streamlit offers an intuitive and efficient way to transform data scripts into shareable web applications. Ideal for data scientists and machine learning engineers, Streamlit significantly reduces the complexity of deploying machine learning models, enabling quicker iteration and easier showcasing of results. This article dives into leveraging Streamlit to create interactive interfaces for your machine learning projects, offering a simplified approach to deployment and enhancing model accessibility.

Key Points

Streamlit simplifies the creation of web apps from Python scripts.

It's perfect for creating interactive UIs for machine learning models.

Easily deploy and share your machine learning projects.

Explore image style transfer using Streamlit and TensorFlow Hub.

Learn how to build an image classification web application.

Introduction to Streamlit for Machine Learning

What is Streamlit?

Streamlit is an open-source Python library that makes it easy to create beautiful, custom web applications for machine learning and data science.

It’s designed with simplicity in mind, allowing you to turn data scripts into shareable web apps in a matter of minutes. Unlike traditional web frameworks, Streamlit requires minimal boilerplate code, letting you focus on the data and the model.

Streamlit's core philosophy is to embrace Python scripting. This means you write your application as a standard Python script, and Streamlit automatically handles the complexities of the web interface. This is a Game-changer for data scientists who may not have extensive web development experience. With Streamlit, you can create interactive interfaces, Visualize data, and deploy machine learning models with just a few lines of code.

Why Streamlit for Machine Learning Deployment?

Deploying machine learning models can be a challenging task. It often involves setting up web servers, creating APIs, and designing user interfaces. Streamlit streamlines this process by providing a simple and intuitive way to expose your models to a wider audience. Here are some key benefits:

  • Rapid Prototyping: Quickly create and iterate on your machine learning applications.
  • Ease of Use: No need for extensive web development knowledge. Focus on your models, not the web framework.
  • Interactive Interfaces: Create interactive dashboards and tools for exploring your data and model predictions.
  • Shareability: Easily share your applications with colleagues, clients, or the world.
  • Integration with Popular Libraries: Seamlessly integrates with popular machine learning libraries like TensorFlow, PyTorch, scikit-learn, and more.

Using streamlit for machine learning deployment is more efficient because it automates a lot of complexities that usually requires the expertise of a DevOps engineer. Furthermore, streamlit interfaces can be shared to make machine learning applications more available to the public.

Key Concepts in Streamlit

Before diving into building applications, it’s helpful to understand some key Streamlit concepts:

  • Streamlit Elements: These are the building blocks of your Streamlit application. They include text, images, charts, data tables, buttons, sliders, and more. You can use these elements to create the user interface of your application.
  • Data Caching: Streamlit automatically caches data to improve performance. This means that if your application needs to load the same data multiple times, Streamlit will only load it once and then cache it for future use. This can significantly speed up your application.
  • Interactive Widgets: Streamlit provides a variety of interactive widgets, such as sliders, text inputs, and dropdown menus. These widgets allow users to interact with your application and control the behavior of your machine learning models.
  • Automatic Updates: Streamlit automatically updates your application whenever you change the code. This means that you can see the results of your changes immediately without having to manually refresh the page.

Understanding these core concepts will help you build more complex and interactive Streamlit applications. The goal of streamlit is to enable anyone to turn data into machine learning applications in the most efficient way.

Building an Image Style Transfer Web Application with Streamlit

Step-by-Step Guide to Image Style Transfer

Let's walk through building a basic image style transfer web application using Streamlit and TensorFlow Hub. Image style transfer is a technique that allows you to apply the artistic style of one image to another. This is a fun and creative way to explore the capabilities of machine learning.

Step 1: Setting Up Your Environment

First, make sure you have Streamlit and TensorFlow installed. If not, you can install them using pip:

pip install streamlit tensorflow tensorflow-hub

Step 2: Importing Libraries

Create a new Python file (e.g., style_transfer_app.py) and import the necessary libraries:

import streamlit as st
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
from PIL import Image

Step 3: Loading the Style Transfer Model

TensorFlow Hub provides pre-trained style transfer models that you can easily load into your Streamlit application.

Load the model using the following code:

model = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')

This code downloads the pre-trained model from TensorFlow Hub and loads it into memory.

Step 4: Creating the Streamlit Interface

Now, let's create the user interface for your application. Add the following code to your Python file:

st.title('Image Style Transfer')

content_image = st.file_uploader('Choose the content image', type=['jpg', 'jpeg', 'png'])
style_image = st.file_uploader('Choose the style image', type=['jpg', 'jpeg', 'png'])

if content_image is not None and style_image is not None:
    content_image = Image.open(content_image).convert('RGB')
    style_image = Image.open(style_image).convert('RGB')

    st.image([content_image, style_image], width=300, caption=['Content Image', 'Style Image'])

    if st.button('Transfer Style'):
        content_tensor = tf.convert_to_tensor(np.array(content_image)[np.newaxis, :])
        style_tensor = tf.convert_to_tensor(np.array(style_image)[np.newaxis, :])

        stylized_image = model(content_tensor, style_tensor)[0]
        stylized_image = tf.clip_by_value(stylized_image, 0, 1)
        stylized_image = Image.fromarray(np.uint8(stylized_image[0]*255))

        st.image(stylized_image, caption='Stylized Image')

This code creates a Streamlit application with the following features:

  • A title for the application.
  • File uploaders for the content and style images.
  • Displays the uploaded images.
  • A button to trigger the style transfer.
  • Displays the Stylized image after the style transfer is complete.

Step 5: Running the Streamlit Application

Save your Python file and run the Streamlit application using the following command:

streamlit run style_transfer_app.py

This will open your application in a web browser. You can now upload your content and style images and click the “Transfer Style” button to generate the stylized image.

The code above will load images and transfer styles in your machine learning applications. Here is a summary of the functions used:

Function Description
st.title() Sets the title of the Streamlit app.
st.file_uploader() Creates a file uploader widget to allow users to upload files.
Image.open() Opens an image file using the PIL (Pillow) library.
st.image() Displays an image in the Streamlit app.
tf.convert_to_tensor() Converts a NumPy array or other Python object to a TensorFlow tensor.
np.array() Converts a Python object (in this case, a PIL Image) to a NumPy array.
model(content_tensor, style_tensor) Applies the style transfer model to the content image, using the style from the style image.
tf.clip_by_value() Clips the tensor values to a specified min and max, ensuring that the image values are within the valid range.
Image.fromarray() Creates a PIL Image from a NumPy array.
np.uint8() Converts the NumPy array to an unsigned 8-bit integer data type, which is commonly used for image data.

The steps above enable the creation of a streamlit interface, a style transfer model, which can then be easily shared as a machine learning application.

How to Use Streamlit for Different Machine Learning Tasks

Building a Simple Image Classifier Interface

Let’s explore how to build a simple image classification web app. This process involves taking an existing trained model and creating a user-friendly interface for interacting with it. This is a valuable way to showcase and test your models.

Step 1: Preparing Your Image Classification Model

Before building the Streamlit application, you need a trained image classification model. For simplicity, let’s assume you have a model that takes an image as input and outputs a predicted class label. This model can be built using libraries such as TensorFlow or PyTorch.

Step 2: Loading Your Model

Load your trained model into your Python script. For example, if you’re using TensorFlow, you might load it like this:

model = tf.keras.models.load_model('your_model.h5')

Step 3: Creating the Streamlit Interface

Create the user interface with Streamlit. Add the following code to your script:

st.title('Image Classifier')

uploaded_file = st.file_uploader("Choose an image...", type="jpg")

if uploaded_file is not None:
    image = Image.open(uploaded_file).convert('RGB')
    st.image(image, caption='Uploaded Image.', use_column_width=True)
    st.write("Classifying...")

    img_array = tf.keras.preprocessing.image.img_to_array(image)
    img_array = tf.expand_dims(img_array, 0) # Create a batch

    predictions = model.predict(img_array)
    class_names = ['cat', 'dog', 'bird'] # Example classes
    score = tf.nn.softmax(predictions[0])

    st.write("This image most likely belongs to {} with a {:.2f} percent confidence.".format(
        class_names[np.argmax(score)], 100 * np.max(score)
    ))

This code does the following:

  • Creates a title for the application.
  • Provides a file uploader for users to upload images.
  • Displays the uploaded image.
  • Classifies the image using the loaded model.
  • Displays the predicted class and confidence score.

Step 4: Running the Application

Save your script and run the application:

streamlit run your_script.py

Now, you can upload an image and see the model’s prediction in real time.

Key Elements for Image Classification

This interface for image classification requires image preprocessing, for both the input data and the image.

Process Description
`st.file_uploader(

Most people like