Streamlit: Quickly Deploy Machine Learning Models in Interactive Web Apps
Businesses today face the challenge of how to most effectively allocate their marketing budgets to maximize sales and ROI. With a large number of website visitors and potential customers, it‘s critical to identify and focus resources on those prospects most likely to actually make a purchase.
Machine learning models trained on historical customer data can predict an individual‘s propensity to buy, enabling marketers to target high-value leads with personalized campaigns and offers. Studies have shown that targeting based on propensity scores can increase conversion rates by 2-5x and ROI by up to 4x compared to traditional segmentation methods.[^1] [^1]: "Propensity Modeling for Digital Advertising." Google, 2022, https://support.google.com/analytics/answer/11809752?hl=en.
However, the process of productionalizing ML models into tools business users can easily leverage is often a bottleneck. Data scientists need to translate their Python code into interactive web applications, which traditionally requires learning new web development frameworks and collaborating with engineering teams. Fortunately, Streamlit provides a faster and easier path for deploying ML models in interactive apps, with just a few lines of Python.
In this post, we‘ll walk through an end-to-end example of using Streamlit to build a web app that predicts a customer‘s likelihood to purchase based on a trained machine learning model. Whether you‘re a data scientist, analyst or ML engineer, Streamlit can help you deliver data-driven insights and solutions to your business stakeholders in record time.
The Business Problem: Predicting Customer Propensity to Buy
Let‘s consider the case of an e-commerce company looking to optimize their retargeting ad campaigns. Of the thousands of daily visitors to their website, only a small percentage will actually make a purchase – the average conversion rate across industries is around 2.5%.[^2] Ideally, the company would focus its ad spend and promotions on reaching the visitors with the highest intent and likelihood of buying.
[^2]: Conversion Rate Benchmarks by Industry. Growcode, 2022, https://growcode.com/blog/conversion-rate-benchmarks/.One approach is to build a machine learning model that predicts a customer‘s propensity to purchase based on their demographic information and browsing behavior. By scoring visitors from 0-100% on their likelihood to buy, the marketing team can focus budgets on the highest value prospects and personalize messaging accordingly.
Training such a model requires historical data on customer attributes and purchase outcomes. Website interactions like time on site, pages viewed, product detail clicks, items wishlisted, and cart abandonment tend to be highly predictive of buying intent. Visitor data like geolocation, device, acquisition channel, and email engagement can also improve model accuracy. Even broader factors like seasonality, promotions, and economic indicators may boost predictive power.
A rigorous modeling process involves:
- Feature engineering: Aggregating raw event data into customer-level features
- Feature selection: Identifying the most predictive attributes, controlling for multicollinearity
- Algorithm selection: Testing models like logistic regression, XGBoost, or neural nets
- Training & hyperparameter tuning: Finding the optimal model parameters
- Evaluation: Measuring model performance on test data with metrics like AUC, precision & recall
- Productionalization: Deploying model into tools for business users
With a robust propensity model achieving AUC of 0.8+, an e-commerce company can realize significant ROI by aligning marketing spend to customer value.[^3] The challenge then becomes: how can data scientists quickly get these models into the hands of marketing users to drive real-world impact? That‘s where Streamlit comes in.
[^3]: "How Propensity Modeling Can Improve Marketing ROI." MarketingProfs, 6 Oct. 2021, https://www.marketingprofs.com/articles/2021/45343/how-propensity-modeling-can-improve-marketing-roi.Building a Propensity Model in Python
For this example, assume we have a dataset of 100K historical website visitor records, with features including:
visitorID: unique identifier for each visitorcountry: country code of visitor‘s geolocationsource: acquisition channel of visitor (search, social, email, etc.)total_pages_visited: total number of pages visited in sessiontotal_session_duration: total time in seconds spent on sitedevice_type: desktop, mobile, or tabletpages_visited_product,pages_visited_cart, etc.: page-specific visit countsadded_to_cart: 1 if visitor added any items to their cart, 0 otherwisepurchased: 1 if visitor completed a purchase, 0 otherwise
With this data, we can train a binary classification model to predict the purchased outcome based on the visitor attributes. Here‘s a sample Python snippet using the XGBoost library:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from xgboost import XGBClassifier
data = pd.read_csv(‘data/visitor_data.csv‘)
X = data[[‘country‘, ‘source‘, ‘total_pages_visited‘, ‘total_session_duration‘,
‘device_type‘, ‘pages_visited_product‘, ‘pages_visited_cart‘, ‘added_to_cart‘]]
y = data[‘purchased‘]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
model = XGBClassifier(n_estimators=500, learning_rate=0.02, max_depth=5, subsample=0.7)
model.fit(X_train, y_train)
print("Training AUC: ", roc_auc_score(y_train, model.predict_proba(X_train)[:,1]))
print("Test AUC: ", roc_auc_score(y_test, model.predict_proba(X_test)[:,1]))
model.save_model("propensity_model.json")
After optimizing the model‘s hyperparameters via techniques like grid search and cross-validation, let‘s say we arrive at a test AUC of 0.87 – a strong result for this type of problem. The most predictive features, in order of importance, are:
added_to_cart– adding an item to cart is strongest indicator of purchase intenttotal_session_duration– more time on site correlates with higher propensitypages_visited_product– more product detail views also predict higher purchase likelihoodsource– visitors from email and paid search tend to convert more than socialdevice_type– desktop users generally convert at higher rates than mobile
We can now save this trained model to disk so it can be loaded later for generating real-time predictions on new website visitors. The next step is productionalizing the model into an interactive app – enter Streamlit.
Introducing Streamlit
Traditionally, deploying a ML model to a web application would require using a framework like Flask or Django, and knowing web development languages like HTML, CSS and Javascript.
Streamlit provides a simpler alternative by allowing data scientists to create interactive web apps directly from Python scripts. With just a few lines of code, you can write an app that offers a UI for inputting data, loading a saved ML model, and visualizing the predictions – no web dev skills needed.
Some key features and benefits of Streamlit:
- Display interactive data tables and plots from DataFrame and Python viz libraries
- Add UI widgets like dropdowns, sliders, text inputs to allow user input
- Render ML model results, text, equations, and media
- Live app updates as you edit the Python script
- Out-of-the-box themes and layouts for quick styling
- Simple deployments via Streamlit sharing, or host your own with Docker
- Open-source and completely free for non-commercial use
Streamlit isn‘t ideal for building complex, enterprise-grade applications, but it excels for rapidly prototyping data science web apps and tools. Let‘s apply it to our customer propensity model example.
Building a Streamlit App for Propensity Predictions
Back to our e-commerce marketing team, who need an interactive tool for entering a website visitor‘s attributes and receiving a propensity-to-purchase prediction. With Streamlit, we can build this in short order:
import streamlit as st
import pandas as pd
from xgboost import XGBClassifier
st.set_page_config(page_title="Propensity to Purchase Predictor", layout="wide")
st.title("💰 Customer Propensity to Purchase")
st.sidebar.header("Enter customer attributes:")
country = st.sidebar.selectbox("Country", ["USA", "UK", "Germany", "France"])
source = st.sidebar.selectbox("Acquisition Source", ["Search", "Social", "Email"])
pages_visited = st.sidebar.number_input("Pages Visited", min_value=1, max_value=30, value=5)
duration = st.sidebar.number_input("Total Session Duration (seconds)", min_value=30, max_value=1800, value=180)
device = st.sidebar.selectbox("Device Type", ["Desktop", "Mobile", "Tablet"])
cart = st.sidebar.selectbox("Added to Cart", ["Yes", "No"])
st.sidebar.text("")
st.sidebar.text("Optionally upload a \nCSV of customer data:")
upload_file = st.sidebar.file_uploader("Choose a file")
if upload_file is not None:
input_df = pd.read_csv(upload_file)
else:
data = {‘country‘: country,
‘source‘: source,
‘total_pages_visited‘: pages_visited,
‘total_session_duration‘: duration,
‘device_type‘: device,
‘added_to_cart‘: 1 if cart=="Yes" else 0}
input_df = pd.DataFrame(data, index=[0])
col1, col2 = st.columns([1, 3])
with col1:
st.subheader("Predictions")
if st.button("Predict Propensity"):
model = XGBClassifier()
model.load_model("propensity_model.json")
propensity = model.predict_proba(input_df)[:,1]
st.subheader("Propensity Scores")
st.write(pd.DataFrame(propensity, columns=["Propensity to Purchase"]))
st.subheader("Customer Ranking")
rankings = pd.DataFrame(input_df.index, columns=["Customer ID"])
rankings["Propensity to Purchase"] = propensity
rankings = rankings.sort_values(by="Propensity to Purchase", ascending=False)
st.write(rankings)
with col2:
st.subheader("Customer Details")
st.write(input_df)
st.subheader("Recommended Actions")
for cust in rankings.index:
st.write("Customer %d: " % cust)
if rankings.loc[cust, "Propensity to Purchase"] >= 0.5:
st.write("⭐ High priority for retargeting. Predicted purchase probability: {:.0%}.".format(rankings.loc[cust, "Propensity to Purchase"]))
else:
st.write("Lower priority. Predicted purchase probability: {:.0%}.".format(rankings.loc[cust, "Propensity to Purchase"]))
st.text("")
Here‘s a visual of the final app:

