Calmcode - streamlit: cache

Cache heavy computations with streamlit.

1 2 3 4 5 6 7 8 9

We're using scikit-learn in this demo. Should you be unfamilar with it, feel free to just copy and paste the code below. The goal of the video is to explain streamlit, not that we worry about understanding the algorithm in detail.

This is the that we end up with at the end of the video;

import numpy as np
import streamlit as st
import matplotlib.pylab as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import AdaBoostRegressor

n = 1000
x = np.linspace(0, 6, n)
X = np.linspace(0, 6, n)[:, np.newaxis]
y = np.sin(X).ravel() + np.sin(6 * X).ravel() + np.random.random(n) * 0.3

n_est = st.sidebar.slider("n_est", min_value=1, max_value=5_000, step=1)

def make_predictions(n_est):
    mod1 = DecisionTreeRegressor(max_depth=4)
    y1 =,y).predict(X)
    y2 = AdaBoostRegressor(mod1, n_estimators=n_est).fit(X, y).predict(X)
    return y1, y2

y1, y2 = make_predictions(n_est=n_est)

if st.sidebar.checkbox("Toggle ScatterChart"):
    plt.scatter(x, y, alpha=0.1)
plt.plot(x, y1, label="just a tree")
plt.plot(x, y2, label=f"adaboost-{n_est}")


Note that we run this app from the command line by running;

streamlit run