A Deep Dive Into Building Interactive Machine Learning Web Apps With Streamlit

Introduction

Building interactive web applications to showcase your machine learning models is a great way to make your work accessible and engaging for others. However, web development skills like HTML, CSS, and JavaScript can be a barrier for many data scientists and ML engineers.

Fortunately, tools like Streamlit make it easy to build beautiful, interactive ML web apps with pure Python. Streamlit is an open-source library that allows you to create custom web apps for machine learning and data science projects without needing any web dev experience.

In this tutorial, we‘ll walk through building an interactive ML web app that lets users train and evaluate multiple classification models on a dataset. We‘ll cover key Streamlit concepts like data loading, visualization, user interaction, and dashboarding. By the end, you‘ll be able to create your own ML web apps to impress your colleagues and showcase your projects! Let‘s get started.

Setting Up a Basic Streamlit App

First, make sure you have Streamlit installed:

pip install streamlit

Next, let‘s initialize a basic Streamlit app. Create a new Python file called app.py with the following code:

import streamlit as st

def main(): st.title("ML Web App with Streamlit") st.sidebar.title("Options")

if name == ‘main‘: main()

This sets up a simple app with a main title and sidebar. The st.title and st.sidebar.title functions add text headers, while the sidebar allows us to put interactive widgets that the user can change.

Run the app with:

streamlit run app.py

This will open the app in a new browser tab. Now we‘re ready to start building out the functionality of our ML app!

Loading and Preparing Data

For this example, we‘ll use the classic mushroom classification dataset from the UCI Machine Learning Repository. The data contains information about different mushroom species and whether they are edible or poisonous.

First, let‘s load the data and do some basic preprocessing:

@st.cache
def load_data():
    data = pd.read_csv("mushrooms.csv")
    label = LabelEncoder() 
    for col in data.columns:
        data[col] = label.fit_transform(data[col])
    return data

df = load_data()

This uses Streamlit‘s @st.cache decorator to cache the loaded data, so it doesn‘t have to be reloaded each time the app is updated. We use scikit-learn‘s LabelEncoder to convert the categorical features to integers.

Let‘s also add an option to display the raw data:

if st.sidebar.checkbox("Show raw data"):
    st.subheader("Mushroom Data Set (Encoded)")
    st.write(df)

Building Classification Models

Next, let‘s allow the user to select different classification models to train and evaluate:

def get_classifier(clf_name):
    if clf_name == "Logistic Regression":
        clf = LogisticRegression()
    elif clf_name == "Random Forest":
        clf = RandomForestClassifier()
    else:
        clf = SVC()
    return clf

clf_name = st.sidebar.selectbox("Select classifier", ("Logistic Regression", "Random Forest", "SVC"))

clf = get_classifier(clf_name)

We define the classifiers in a dictionary and use a dropdown select box to let the user choose. The get_classifier function returns the chosen model.

Hyperparameter Selection

To make the model training interactive, let‘s provide options for the user to set key hyperparameters for each model:

if clf_name == "Logistic Regression":
    C = st.sidebar.number_input("C (Regularization parameter)", 0.01, 10.0, step=0.01, key="C_LR")
    max_iter = st.sidebar.slider("Maximum iterations", 100, 500, key="max_iter")

elif clf_name == "Random Forest": n_estimators = st.sidebar.number_input("Number of trees in the forest", 100, 5000, step=10, key="n_estimators") max_depth = st.sidebar.number_input("Maximum depth of the tree", 1, 20, step=1, key="max_depth")

elif clf_name == "SVC": C = st.sidebar.number_input("C (Regularization parameter)", 0.01, 10.0, step=0.01, key="C_SVC") kernel = st.sidebar.radio("Kernel", ("rbf", "linear"), key="kernel") gamma = st.sidebar.radio("Gamma (Kernel coefficient)", ("scale", "auto"), key="gamma")

params = { "Logistic Regression": { "C": C, "max_iter": max_iter }, "Random Forest": { "n_estimators": n_estimators, "max_depth": max_depth }, "SVC": { "C": C, "kernel": kernel, "gamma": gamma } }

Here we use Streamlit widgets like number_input, slider, and radio to provide hyperparameter options depending on the chosen model. These are stored in a params dictionary.

Model Evaluation and Metrics

With the model and hyperparameters chosen, we can now implement a function to evaluate the trained model‘s performance:

def evaluate_model(clf, X_train, X_test, y_train, y_test):
    clf.fit(X_train, y_train)
    accuracy = clf.score(X_test, y_test)
    y_pred = clf.predict(X_test)
    precision = precision_score(y_test, y_pred)  
    recall = recall_score(y_test, y_pred) 
    return accuracy, precision, recall

if st.sidebar.button("Evaluate", key="evaluate"): X_train, X_test, y_train, y_test = train_test_split(df.iloc[:,1:], df.iloc[:,0], test_size=0.3) clf = get_classifier(clf_name) clf.set_params(**params[clf_name]) accuracy, precision, recall = evaluate_model(clf, X_train, X_test, y_train, y_test)

st.write("Classifier:", clf_name)  
st.write("Accuracy:", accuracy.round(2))
st.write("Precision:", precision.round(2))  
st.write("Recall:", recall.round(2))

When the user clicks the "Evaluate" button, the selected model is trained on the data with the specified hyperparameters. The accuracy, precision, and recall scores are computed on the test set and displayed.

Plotting Evaluation Metrics

In addition to the raw scores, it would be nice to visualize the model‘s performance with plots like the confusion matrix, ROC curve, and precision-recall curve. We can add options for the user to select which metrics to plot:

metrics = st.sidebar.multiselect("Select metrics to plot", ("Confusion Matrix", "ROC Curve", "Precision-Recall Curve"))

def plot_metrics(metrics_list): if "Confusion Matrix" in metrics_list: st.subheader("Confusion Matrix") plot_confusion_matrix(clf, X_test, y_test, display_labels=class_names) st.pyplot()

if "ROC Curve" in metrics_list:
    st.subheader("ROC Curve")
    plot_roc_curve(clf, X_test, y_test)
    st.pyplot()

if "Precision-Recall Curve" in metrics_list:
    st.subheader("Precision-Recall Curve")
    plot_precision_recall_curve(clf, X_test, y_test)
    st.pyplot()

The plot_metrics function uses Streamlit‘s pyplot function to display the selected plots inline in the app.

Debugging: plot_roc_curve Import Error

One common issue you may encounter, especially with scikit-learn version 0.22 and earlier, is the following error when trying to plot the ROC curve:

cannot import name ‘plot_roc_curve‘ from ‘sklearn.metrics‘

This error occurs because plot_roc_curve was only added in version 0.23. For earlier versions, you‘ll need to use roc_curve directly:

  
if "ROC Curve" in metrics_list:
    st.subheader("ROC Curve") 
    y_proba = clf.predict_proba(X_test)[:, 1]
    fpr, tpr, _ = roc_curve(y_test, y_proba)
    plt.plot(fpr, tpr)
    plt.xlabel("False Positive Rate") 
    plt.ylabel("True Positive Rate")
    st.pyplot()

This computes the ROC curve data directly using roc_curve and plots it using matplotlib. The resulting plot is then displayed using st.pyplot.

Next Steps

Congratulations, you now have an interactive ML web app that allows users to train and evaluate multiple classification models! Some ideas to expand your app:

  • Allow uploading custom datasets
  • Implement more models like gradient boosting or neural networks
  • Add feature importance plots and other interpretability tools
  • Allow downloading the trained models
  • Deploy your app using Streamlit Sharing or another hosting service

The complete code for this app is available in the GitHub repo linked below. Feel free to use it as a starting point for your own Streamlit ML apps!

Conclusion

In this tutorial, we‘ve seen how Streamlit makes it easy to build interactive machine learning web apps with pure Python. We walked through loading data, setting up ML models, allowing the user to select hyperparameters, and evaluating model performance with metrics and plots.

You should now have a solid foundation for creating your own Streamlit ML apps. The sky is the limit in terms of the features and visualizations you can add! Streamlit‘s detailed documentation and active community provide many more examples and ideas to draw from.

By making machine learning more accessible and interactive, tools like Streamlit have the potential to greatly accelerate the development and adoption of ML applications. Hopefully this tutorial has inspired you to build and share your own models and insights with the world!

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