Let‘s unpack the key elements:
- By importing
streamlit,pandas, andxgboost, we gain access to Streamlit‘s app development functionality and the same DS tools used to train the model - The
st.titleandst.headerdisplay text in the app, whilest.columnscreates a multi-column layout - In the sidebar, a combination of
st.selectbox,st.number_input, and other widgets allow users to manually input a customer‘s attributes - We also offer a file uploader so users can predict on multiple customers by uploading a CSV
- The "Predict Propensity" button triggers loading the saved XGBoost model, generating propensity scores, and rendering the results
- An interactive DataFrame shows each customer ranked by propensity score, and a second table displays the full input data
- Finally, we print a text recommendation on whether to prioritize each customer for retargeting campaigns based on their score
In just 50 lines of code, we‘ve created an app allowing marketing users to manually input customers, batch upload data, and view propensity scores and recommendations. The predictions update live as users change inputs, making it easy to test scenarios and segment customers.
Deploying the App and Next Steps
With our app ready, we can share it with a few commands through Streamlit‘s free sharing service, or deploy it to our own infrastructure. Streamlit apps run in Docker containers, making them easy to integrate into existing deployment workflows on cloud platforms or internal servers.
This example illustrates the power of Streamlit to quickly translate data science work into interactive tools. The same approach could be used to deploy churn propensity models, LTV predictions, product recommendation engines, and more. Streamlit‘s simple API abstracts away the web development complexity, letting data scientists focus on the modeling.
Some other promising use cases for Streamlit in the ML lifecycle:
- Interactive EDA and data visualization prior to modeling
- Tools for annotating and labeling training data at scale
- Testing and comparing different models and parameters
- Collecting feedback and monitoring model performance in production
- Dashboards to monitor data drift and model accuracy over time
However, Streamlit isn‘t ideal for every ML use case. More complex applications requiring user authentication, backend databases, and custom UI often call for traditional web frameworks. Streamlit also isn‘t designed for mobile apps or offline use cases. But for quickly prototyping ideas and delivering models to business users, it‘s a powerful tool.
Conclusion
This tutorial walked through the process of designing a customer propensity model, building it in Python, and deploying it as an interactive app with Streamlit. By leveraging ML to predict purchase likelihood and integrating those predictions into marketing workflows, businesses can realize significant ROI through more targeted customer acquisition.
Streamlit‘s simple, Python-based framework empowers data scientists to rapidly build web apps to serve insights and collect input and feedback from stakeholders. As data science and ML proliferate in organizations, tools like Streamlit will be key to democratizing access to these technologies for non-technical users.
Consider how Streamlit could help translate your data products into interactive tools and actionable insights for decision-makers. With its easy learning curve and quick development process, Streamlit lets data scientists deliver value faster than ever.
To learn more, explore Streamlit‘s documentation and community to see how others are applying it. You‘re also welcome to adapt the code from this propensity modeling project to fit your specific use case.
By bringing data to life through interactive apps, we can enable businesses to extract the full value from their investments in data science and ML. Streamlit puts that power directly in the hands of data scientists – no complex engineering required.