Streamlit: Quickly Turn Your Machine Learning Models into Web Apps

Introduction

Deploying machine learning models into interactive web applications has traditionally required significant web development skills. Data scientists would have to learn frontend frameworks, wrangle with web servers, and rewrite their models to integrate with backend APIs. This process was time-consuming and took data scientists away from their core competency of building effective ML models.

Enter Streamlit – an open-source Python library that makes it incredibly easy to build interactive web apps for machine learning and data science. With Streamlit, you can take your existing ML models and data pipelines, add a few lines of code, and spin up a fully-functional web app in minutes. No HTML, CSS, or JavaScript required.

In this post, we‘ll dive into what makes Streamlit such a powerful tool for data scientists and ML engineers who want to quickly productionize and share their work. We‘ll walk through installing Streamlit, building a sample ML app, and deploying it live on the web. By the end, you‘ll have a solid foundation to start creating your own ML web apps using Streamlit and Python.

What is Streamlit?

At its core, Streamlit is a Python library that provides a simple API for building interactive web applications with data and ML models. It allows you to write an app the same way you write a normal Python script – interspersing application elements alongside your code.

Streamlit then takes your script, executes it from top to bottom, and translates it into a web app on the fly. Any time the script is updated and saved, the application automatically refreshes with the changes. This makes iteration extremely fast.

Some key features of Streamlit include:

  • No frontend experience required. You only need to know Python.
  • Simple, clean API for displaying text, charts, tables, and interactive widgets
  • Live code and app updates for quick iteration and prototyping
  • Built-in caching for fast performance when rerunning scripts
  • Support for rich media like images, video, and audio
  • Ability to record a screencast of your app flow for easier sharing
  • One-click deployment to Streamlit‘s hosted platform or your own infrastructure

Streamlit has seen rapid adoption by the data science community, with over 20,000 GitHub stars and used by companies ranging from startups to the Fortune 500. Its focused yet flexible feature set makes it ideal for both quick prototyping and building production-grade ML applications.

Getting Started with Streamlit

Installing Streamlit

First things first – to use Streamlit, you‘ll need to install it in your Python environment. You can install the latest release of Streamlit using pip:

pip install streamlit

Alternatively, if you use Anaconda, you can install Streamlit from the conda-forge channel:

conda install -c conda-forge streamlit

That‘s it! You‘re now ready to start building Streamlit apps.

Your First Streamlit App

To get a feel for how Streamlit works, let‘s create a simple "Hello, World!" application. Open up your favorite Python IDE and create a new file called hello.py with the following code:

import streamlit as st

st.write(‘Hello, World!‘)

Now run your app with the following command:

streamlit run hello.py

This will start a local server and open your default web browser pointing to your new app. You should see the text "Hello, World!" displayed on the page.

Congratulations, you just deployed your first Streamlit app! Let‘s break down what‘s happening:

  1. The first line imports the streamlit library, which we alias as st for brevity.
  2. We then use one of Streamlit‘s most basic commands, st.write(), to write the text "Hello, World!" to the app.
  3. When you run the app using streamlit run, Streamlit executes the Python script from top to bottom and translates each command into an element on the web page.

Of course, this is just the tip of the iceberg. Streamlit provides dozens of commands for creating rich text, data visualizations, tables, forms, and interactive widgets. We‘ll see more of those in action as we build our ML app.

Building an ML Web App with Streamlit

To demonstrate Streamlit‘s capabilities, let‘s build an interactive web app for a common ML use case: exploring a dataset and building a predictive model. We‘ll use the classic Iris flower dataset which consists of measurements for three species of Iris flowers.

Loading and Visualizing the Data

First, let‘s load the Iris dataset and display some basic information about it in our Streamlit app. Update your hello.py file with the following code:

import streamlit as st
import pandas as pd
from sklearn import datasets

iris = datasets.load_iris()
X = pd.DataFrame(iris.data, columns=iris.feature_names)
Y = pd.Series(iris.target, name=‘class‘)

st.title("Iris Dataset Explorer")
st.write("""
This app explores the Iris dataset which contains measurements 
for three species of Iris flowers. Use the controls below to 
filter the data and train a classifier.
""")

st.header("Raw Data")
st.write(pd.concat([X, Y], axis=1))

st.header("Data Summary")
st.write(X.describe())

Running this updated script, you should see the app display the title, description, raw data table, and summary statistics for the Iris dataset. Streamlit‘s st.write() command automatically formats the output based on the type of input – rendering text, tables, and data frames as appropriate.

Adding Interactive Widgets

Next, let‘s add some interactivity to our app by letting the user filter the dataset. Streamlit provides a variety of input widgets like sliders, checkboxes, and dropdowns that automatically update the application state when changed.

Add the following code to your script after the raw data section:

st.sidebar.header("Filtering Options")

species = st.sidebar.multiselect(
    "Select the Iris Species",
    options=sorted(Y.unique()),
    default=sorted(Y.unique())
)

min_sepal_length = st.sidebar.slider(
    "Minimum Sepal Length",
    float(X.min()[0]), float(X.max()[0])
)

selected_data = X[(X[‘sepal length (cm)‘] >= min_sepal_length) & (Y.isin(species))]
st.write(f"Selected {len(selected_data)} rows out of {len(X)}")
st.write(selected_data)

This code adds two widgets to the application sidebar:

  1. A multiselect dropdown for filtering by Iris species
  2. A slider for selecting a minimum sepal length

Both widgets automatically trigger callbacks to subset the data frame whenever their values change. The selected rows are then displayed back to the user in real-time.

This interactive filtering capability would be much more difficult to implement using traditional web frameworks, but with Streamlit it only takes a few lines of code. Being able to rapidly prototype interactions like this is one of Streamlit‘s killer features.

