-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
257 lines (219 loc) · 9.28 KB
/
app.py
File metadata and controls
257 lines (219 loc) · 9.28 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import joblib
from sklearn.model_selection import train_test_split
from matplotlib import rcParams
# Enhanced styling setup
sns.set_style("whitegrid")
plt.style.use('seaborn-v0_8')
rcParams['figure.facecolor'] = '#FAFAFC'
rcParams['axes.facecolor'] = '#FFFFFF'
rcParams['axes.spines.top'] = False
rcParams['axes.spines.right'] = False
# Custom color palette
colors = {
'primary': '#6366F1', # Indigo
'secondary': '#8B5CF6', # Violet
'accent': '#06B6D4', # Cyan
'success': '#10B981', # Emerald
'warning': '#F59E0B', # Amber
'bg': '#F8FAFC', # Slate light
'card': '#FFFFFF'
}
# ---------- Load data & model ----------
df = pd.read_csv("data/insurance.csv")
@st.cache_resource
def load_model():
return joblib.load("models/final_insurance_model.pkl")
model = load_model()
# Hard-code test metrics
MAE = 2538.91
RMSE = 4602.51
R2 = 0.8636
# Pre-split for plot
X_all = df.drop("charges", axis=1)
y_all = df["charges"]
X_train_plot, X_test_plot, y_train_plot, y_test_plot = train_test_split(
X_all, y_all, test_size=0.2, random_state=42
)
# ---------- Page config ----------
st.set_page_config(
page_title="Medical Insurance Cost Dashboard",
page_icon="💊",
layout="wide"
)
st.title("💊 Medical Insurance Cost Prediction")
st.markdown("---")
# ---------- Tabs ----------
tab_overview, tab_eda, tab_model ,tab_about= st.tabs(["📊 Overview", "🔍 EDA", "🤖 Model & Prediction","ℹ️ About"])
# ===== Overview tab =====
with tab_overview:
st.subheader("Dataset Overview")
col1, col2 = st.columns([1, 1])
with col1:
st.markdown("**First 5 rows**")
st.dataframe(df.head(), use_container_width=True)
with col2:
st.markdown("**Summary Statistics**")
st.dataframe(df.describe().round(2), use_container_width=True)
st.markdown(
"""
**📋 Feature Descriptions**
- `age`: Age of insured person (18-64)
- `sex`: Gender (male/female)
- `bmi`: Body Mass Index (10-60)
- `children`: Number of dependents (0-5)
- `smoker`: Smoking status (yes/no) ← **Strongest predictor**
- `region`: US region (4 categories)
- `charges`: Annual medical cost (target)
"""
)
# ===== EDA tab =====
with tab_eda:
# 1. Distribution with gradient fill
st.subheader("📈 Charges Distribution")
fig1, ax1 = plt.subplots(figsize=(10, 6))
sns.histplot(df["charges"], bins=35, kde=True, ax=ax1,
color=colors['primary'], alpha=0.7, edgecolor='white')
ax1.set_xlabel("Annual Medical Charges ($)", fontsize=12, weight='bold')
ax1.set_ylabel("Frequency", fontsize=12, weight='bold')
ax1.set_title("Distribution of Medical Insurance Charges",
fontsize=16, weight='bold', pad=20)
plt.tight_layout()
st.pyplot(fig1)
st.markdown(
"🔍 **Key Insight**: Highly **right-skewed distribution** - most pay low-moderate amounts, "
"few have extremely high costs."
)
# 2. Numeric scatter plots
st.subheader("📊 Numeric Features vs Charges")
col1, col2 = st.columns(2)
with col1:
fig2, ax2 = plt.subplots(figsize=(8, 5))
scatter = sns.scatterplot(data=df, x="age", y="charges",
alpha=0.7, s=60, color=colors['accent'], ax=ax2)
ax2.set_title("Age vs Medical Charges", fontsize=14, weight='bold', pad=15)
ax2.set_xlabel("Age", fontsize=12, weight='bold')
ax2.set_ylabel("Charges ($)", fontsize=12, weight='bold')
plt.tight_layout()
st.pyplot(fig2)
st.markdown("👴 **Older age → Higher charges** (clear upward trend)")
with col2:
fig3, ax3 = plt.subplots(figsize=(8, 5))
sns.scatterplot(data=df, x="bmi", y="charges",
alpha=0.7, s=60, color=colors['warning'], ax=ax3)
ax3.set_title("BMI vs Medical Charges", fontsize=14, weight='bold', pad=15)
ax3.set_xlabel("BMI", fontsize=12, weight='bold')
ax3.set_ylabel("Charges ($)", fontsize=12, weight='bold')
plt.tight_layout()
st.pyplot(fig3)
st.markdown("⚖️ **Higher BMI → Higher charges** (especially BMI > 35)")
# 3. Categorical boxplots
st.subheader("🎯 Categorical Impact")
col3, col4 = st.columns(2)
with col3:
fig4, ax4 = plt.subplots(figsize=(8, 5))
sns.boxplot(data=df, x="smoker", y="charges", ax=ax4,
palette=[colors['success'], colors['warning']])
ax4.set_title("Smoker Status Impact", fontsize=14, weight='bold', pad=15)
ax4.set_ylabel("Charges ($)", fontsize=12, weight='bold')
plt.tight_layout()
st.pyplot(fig4)
st.markdown("🚬 **Smokers: 4x higher median charges!**")
with col4:
fig5, ax5 = plt.subplots(figsize=(8, 5))
sns.boxplot(data=df, x="region", y="charges", ax=ax5,
palette=['#EF4444', '#F59E0B', '#10B981', '#3B82F6'])
ax5.set_title("Regional Differences", fontsize=14, weight='bold', pad=15)
ax5.set_ylabel("Charges ($)", fontsize=12, weight='bold')
plt.tight_layout()
st.pyplot(fig5)
st.markdown("🌍 **Regions similar** - smoking dominates geography")
# 4. Correlation heatmap
st.subheader("🔗 Feature Correlations")
fig6, ax6 = plt.subplots(figsize=(7, 5))
corr = df[["age", "bmi", "children", "charges"]].corr()
sns.heatmap(corr, annot=True, cmap="RdYlBu_r", fmt=".2f",
linewidths=1, linecolor='white', cbar_kws={'shrink': 0.8}, ax=ax6)
ax6.set_title("Correlation Matrix", fontsize=14, weight='bold', pad=20)
plt.tight_layout()
st.pyplot(fig6)
st.markdown("**Top correlations**: Age (0.30) & BMI (0.20) → Charges")
# ===== Model tab =====
with tab_model:
st.subheader("🎯 Live Prediction")
# Input form
col1, col2, col3 = st.columns(3)
with col1:
age = st.number_input("👤 Age", min_value=18, max_value=100, value=30)
children = st.number_input("👨👩👧👦 Children", min_value=0, max_value=5, value=0)
with col2:
sex = st.selectbox("⚥️ Sex", ["male", "female"])
smoker = st.selectbox("🚬 Smoker", ["yes", "no"])
with col3:
bmi = st.number_input("⚖️ BMI", min_value=10.0, max_value=60.0, value=25.0, step=0.1)
region = st.selectbox("📍 Region", ["southeast", "southwest", "northeast", "northwest"])
if st.button("🔮 Predict Cost", type="primary", use_container_width=True):
input_df = pd.DataFrame({
"age": [age], "sex": [sex], "bmi": [bmi],
"children": [children], "smoker": [smoker], "region": [region]
})
user_pred = model.predict(input_df)[0]
st.success(f"💰 **Estimated Annual Cost: ${user_pred:,.0f}**")
st.balloons()
else:
st.info("📝 Fill inputs above → Click **Predict Cost**")
st.markdown("---")
# Performance metrics
st.subheader("📊 Model Performance")
colm1, colm2, colm3 = st.columns(3)
colm1.metric("🎯 MAE", f"${MAE:,.0f}")
colm2.metric("📈 RMSE", f"${RMSE:,.0f}")
colm3.metric("⭐ R²", f"{R2:.3f}")
st.markdown(
"**✅ Excellent model**: R²=0.86 means 86% of cost variation explained!"
)
st.markdown("---")
# Prediction plot
st.subheader("🎲 Actual vs Predicted")
y_test_pred = model.predict(X_test_plot)
fig7, ax7 = plt.subplots(figsize=(9, 7))
scatter = ax7.scatter(y_test_plot, y_test_pred, alpha=0.7, s=40,
c=y_test_pred - y_test_plot, cmap='RdYlBu_r',
edgecolors='white', linewidth=0.5)
max_val = max(y_test_plot.max(), y_test_pred.max()) * 1.05
ax7.plot([0, max_val], [0, max_val], "crimson", linewidth=3, alpha=0.9, label="Perfect Prediction")
ax7.set_xlabel("Actual Charges ($)", fontsize=12, weight='bold')
ax7.set_ylabel("Predicted Charges ($)", fontsize=12, weight='bold')
ax7.set_title("Model Accuracy: Actual vs Predicted", fontsize=16, weight='bold', pad=20)
ax7.legend()
plt.colorbar(scatter, label="Prediction Error", shrink=0.8)
plt.tight_layout()
st.pyplot(fig7)
st.markdown(
"🎯 **Points near red line = accurate predictions**. "
"Color shows error: **blue=underpredict**, **red=overpredict**."
)
with tab_about:
st.subheader("ℹ️ About this app")
st.markdown(
"""
This app is a **Medical Insurance Cost Prediction Dashboard** created as a
personal project to practice data analysis, visualization, and deploying a
machine learning model to the cloud.
**Main features**
- Exploratory Data Analysis of the medical insurance dataset
- Random Forest model to estimate annual insurance charges
- Interactive UI where users can input their details and see predictions
**Author**
- Name: Pratik Rath
- Email: pratikrath28@gmail.com
- LinkedIn: [Pratik Rath](https://www.linkedin.com/in/pratik-rath-02b527394/)
- GitHub: [pratikrath126](https://github.com/pratikrath126)
Thank you for checking out this project!
""",
unsafe_allow_html=False,
)