Anthony Corletti
Published on

ML with StreamLit

Authors

Building lightweight ML applications with python, pandas, streamlit, and scikit-learn is a awesome.

Let's run through a simple example app to illustrate this.

Install necessary requirements first.

pip install streamlit pandas scikit-learn

Here's the app with inline explanations.

# ml-app.py
# import libs
import streamlit as st
import pandas as pd
from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
st.write("""
# A Simple Iris Flower Prediction App
This app predicts the iris flower type!
""")
st.sidebar.header("User Input Parameters")
# this basically is inputting features of a flower observation into a dataframe
def user_input_features():
sepal_length = st.sidebar.slider("Sepal length", 4.3, 7.7, 5.4)
sepal_width = st.sidebar.slider("Sepal width", 2.0, 4.3, 3.4)
petal_length = st.sidebar.slider("Petal length", 1.0, 6.9, 1.3)
petal_width = st.sidebar.slider("Petal width", 0.2, 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)
# load in our datasets
iris = datasets.load_iris()
X = iris.data
Y = iris.target
# use a random forest classifier to fit our data to our target
clf = RandomForestClassifier()
clf.fit(X, Y)
# get the prediction and show our results in the ui
prediction = clf.predict(df)
prediction_prob = clf.predict_proba(df)
st.subheader("Class labels and their corresponding index number")
st.write(iris.target_names)
st.subheader("Prediction")
st.write(iris.target_names[prediction])
st.subheader("Prediction Probability")
st.write(prediction_prob)

Run the app 🚀

streamlit run ml-app.py

Once it's done starting up, visit http://localhost:8501 and you should see something like

Awesome right?? StreamLit is a great tool for building and examining your models with a minimal, accessible interface. If you're interested in learning more, checkout their website, streamlit.io.