Training and Visualizing a Model

Finally, let‘s train a simple logistic regression model on the filtered dataset and visualize its predictions. Add this code to the end of your script:

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

model = LogisticRegression()
X_train, X_test, y_train, y_test = train_test_split(
    selected_data, Y[selected_data.index], test_size=0.2
)

model.fit(X_train, y_train)
predictions = model.predict(X_test)

accuracy = accuracy_score(y_test, predictions)
st.write(f"Accuracy: {accuracy:.2f}")

st.header("Confusion Matrix")
from sklearn.metrics import plot_confusion_matrix
plot_confusion_matrix(model, X_test, y_test)
st.pyplot()

This snippet first splits the selected data into train and test sets, then trains a logistic regression model. It prints the accuracy score and displays an interactive confusion matrix using Sklearn‘s plotting utilities and Streamlit‘s st.pyplot() command.

And with that, our interactive Iris classification app is complete! You can run the full script and explore the dynamic visualizations and widgets we created. The complete flow looks something like this:

  1. View summary statistics and raw data
  2. Filter data by species and sepal length
  3. Train model on filtered data
  4. View model accuracy and confusion matrix
  5. Change filters and retrain model
  6. Repeat

Being able to intuitively build and share a flow like this – without any web development – is incredibly powerful for both prototyping and communicating results.

Deploying Your Streamlit App

Once you‘ve built your Streamlit app, the next step is to deploy it so others can use it. Streamlit offers a few different deployment options depending on your needs.

Streamlit Sharing

The easiest way to deploy your app is on Streamlit‘s own sharing platform. You can sign up for a free community account at streamlit.io/sharing and deploy your app with a few clicks.

To deploy your app, first make sure it‘s pushed to a public GitHub repo. Then log into your Streamlit sharing account, click "New app", and select the repo, branch, and file name for your app. Streamlit will automatically deploy the app and give you a public URL you can share with others.

Streamlit sharing is great for quickly deploying public apps without any infrastructure setup. However, it has some limitations on resource usage and customization.

Self-Hosted Deployment

For more flexibility and control, you can deploy Streamlit apps on your own infrastructure using platforms like Heroku, AWS, or Google Cloud. The process typically involves:

  1. Adding a few configuration files to your repo (e.g. requirements.txt, Procfile)
  2. Creating a new app on your platform of choice
  3. Linking the app to your GitHub repo
  4. Configuring any necessary buildpacks or environment variables
  5. Deploying the app

This process will differ slightly depending on your hosting platform, but Streamlit maintains deployment guides for popular services in its documentation.

Self-hosting gives you complete control over your app‘s performance, security, and customization. It‘s a good option for production applications or sensitive internal tools. However, it does require more setup and maintenance than Streamlit sharing.

Why Streamlit?

We‘ve seen how Streamlit simplifies the process of building and sharing web apps, but why else might you choose it over other frameworks? Here are a few key benefits:

  • Python-first: If you‘re already working with Python for data science and ML, Streamlit fits naturally into your existing workflow. You don‘t need to context switch to JavaScript or learn new frontend frameworks.
  • Fast prototyping: Streamlit‘s simple API and live-reloading model enable incredibly fast iteration. You can prototype new features and interactions in minutes rather than hours or days. This is a huge productivity boost when exploring new datasets or models.
  • Easy sharing: Streamlit‘s built-in sharing platform and deployment guides make it straightforward to get your apps in front of stakeholders. This accelerates the feedback loop and helps build alignment.
  • Flexible layouts: While Streamlit provides a default vertical app layout, you can customize it with columns, sidebars, expanders, and more. This allows you to build surprisingly sophisticated interfaces without any CSS.
  • Rich visualizations: Streamlit has built-in support for popular charting libraries like Matplotlib, Plotly, Altair, and Bokeh. It also provides interactive widgets for tables, maps, and media. Displaying complex data is a breeze.
  • Interoperability: Streamlit plugs seamlessly into the Python data science ecosystem. You can use it with Pandas, Numpy, Scikit-Learn, TensorFlow, PyTorch, and just about any other library. This lets you leverage your existing skills and tools.

Of course, Streamlit isn‘t perfect for every use case. If you need complete customization over your app‘s appearance or behavior, you may want to use a more flexible framework like Dash or a frontend JS library. And for enterprise apps that require advanced security, user management, and DevOps pipelines, you‘ll likely want to combine Streamlit with other tools.

But for data scientists and ML practitioners who want to quickly build interactive apps, Streamlit is hard to beat. Its focused API, Python-native approach, and built-in sharing make it a delight to use. Give it a try on your next project – you may be surprised how far you can get with just a few lines of code!

Example Streamlit Apps

To see what‘s possible with Streamlit, check out these example apps built by the community:

You can find dozens more examples on the Streamlit Gallery page. They‘re great for inspiration or as a starting point for your own apps.

Conclusion

In this post, we covered how Streamlit enables data scientists and ML practitioners to quickly turn their Python models into interactive web apps. We walked through the key features of Streamlit, how to install it, and built a sample app for exploring the Iris dataset and training a classifier.

We also discussed the benefits of Streamlit, like its Python-native API, fast prototyping capabilities, and simple sharing and deployment. And we looked at some example apps built by the Streamlit community.

Hopefully you now have a solid foundation to start building your own Streamlit apps. Whether you‘re prototyping a new model, exploring a dataset, or sharing results with stakeholders, Streamlit provides a fast and intuitive way to create interactive apps with just a few lines of Python. Give it a try and see how much you can streamline your workflow.

Happy Streamlit-ing!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts