EnYa32 commited on
Commit
b7fb521
·
verified ·
1 Parent(s): e8481c4

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +87 -36
src/streamlit_app.py CHANGED
@@ -1,40 +1,91 @@
1
- import altair as alt
2
  import numpy as np
3
  import pandas as pd
 
4
  import streamlit as st
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import numpy as np
2
  import pandas as pd
3
+ import joblib
4
  import streamlit as st
5
 
6
+ st.set_page_config(page_title="Insurance Charges Predictor", page_icon="🩺", layout="centered")
7
+
8
+ @st.cache_resource
9
+ def load_model():
10
+ return joblib.load("gb_model.pkl")
11
+
12
+ def build_features(age, sex, bmi, children, smoker, region, expected_cols=None):
13
+ row = pd.DataFrame([{
14
+ "age": int(age),
15
+ "sex": sex,
16
+ "bmi": float(bmi),
17
+ "children": int(children),
18
+ "smoker": smoker,
19
+ "region": region
20
+ }])
21
+
22
+ # Same idea as training: pd.get_dummies(X, drop_first=True)
23
+ X = pd.get_dummies(row, drop_first=True)
24
+
25
+ # Align to training columns if we know them
26
+ if expected_cols is not None:
27
+ X = X.reindex(columns=expected_cols, fill_value=0)
28
+
29
+ return X
30
+
31
+ st.title("🩺 Insurance Charges Predictor")
32
+ st.write("Enter the details and get an estimated medical insurance charge.")
33
+
34
+ # Load model
35
+ try:
36
+ model = load_model()
37
+ st.caption("Loaded model: `gb_model.pkl`")
38
+ except Exception as e:
39
+ st.error(f"Could not load model: {e}")
40
+ st.stop()
41
+
42
+ # Detect expected columns (works if model was fit with a DataFrame in sklearn)
43
+ expected_cols = list(model.feature_names_in_) if hasattr(model, "feature_names_in_") else None
44
+ if expected_cols is None:
45
+ st.warning(
46
+ "I could not detect the training columns from the model. "
47
+ "If you get a column mismatch error, see the fix at the bottom."
48
+ )
49
+
50
+ with st.sidebar:
51
+ st.header("Options")
52
+ log_model = st.checkbox("My model predicts log(charges) (I used np.log1p on charges)", value=False)
53
+
54
+ c1, c2 = st.columns(2)
55
+ with c1:
56
+ age = st.number_input("Age", min_value=0, max_value=120, value=30, step=1)
57
+ bmi = st.number_input("BMI", min_value=10.0, max_value=80.0, value=27.5, step=0.1)
58
+ children = st.number_input("Children", min_value=0, max_value=10, value=0, step=1)
59
+
60
+ with c2:
61
+ sex = st.selectbox("Sex", ["female", "male"])
62
+ smoker = st.selectbox("Smoker", ["no", "yes"])
63
+ region = st.selectbox("Region", ["northeast", "northwest", "southeast", "southwest"])
64
+
65
+ if st.button("Predict Charges", type="primary"):
66
+ X_input = build_features(age, sex, bmi, children, smoker, region, expected_cols)
67
+
68
+ try:
69
+ pred = float(model.predict(X_input)[0])
70
+ if log_model:
71
+ pred = float(np.expm1(pred))
72
+
73
+ st.success(f"Estimated Insurance Charges: **{pred:,.2f}**")
74
+
75
+ with st.expander("Show encoded input features"):
76
+ st.dataframe(X_input)
77
+
78
+ if hasattr(model, "feature_importances_") and expected_cols is not None:
79
+ fi = pd.DataFrame({
80
+ "Feature": expected_cols,
81
+ "Importance": model.feature_importances_
82
+ }).sort_values("Importance", ascending=False)
83
+
84
+ st.subheader("Feature Importance")
85
+ st.dataframe(fi)
86
+
87
+ except Exception as e:
88
+ st.error(f"Prediction failed: {e}")
89
+
90
+ st.markdown("---")
91
+ st.caption("Tip: The encoding must match the training data (same dummy columns).")