Spaces:
Sleeping
Sleeping
File size: 3,026 Bytes
863da02 b7fb521 863da02 b7fb521 034860a b7fb521 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | 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).") |