Build Powerful Web Apps for Machine Learning in Python with Streamlit

Machine learning and data science have transformed nearly every industry, but a key challenge has always been how to best productionize models and share insights with others. While a data scientist can build highly accurate models, actually integrating those models into user-friendly applications has traditionally required a completely separate web development skillset and tech stack.

However, a fast-growing open-source project called Streamlit is revolutionizing this workflow by allowing data scientists to quickly create powerful web apps for machine learning with simple Python scripts. Since its launch in 2019, Streamlit has exploded in popularity, with the library now receiving over 1.7 million downloads per month and 20,000+ GitHub stars. Let‘s explore what makes Streamlit so compelling and walk through a detailed example of using it to build an interactive ML web app.

The Rise of Streamlit

Founded by Adrien Treuille, Amanda Kelly, and Thiago Teixeira, Streamlit‘s mission is to make data science and machine learning more accessible and collaborative. The founders recognized that while it was easier than ever to build ML models in Python, deploying them remained a huge challenge. Existing web frameworks like Django and Flask required significant front-end coding and didn‘t integrate well with popular data science tools and workflows.

As Treuille shared in a 2019 TechCrunch article, "Streamlit is a single open-source script that runs in a web browser. It‘s a very flexible framework that‘s focused on machine learning and data visualization applications." The key insight was that data scientists already know Python – so why not use Python itself as the web framework?

Since launching, Streamlit has seen tremendous adoption across the data science community. The framework has proven especially popular for:

  • Quick prototyping and iterating on ML models
  • Building internal dashboards and tools
  • Sharing analyses and results with non-technical stakeholders
  • Deploying models for hands-on user testing

A few prominent companies using Streamlit include Uber, Twitter, Stitch Fix, and Dropbox. Incredibly, Streamlit has achieved this growth as a small, independent company, speaking to the strength of its open-source community. In late 2022, Streamlit was acquired by Snowflake for $800 million, a huge validation of the project and its ecosystem.

Why Streamlit for Machine Learning

While tools like Jupyter notebooks and R Shiny have enabled more interactive data science workflows, Streamlit takes things to the next level by making it dead simple to create production-ready, performant web apps with Python. Some of the key benefits include:

  • Perfect for ML/data science workflows: Unlike traditional web frameworks that are designed for software engineers, Streamlit is built from the ground up for data scientists. It integrates seamlessly with popular Python libraries like Pandas, Matplotlib, Scikit-learn, and TensorFlow, allowing you to incorporate your existing ML code and workflows.

  • Simple, intuitive API: With Streamlit, you don‘t need to know Javascript, HTML, or CSS – just Python! The API is highly intuitive, with most apps requiring just a few lines of code. Even the most complicated Streamlit apps are usually under 100 lines of Python.

  • Fast, interactive development: Steamlit‘s unique architecture allows for very fast prototyping. Any time you update and save your Python script, the app automatically refreshes with the latest changes in your web browser. No need to manually recompile or redeploy the app.

  • Built-in caching for performance: One potential downside of the auto-reloading flow is that it re-executes the entire script, which could be slow for certain tasks like loading large datasets or retraining models. Luckily, Streamlit offers a built-in caching mechanism where you can designate certain functions as @st.cache – meaning Streamlit will store the results in a local cache and only rerun the function when the inputs change. This allows for excellent performance even for complex apps.

  • Fully customizable and extensible: While you can build highly functional apps with just Streamlit‘s built-in widgets and components, it‘s also fully customizable. You have the ability to write your own custom CSS, HTML, and Javascript, create custom components, or even extend Streamlit‘s functionality with other Python libraries and frameworks.

Building an Interactive Machine Learning App

To illustrate Streamlit‘s capabilities, let‘s walk through an example of building an interactive web app for a common machine learning use case: predicting iris flower species from measurements.

We‘ll use the famous Iris dataset, which consists of measurements (sepal length, sepal width, petal length, petal width) for 150 iris flowers of 3 different species (setosa, versicolor, virginica). Our app will allow a user to input measurements and see the model‘s predicted species and prediction probability.

Setup and Data Loading

First, make sure you have Streamlit installed:

pip install streamlit

Then import the necessary libraries and load the Iris dataset from scikit-learn:

import streamlit as st 
import pandas as pd
import numpy as np
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

iris = datasets.load_iris()
X = iris.data
y = iris.target

Display App Info and Sidebar

Let‘s add a title and brief description of our app using Streamlit‘s write function. We‘ll also use st.sidebar to add input widgets in a sidebar:

st.write("""
# Iris Flower Prediction App

This app predicts the **Iris flower** species based on user input of sepal length, sepal width, petal length, and petal width. The prediction is made using a Random Forest classifier trained on the classic Iris dataset.
""")

st.sidebar.header(‘User Input Features‘)

App Title and Sidebar

Capture User Inputs

Now let‘s allow users to input iris measurements using sliders in the sidebar, and capture their inputs as a DataFrame:

def user_input_features():
    sepal_length = st.sidebar.slider(‘Sepal length‘, 4.3, 7.9, 5.4)
    sepal_width = st.sidebar.slider(‘Sepal width‘, 2.0, 4.4, 3.4)
    petal_length = st.sidebar.slider(‘Petal length‘, 1.0, 6.9, 1.3)
    petal_width = st.sidebar.slider(‘Petal width‘, 0.1, 2.5, 0.2)
    data = {‘sepal_length‘: sepal_length,
            ‘sepal_width‘: sepal_width,
            ‘petal_length‘: petal_length,
            ‘petal_width‘: petal_width}
    features = pd.DataFrame(data, index=[0])
    return features

df = user_input_features()

st.subheader(‘User Input Parameters‘)
st.write(df)

User Input Sliders

Visualize Feature Distributions

As a nice enhancement, we can add violin plots showing the distributions of each feature across the three iris species:

st.subheader(‘Class Feature Distributions‘)
for feature in [‘sepal_length‘, ‘sepal_width‘, ‘petal_length‘, ‘petal_width‘]:
    plt.figure()
    sns.violinplot(x=‘species‘, y=feature, data=pd.melt(X_df, var_name=‘species‘, value_name=feature))
    st.pyplot(plt.gcf())

This allows the user to see how their input compares to the typical ranges for each species.

Feature Distributions

Train and Evaluate Model

Next, let‘s split our data into train and test sets, train a Random Forest model, and evaluate its performance:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)

y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)

st.subheader(‘Model Performance‘)
st.write(f‘Accuracy: {accuracy:.2f}‘)

feature_importances = pd.Series(clf.feature_importances_, index=iris.feature_names).sort_values(ascending=False)
st.bar_chart(feature_importances)

We display the model‘s accuracy score on the test set as well as a bar chart showing the importance of each feature based on the trained model. The bar chart helps explain which features are most predictive.

Model Performance Metrics

Make Predictions on User Input

Finally, we take the user input, generate predictions, and display the predicted species and probabilities:

prediction = clf.predict(df)
prediction_proba = clf.predict_proba(df)

st.subheader("Prediction")
st.write(iris.target_names[prediction])

st.subheader(‘Prediction Probability‘)
st.write(prediction_proba)

Model Predictions

Deploying your Streamlit App

Once you‘ve developed your Streamlit app, deploying it is incredibly straightforward. Streamlit offers a free Community Cloud hosting platform at share.streamlit.io. To deploy there, simply push your code to a public GitHub repo and then log into Streamlit Cloud and deploy directly from the repo.

For more advanced use cases, Streamlit apps can be deployed on other platforms like Heroku, AWS, or Google Cloud, or self-hosted on a private server. The deployment process typically involves containerizing your app using Docker and then deploying the container to your platform of choice.

Conclusion and Resources

Hopefully this article has conveyed the power and simplicity of using Streamlit for building machine learning web apps. With just a few dozen lines of Python, we were able to build a fully interactive app that loads data, trains a model, visualizes results, and generates predictions based on user input. The ability to incorporate these rich features without a separate front-end stack is a huge productivity boost for data science teams.

Of course, we‘ve only scratched the surface of what‘s possible with Streamlit. The ecosystem is constantly evolving, with new features and third-party components that extend Streamlit‘s functionality for maps, graphs, video processing, and more.

To learn more, I highly recommend checking out these resources:

Also be sure to join the Streamlit community forum to connect with other Streamlit developers, get your questions answered, and stay up to date on the latest advancements.

With Streamlit quickly emerging as the go-to framework for building ML web apps in Python, there‘s never been a better time to add it to your data science toolkit. 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