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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import joblib
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import requests
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import shap
|
| 8 |
+
import tempfile
|
| 9 |
+
import streamlit.components.v1 as components
|
| 10 |
+
import scipy.sparse as sp
|
| 11 |
+
|
| 12 |
+
# Setup
|
| 13 |
+
API_URL = os.getenv("API_URL", "https://signe22-diabetes-prediction-api.hf.space/predict_batch")
|
| 14 |
+
NUMERIC_FEATURES = ['age','alcohol_consumption_per_week','physical_activity_minutes_per_week',
|
| 15 |
+
'diet_score','bmi','cholesterol_total','insulin_level','map','glucose_fasting']
|
| 16 |
+
CATEGORICAL_FEATURES = ['gender','ethnicity','education_level','income_level','employment_status',
|
| 17 |
+
'smoking_status','family_history_diabetes','hypertension_history','cardiovascular_history']
|
| 18 |
+
ALL_FEATURES = NUMERIC_FEATURES + CATEGORICAL_FEATURES
|
| 19 |
+
|
| 20 |
+
st.set_page_config(page_title="Diabetes Predictions", layout="wide")
|
| 21 |
+
|
| 22 |
+
# Function for SHAP plot
|
| 23 |
+
def st_shap(plot, height=None):
|
| 24 |
+
"""Renders a SHAP plot in Streamlit using standalone HTML + JS and white background."""
|
| 25 |
+
import tempfile, os
|
| 26 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".html") as tmpfile:
|
| 27 |
+
shap.save_html(tmpfile.name, plot)
|
| 28 |
+
html = open(tmpfile.name, "r").read()
|
| 29 |
+
os.unlink(tmpfile.name)
|
| 30 |
+
|
| 31 |
+
# HTML style
|
| 32 |
+
styled_html = f"""
|
| 33 |
+
<div style="
|
| 34 |
+
background-color: white;
|
| 35 |
+
padding: 20px;
|
| 36 |
+
border-radius: 12px;
|
| 37 |
+
box-shadow: 0 0 10px rgba(0,0,0,0.05);
|
| 38 |
+
">
|
| 39 |
+
{html}
|
| 40 |
+
</div>
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
components.html(styled_html, height=height or 500, width=1000, scrolling=True)
|
| 44 |
+
|
| 45 |
+
def _to_dense(X):
|
| 46 |
+
"""Ensure X is a dense NumPy array (convert from sparse if needed)."""
|
| 47 |
+
if sp.issparse(X):
|
| 48 |
+
return X.toarray()
|
| 49 |
+
return np.asarray(X)
|
| 50 |
+
|
| 51 |
+
# Function to create synthetic data
|
| 52 |
+
def synth_data(n_policyholders=100, seed=42):
|
| 53 |
+
rng = np.random.default_rng(seed); n = n_policyholders
|
| 54 |
+
age = rng.normal(50, 15, n).clip(18, 90)
|
| 55 |
+
alcohol = rng.gamma(2, 3, n).clip(0, 40)
|
| 56 |
+
activity = rng.normal(150, 60, n).clip(0, 600)
|
| 57 |
+
diet = rng.uniform(1, 10, n)
|
| 58 |
+
bmi = rng.normal(27, 5, n).clip(15, 50)
|
| 59 |
+
chol = rng.normal(200, 40, n).clip(100, 400)
|
| 60 |
+
insulin = rng.normal(10, 5, n).clip(2, 40)
|
| 61 |
+
map_ = rng.normal(95, 10, n).clip(70, 130)
|
| 62 |
+
glucose = rng.normal(100, 25, n).clip(60, 250)
|
| 63 |
+
gender = np.random.choice(['Male','Female','Other'], n, p=[0.48,0.5,0.02])
|
| 64 |
+
ethnicity = np.random.choice(['White','Black','Asian','Hispanic','Other'], n)
|
| 65 |
+
edu = np.random.choice(['High School','Bachelor','Master','PhD'], n, p=[0.4,0.35,0.2,0.05])
|
| 66 |
+
income = np.random.choice(['Low','Middle','High'], n, p=[0.3,0.5,0.2])
|
| 67 |
+
emp = np.random.choice(['Employed','Unemployed','Retired','Student'], n, p=[0.6,0.1,0.25,0.05])
|
| 68 |
+
smoke = np.random.choice(['Never','Former','Current'], n, p=[0.6,0.25,0.15])
|
| 69 |
+
fam = np.random.choice(['Yes','No'], n, p=[0.35,0.65])
|
| 70 |
+
hyper = np.random.choice(['Yes','No'], n, p=[0.3,0.7])
|
| 71 |
+
cardio = np.random.choice(['Yes','No'], n, p=[0.2,0.8])
|
| 72 |
+
df = pd.DataFrame({
|
| 73 |
+
'age':age,'alcohol_consumption_per_week':alcohol,'physical_activity_minutes_per_week':activity,
|
| 74 |
+
'diet_score':diet,'bmi':bmi,'cholesterol_total':chol,'insulin_level':insulin,'map':map_,'glucose_fasting':glucose,
|
| 75 |
+
'gender':gender,'ethnicity':ethnicity,'education_level':edu,'income_level':income,
|
| 76 |
+
'employment_status':emp,'smoking_status':smoke,'family_history_diabetes':fam,
|
| 77 |
+
'hypertension_history':hyper,'cardiovascular_history':cardio
|
| 78 |
+
})
|
| 79 |
+
df.insert(0, 'policyholder_id', range(1, len(df)+1))
|
| 80 |
+
return df
|
| 81 |
+
|
| 82 |
+
def call_api(df: pd.DataFrame):
|
| 83 |
+
payload = {'data': df[ALL_FEATURES].to_dict(orient="records")}
|
| 84 |
+
r = requests.post(API_URL, json=payload, timeout=60); r.raise_for_status()
|
| 85 |
+
return np.array(r.json()["probabilities"])
|
| 86 |
+
|
| 87 |
+
# Cache model to make it faster
|
| 88 |
+
@st.cache_resource
|
| 89 |
+
def load_model():
|
| 90 |
+
return joblib.load("diabetes_prediction_model_20251007.pkl")
|
| 91 |
+
|
| 92 |
+
pipe = load_model()
|
| 93 |
+
|
| 94 |
+
# Initiate state
|
| 95 |
+
if "df" not in st.session_state:
|
| 96 |
+
st.session_state.df = None
|
| 97 |
+
if "selected_id" not in st.session_state:
|
| 98 |
+
st.session_state.selected_id = None
|
| 99 |
+
|
| 100 |
+
# Sidebar with filters
|
| 101 |
+
with st.sidebar:
|
| 102 |
+
st.header("Simulation")
|
| 103 |
+
n_policyholders = st.slider("Synthetic policyholders per day", 10, 200, 20, 10)
|
| 104 |
+
seed = st.number_input("Random seed", 0, 99999, 42, 1)
|
| 105 |
+
threshold = st.slider("Classification threshold", 0.0, 1.0, 0.24, 0.01)
|
| 106 |
+
|
| 107 |
+
if st.button("Generate & Predict", use_container_width=True):
|
| 108 |
+
df = synth_data(n_policyholders=n_policyholders, seed=int(seed))
|
| 109 |
+
probs = call_api(df)
|
| 110 |
+
df["predicted_risk"] = probs
|
| 111 |
+
df['risk_category'] = np.where(df['predicted_risk'] >= threshold, "High-risk", "Low-risk")
|
| 112 |
+
st.session_state.df = df
|
| 113 |
+
# reset selection to first id for consistency
|
| 114 |
+
st.session_state.selected_id = int(df["policyholder_id"].iloc[0])
|
| 115 |
+
st.success("Predictions received from API")
|
| 116 |
+
|
| 117 |
+
if st.session_state.df is not None:
|
| 118 |
+
st.session_state.selected_id = st.selectbox(
|
| 119 |
+
"Select Policyholder ID:",
|
| 120 |
+
st.session_state.df["policyholder_id"].tolist(),
|
| 121 |
+
index=(
|
| 122 |
+
st.session_state.df["policyholder_id"].tolist().index(st.session_state.selected_id)
|
| 123 |
+
if st.session_state.selected_id in st.session_state.df["policyholder_id"].tolist()
|
| 124 |
+
else 0
|
| 125 |
+
),
|
| 126 |
+
key="selected_id_widget"
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Main outputs of model
|
| 130 |
+
st.title("Predictions of high risk diabetes")
|
| 131 |
+
st.caption("API: " + API_URL)
|
| 132 |
+
|
| 133 |
+
if st.session_state.df is None:
|
| 134 |
+
st.info("Generate predictions first to enable results and SHAP explanation.")
|
| 135 |
+
else:
|
| 136 |
+
df = st.session_state.df
|
| 137 |
+
st.write("### Results", df[["policyholder_id", "predicted_risk", "risk_category"]])
|
| 138 |
+
st.metric("Average predicted diabetes risk", f"{df['predicted_risk'].mean():.2%}")
|
| 139 |
+
|
| 140 |
+
st.header("Explain Prediction for a Policyholder")
|
| 141 |
+
# Set up SHAP explanation for a chosen policyholder
|
| 142 |
+
selected_id = st.session_state.selected_id
|
| 143 |
+
if selected_id is not None:
|
| 144 |
+
row = df.loc[df["policyholder_id"] == selected_id, ALL_FEATURES]
|
| 145 |
+
|
| 146 |
+
preprocessor = pipe.named_steps["preprocessor"]
|
| 147 |
+
model = pipe.named_steps["classifier"]
|
| 148 |
+
|
| 149 |
+
X_all = preprocessor.transform(df[ALL_FEATURES])
|
| 150 |
+
X_row = preprocessor.transform(row)
|
| 151 |
+
feature_names = preprocessor.get_feature_names_out(ALL_FEATURES)
|
| 152 |
+
|
| 153 |
+
explainer = shap.LinearExplainer(model, X_all)
|
| 154 |
+
shap_values = explainer.shap_values(X_row)
|
| 155 |
+
|
| 156 |
+
# Force plot
|
| 157 |
+
shap_plot = shap.force_plot(
|
| 158 |
+
explainer.expected_value,
|
| 159 |
+
shap_values[0],
|
| 160 |
+
_to_dense(X_row)[0],
|
| 161 |
+
feature_names=feature_names
|
| 162 |
+
)
|
| 163 |
+
st_shap(shap_plot, height=250)
|
| 164 |
+
|
| 165 |
+
# Shap df set up for text explanation
|
| 166 |
+
shap_df = pd.DataFrame({"Feature": feature_names, "SHAP value": shap_values[0]})
|
| 167 |
+
shap_df = shap_df.reindex(shap_df["SHAP value"].abs().sort_values(ascending=False).index)
|
| 168 |
+
|
| 169 |
+
# Text explanation of most important features
|
| 170 |
+
top_features = shap_df.head(5) # the 5 most important features
|
| 171 |
+
increase = top_features[top_features["SHAP value"] > 0]
|
| 172 |
+
decrease = top_features[top_features["SHAP value"] < 0]
|
| 173 |
+
|
| 174 |
+
st.markdown("### Why this prediction?")
|
| 175 |
+
st.info(
|
| 176 |
+
f"The model predicts a higher diabetes risk mainly due to **{', '.join(increase['Feature']) or 'none'}**, "
|
| 177 |
+
f"while lower risk is influenced by **{', '.join(decrease['Feature']) or 'none'}**.")
|