Flask / Streamlit for web deployment
Description
Flask and Streamlit are popular Python-based frameworks used to deploy machine learning models to the web.
Flask is a lightweight and flexible web framework that allows for building custom web servers and APIs. It is suitable for integrating ML models with fully customizable front-ends or third-party services.
Streamlit is a more high-level framework tailored for data scientists and ML developers. It simplifies creating interactive and visually appealing apps for model demos with minimal code.
Examples
Example: Deploying a model using Flask
# filename: iris_streamlit_app.py
import streamlit as st
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
# ---------------------------------------
# MODEL BUILDING
# ---------------------------------------
@st.cache_data
def load_data():
data = load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)
df['target'] = data.target
return df, data
@st.cache_resource
def train_model(df):
X = df.drop('target', axis=1)
y = df['target']
model = RandomForestClassifier()
model.fit(X, y)
return model
# ---------------------------------------
# WEB INTERFACE WITH STREAMLIT
# ---------------------------------------
st.set_page_config(page_title="Iris Flower Classifier", layout="centered")
st.title("🌸 Iris Flower Classification App")
st.markdown("This app uses a **Random Forest Classifier** to predict the type of Iris flower.")
# Load data and train model
df, iris_data = load_data()
model = train_model(df)
# Input sliders
st.sidebar.header("Input Features")
sepal_length = st.sidebar.slider("Sepal Length (cm)", 4.3, 7.9, 5.4)
sepal_width = st.sidebar.slider("Sepal Width (cm)", 2.0, 4.4, 3.4)
petal_length = st.sidebar.slider("Petal Length (cm)", 1.0, 6.9, 1.3)
petal_width = st.sidebar.slider("Petal Width (cm)", 0.1, 2.5, 0.2)
input_features = pd.DataFrame([[sepal_length, sepal_width, petal_length, petal_width]],
columns=iris_data.feature_names)
# Prediction
if st.button("Predict Flower Type"):
prediction = model.predict(input_features)[0]
predicted_class = iris_data.target_names[prediction]
st.success(f"🌼 Predicted Iris type: **{predicted_class}**")
# Show raw data (optional)
with st.expander("Show Iris Dataset"):
st.dataframe(df)
Save the code above to a file named iris_streamlit_app.py.
Run the app with:
streamlit run iris_streamlit_app.py
Real-World Applications
Prototyping ML Apps
Use Streamlit for quick model demos and UI-based experiments without web development overhead.
Model APIs
Flask is ideal for serving models as RESTful APIs used by frontend apps or mobile devices.
Interactive Dashboards
Streamlit helps build interactive data visualization and model explanation dashboards.
Custom Deployments
Flask gives full control for deploying ML systems with custom routes, logic, and integrations.
Resources
Recommended Books
- Flask Web Development by Miguel Grinberg
- Streamlit Documentation (Official)
- Deep Learning with Python by François Chollet
Interview Questions
What are the key differences between Flask and Streamlit for ML deployment?
Flask offers full control for building APIs and is suited for production systems, while Streamlit is tailored for creating quick and interactive model demos without writing HTML/CSS.
Can Streamlit be used in production environments?
Streamlit is excellent for demos and internal tools but may lack flexibility and scalability for large-scale production deployments, which Flask better supports.
How do you handle model loading in web apps?
Load the model once at the start of the app using libraries like joblib
or torch
. Ensure thread safety if serving multiple requests simultaneously.