Q&A 30 How do you build a basic Streamlit app to deploy your ML model?

30.1 Explanation

After training a model, sharing it with others through a web interface is powerful and accessible. Streamlit makes this easy — you can turn a model into an interactive app with minimal code.

In this example, we:

  • Load a previously saved model (rf_titanic.joblib)
  • Create an input form for features like Pclass, Age, Fare, Sex, and Embarked
  • Predict and display the survival probability

30.2 Python Code: streamlit_app.py

# streamlit_app.py
import warnings
import streamlit.runtime.scriptrunner_utils as sru

# Suppress the ScriptRunContext warning
warnings.filterwarnings(
    "ignore",
    message=".*ScriptRunContext.*",
    category=UserWarning,
    module="streamlit"
)

import streamlit as st
import pandas as pd
import joblib
import warnings
warnings.simplefilter("ignore")


# Load trained model
model = joblib.load("models/rf_titanic.joblib")
model

st.title("Titanic Survival Prediction")

# Input form
pclass = st.selectbox("Passenger Class (1=1st, 2=2nd, 3=3rd)", [1, 2, 3])
age = st.slider("Age", 0, 100, 25)
fare = st.slider("Fare", 0.0, 500.0, 50.0)
sex = st.selectbox("Sex", ["male", "female"])
embarked = st.selectbox("Embarked", ["C", "Q", "S"])

# Convert to numeric
sex_num = 0 if sex == "male" else 1
embarked_map = {"C": 0, "Q": 1, "S": 2}
embarked_num = embarked_map[embarked]

# Create input DataFrame
input_df = pd.DataFrame({
    "Pclass": [pclass],
    "Age": [age],
    "Fare": [fare],
    "Sex": [sex_num],
    "Embarked": [embarked_num]
})

# Predict
if st.button("Predict Survival"):
    prob = model.predict_proba(input_df)[0][1]
    st.success(f"🧮 Predicted Survival Probability: {prob:.2%}")
streamlit run scripts.streamlit_app.py # Because the app is in scripts folder use scripts.appname...

For more details see https://deployment.complexdatainsights.com