Python Engineer

Free Python and Machine Learning Tutorials

Become A Patron and get exclusive content! Get access to ML From Scratch notebooks, join a private Slack channel, get priority response, and more! I really appreciate the support!

Build A Beautiful Machine Learning Web App With Streamlit And Scikit-learn

03 Jun 2020

In this tutorial we build an interactive machine learning app with Streamlit and Scikit-learn to explore different datasets and classifier. This tutorial should demonstrate how easy interactive web applications can be build with Streamlit. Streamlit lets you create beautiful apps for your machine learning projects with simple Python scripts. See official Streamlit website for more info. As a bonus, you will also learn how we can implement Machine Learning classification pipelines using Scikit-learn.

You can find the code and a Preview gif on GitHub.

Installation

Just install with pip (I recommend to use a virtual environment)

pip install streamlit

For our project we also need these dependencies

pip install scikit-learn pip install matplotlib

Run the App

After installation I recommend to have a look at the official example app by running

streamlit hello

To run our own script we have to run

streamlit run file_name.py

Start Implementing and Add Widgets

With streamlit we can create beautiful UI widgets with just a few lines of code. Here are some example widgets. Have a look at the official docs to see all possibilities.

import streamlit as st st.title('Streamlit Example') # use markdown syntax st.write(""" # Explore different classifier and datasets Which one is the best? """) # selectbox (move it to the sidebar with .sidebar) dataset_name = st.sidebar.selectbox( 'Select Dataset', ('Iris', 'Breast Cancer', 'Wine') ) # widgets can be assigned to variables, # which obtain the value of the selection K = st.sidebar.slider('K', 1, 15) # plot fig = plt.figure() plt.scatter(x1, x2) st.pyplot()

Data Flow and Caching

Streamlit reruns your Python script from top to bottom whenever the user interacts with the widgets. However, to stay fast and performant, streamlit has integrated some intelligent caching mechanisms. Find out more here.