import numpy as np import pandas as pd import joblib import streamlit as st st.set_page_config(page_title="Insurance Charges Predictor", page_icon="🩺", layout="centered") @st.cache_resource def load_model(): return joblib.load("src/gb_model.pkl") def build_features(age, sex, bmi, children, smoker, region, expected_cols=None): row = pd.DataFrame([{ "age": int(age), "sex": sex, "bmi": float(bmi), "children": int(children), "smoker": smoker, "region": region }]) # Same idea as training: pd.get_dummies(X, drop_first=True) X = pd.get_dummies(row, drop_first=True) # Align to training columns if we know them if expected_cols is not None: X = X.reindex(columns=expected_cols, fill_value=0) return X st.title("🩺 Insurance Charges Predictor") st.write("Enter the details and get an estimated medical insurance charge.") # Load model try: model = load_model() st.caption("Loaded model: `gb_model.pkl`") except Exception as e: st.error(f"Could not load model: {e}") st.stop() # Detect expected columns (works if model was fit with a DataFrame in sklearn) expected_cols = list(model.feature_names_in_) if hasattr(model, "feature_names_in_") else None if expected_cols is None: st.warning( "I could not detect the training columns from the model. " "If you get a column mismatch error, see the fix at the bottom." ) with st.sidebar: st.header("Options") log_model = st.checkbox("My model predicts log(charges) (I used np.log1p on charges)", value=False) c1, c2 = st.columns(2) with c1: age = st.number_input("Age", min_value=0, max_value=120, value=30, step=1) bmi = st.number_input("BMI", min_value=10.0, max_value=80.0, value=27.5, step=0.1) children = st.number_input("Children", min_value=0, max_value=10, value=0, step=1) with c2: sex = st.selectbox("Sex", ["female", "male"]) smoker = st.selectbox("Smoker", ["no", "yes"]) region = st.selectbox("Region", ["northeast", "northwest", "southeast", "southwest"]) if st.button("Predict Charges", type="primary"): X_input = build_features(age, sex, bmi, children, smoker, region, expected_cols) try: pred = float(model.predict(X_input)[0]) if log_model: pred = float(np.expm1(pred)) st.success(f"Estimated Insurance Charges: **{pred:,.2f}**") with st.expander("Show encoded input features"): st.dataframe(X_input) if hasattr(model, "feature_importances_") and expected_cols is not None: fi = pd.DataFrame({ "Feature": expected_cols, "Importance": model.feature_importances_ }).sort_values("Importance", ascending=False) st.subheader("Feature Importance") st.dataframe(fi) except Exception as e: st.error(f"Prediction failed: {e}") st.markdown("---") st.caption("Tip: The encoding must match the training data (same dummy columns).")