9.2. Streamlit Development#
Streamlit is a Python framework purpose-built for creating data science and machine learning applications. Unlike Voila (which converts notebooks), Streamlit apps are Python scripts designed from the ground up for interactive web applications.
9.2.1. Why Streamlit?#
Pure Python: No HTML/CSS/JavaScript required
Rapid development: Build apps in hours
Built for ML: Optimized for data science workflows
Active development: Rich ecosystem and community
Easy deployment: Streamlit Cloud (free hosting)
9.2.2. Installation#
pip install streamlit
9.2.3. Your First Streamlit App#
Create app.py:
import streamlit as st
st.title("My First Streamlit App")
name = st.text_input("Enter your name:")
if name:
st.write(f"Hello, {name}!")
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[1], line 1
----> 1 import streamlit as st
3 st.title("My First Streamlit App")
5 name = st.text_input("Enter your name:")
ModuleNotFoundError: No module named 'streamlit'
Run:
streamlit run app.py
Opens automatically at http://localhost:8501
9.2.4. Streamlit Basics#
9.2.4.1. Display Content#
import streamlit as st
# Text
st.title("Title")
st.header("Header")
st.subheader("Subheader")
st.text("Plain text")
st.markdown("**Bold** and *italic*")
st.write("Anything:", data, object, plot)
# Code
st.code("print('Hello')", language='python')
# LaTeX
st.latex(r"e^{i\\pi} + 1 = 0")
9.2.4.2. Input Widgets#
# Text input
name = st.text_input("Name:")
email = st.text_input("Email:", type="password")
text = st.text_area("Comments:")
# Numbers
age = st.number_input("Age:", min_value=0, max_value=120, value=25)
slider_val = st.slider("Select value:", 0, 100, 50)
# Selection
option = st.selectbox("Choose one:", ["A", "B", "C"])
multi = st.multiselect("Choose multiple:", ["X", "Y", "Z"])
checked = st.checkbox("Agree to terms")
radio = st.radio("Select:", ["Option 1", "Option 2"])
# Buttons
if st.button("Click me"):
st.write("Button clicked!")
# File upload
uploaded = st.file_uploader("Choose a CSV", type="csv")
# Date/Time
date = st.date_input("Select date")
time = st.time_input("Select time")
# Color picker
color = st.color_picker("Pick a color", "#00f900")
9.2.4.3. Layout#
Columns:
col1, col2, col3 = st.columns(3)
with col1:
st.header("Column 1")
st.write("Content for column 1")
with col2:
st.header("Column 2")
st.write("Content for column 2")
with col3:
st.header("Column 3")
st.write("Content for column 3")
Expander:
with st.expander("Click to expand"):
st.write("Hidden content")
st.image("image.png")
Sidebar:
st.sidebar.title("Settings")
threshold = st.sidebar.slider("Threshold:", 0.0, 1.0, 0.5)
model_type = st.sidebar.selectbox("Model:", ["Linear", "RF", "GB"])
Tabs:
tab1, tab2, tab3 = st.tabs(["Data", "Model", "Results"])
with tab1:
st.header("Data Overview")
st.dataframe(df)
with tab2:
st.header("Model Configuration")
# Model settings
with tab3:
st.header("Results")
# Show results
9.2.5. ML Model Application#
import streamlit as st
import joblib
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
st.title("🔮 Customer Churn Prediction")
# Load model
@st.cache_resource
def load_model():
return joblib.load('models/churn_model.joblib')
model = load_model()
# Sidebar for inputs
st.sidebar.header("Customer Information")
age = st.sidebar.slider("Age", 18, 80, 35)
income = st.sidebar.slider("Annual Income ($)", 20000, 200000, 50000, step=5000)
credit_score = st.sidebar.slider("Credit Score", 300, 850, 650)
# Feature engineering
features = pd.DataFrame({
'age': [age],
'income': [income],
'credit_score': [credit_score]
})
# Main area
st.header("Customer Profile")
col1, col2, col3 = st.columns(3)
col1.metric("Age", age)
col2.metric("Income", f"${income:,}")
col3.metric("Credit Score", credit_score)
# Predict
if st.button("Predict Churn", type="primary"):
prediction = model.predict(features)[0]
probability = model.predict_proba(features)[0]
st.header("Prediction")
if prediction == 1:
st.error("⚠️ HIGH RISK: Customer likely to churn")
else:
st.success("✅ LOW RISK: Customer likely to stay")
# Probability gauge
churn_prob = probability[1]
st.write(f"**Churn Probability:** {churn_prob:.1%}")
st.progress(churn_prob)
# Visualization
fig, ax = plt.subplots()
ax.barh(['Retain', 'Churn'], probability)
ax.set_xlabel('Probability')
ax.set_xlim(0, 1)
st.pyplot(fig)
9.2.6. Caching for Performance#
@st.cache_data: Cache data (DataFrames, lists, etc.)
@st.cache_data
def load_data():
# Expensive data loading
return pd.read_csv('large_file.csv')
df = load_data() # Runs once, then cached
@st.cache_resource: Cache models, connections
@st.cache_resource
def load_model():
return joblib.load('model.joblib')
model = load_model() # Cached
9.2.7. Session State#
Maintain state across reruns:
# Initialize
if 'count' not in st.session_state:
st.session_state.count = 0
# Update
if st.button("Increment"):
st.session_state.count += 1
st.write(f"Count: {st.session_state.count}")
9.2.8. Deployment#
9.2.8.1. Streamlit Cloud (Free)#
Push code to GitHub
Go to share.streamlit.io
Connect repository
Deploy!
requirements.txt:
streamlit
scikit-learn
joblib
pandas
matplotlib
9.2.8.2. Docker Deployment#
Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8501
CMD ["streamlit", "run", "app.py", "--server.address", "0.0.0.0"]
docker build -t streamlit-app .
docker run -p 8501:8501 streamlit-app
9.2.9. Pros and Cons#
9.2.9.1. Advantages#
Pure Python (no web dev skills needed)
Rapid development
Built-in widgets and layouts
Free hosting (Streamlit Cloud)
Active community
9.2.9.2. Limitations#
Limited customization of UI
Reruns entire script on interaction
Not ideal for complex applications
Some performance constraints
9.2.10. When to Use Streamlit#
Use Streamlit when:
Building ML/data apps from scratch
Need more customization than Voila
Want rapid prototyping
Target is data scientists/analysts
Skip Streamlit when:
Need pixel-perfect custom UI
Building complex multi-page applications
Need fine-grained control over frontend
9.2.11. Summary#
Streamlit provides:
Fast development of data/ML apps
Pure Python interface
Built-in widgets and layouts
Easy deployment to Streamlit Cloud
Good balance between simplicity and functionality