Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
201 lines (166 loc) · 6.39 KB
/
Copy pathapp.py
File metadata and controls
201 lines (166 loc) · 6.39 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
import json
from pathlib import Path
import joblib
import pandas as pd
import streamlit as st
# ============================================================
# Paths
# ============================================================
# Adjust MODEL_DIR if your saved_models folder lives elsewhere
# relative to wherever you run `streamlit run app.py` from.
MODEL_DIR = Path("src/saved_models")
SCALER_PATH = MODEL_DIR / "four_feature_scaler.joblib"
METRICS_PATH = MODEL_DIR / "metrics.json"
# ============================================================
# Page config
# ============================================================
st.set_page_config(
page_title="Diamond Price Prediction",
page_icon="💎",
layout="centered"
)
st.title("💎 Diamond Price Prediction System")
st.write(
"""
Pick a model, describe the diamond's characteristics, and get a live
price estimate. All fields update the prediction instantly — no
button needed.
"""
)
# ============================================================
# Discover available models
# ============================================================
# Any *_model.joblib file in saved_models is treated as a selectable model.
# The scaler file is explicitly excluded from this list.
if not MODEL_DIR.exists():
st.error(f"Model directory not found: {MODEL_DIR.resolve()}")
st.stop()
model_files = sorted(MODEL_DIR.glob("*_model.joblib"))
if not model_files:
st.error(f"No '*_model.joblib' files found in {MODEL_DIR.resolve()}")
st.stop()
# Friendly names for known model abbreviations
FRIENDLY_NAMES = {
"etr": "Extra Tree Regression",
"svr": "Support Vector Regression",
"lr": "Linear Regression",
"gbr": "Gradient Boosting Regression (Pro)",
}
# Build a friendly display name -> path mapping, e.g. "Extra Tree Regression" -> etr_model.joblib
MODEL_OPTIONS = {
FRIENDLY_NAMES.get(p.stem.replace("_model", "").lower(), p.stem.replace("_model", "").upper()): p
for p in model_files
}
# ============================================================
# Cached loaders (avoid re-reading disk on every slider move)
# ============================================================
@st.cache_resource
def load_model(path: str):
return joblib.load(path)
@st.cache_resource
def load_scaler(path: str):
return joblib.load(path)
@st.cache_resource
def load_encoder(path: str):
return joblib.load(path)
@st.cache_data
def load_metrics(path: str):
"""Load precomputed R2 / MAE / RMSE per model, if available.
Expected format (see testing.py note below for how to produce this):
{
"ETR": {"r2": 0.98, "mae": 250.1, "rmse": 400.3, "fit_time": 3.2},
"GBR": {...},
...
}
"""
p = Path(path)
if not p.exists():
return None
with open(p, "r") as f:
return json.load(f)
try:
scaler = load_scaler(str(SCALER_PATH))
except FileNotFoundError as e:
st.error(f"Required file not found: {e.filename}")
st.stop()
metrics = load_metrics(str(METRICS_PATH))
# ============================================================
# Model selection
# ============================================================
model_choice = st.selectbox("Select a model", list(MODEL_OPTIONS.keys()))
try:
model = load_model(str(MODEL_OPTIONS[model_choice]))
except FileNotFoundError:
st.error(f"Model file not found: {MODEL_OPTIONS[model_choice].resolve()}")
st.stop()
# ============================================================
# Metrics expander
# ============================================================
with st.expander("📊 Model Performance"):
if metrics is None:
st.info(
f"No metrics file found at `{METRICS_PATH}`. "
"Run the updated `testing.py` (see notes) to generate one, "
"then re-run this app."
)
elif model_choice not in metrics:
st.warning(f"No stored metrics for '{model_choice}' in metrics.json.")
else:
m = metrics[model_choice]
col1, col2, col3 = st.columns(3)
col1.metric("R²", f"{m['r2']:.4f}")
col2.metric("MAE", f"${m['mae']:,.2f}")
col3.metric("RMSE", f"${m['rmse']:,.2f}")
if "fit_time" in m:
st.caption(f"Fit time: {m['fit_time']:.4f} s")
# ============================================================
# Training ranges (numerical features) — used for slider bounds
# Pulled from your describe() output. Update these if your split differs.
# ============================================================
CARAT_MIN, CARAT_MAX = 0.20, 2.00
X_MIN, X_MAX = 3.70, 8.30
Y_MIN, Y_MAX = 3.68, 8.30
Z_MIN, Z_MAX = 1.40, 5.30
# ============================================================
# User inputs — all 9 features
# ============================================================
st.subheader("Diamond Characteristics")
carat = st.slider("Carat", CARAT_MIN, CARAT_MAX, 1.00, 0.01)
x = st.slider("Length (x) mm", X_MIN, X_MAX, 5.50, 0.01)
y = st.slider("Width (y) mm", Y_MIN, Y_MAX, 5.50, 0.01)
z = st.slider("Depth (z) mm", Z_MIN, Z_MAX, 3.50, 0.01)
# ============================================================
# Logical (cross-field) sanity checks
# ============================================================
warnings = []
if z > x:
warnings.append("Depth (z) is currently greater than Length (x) — that's unusual for a real diamond.")
if z > y:
warnings.append("Depth (z) is currently greater than Width (y) — that's unusual for a real diamond.")
for msg in warnings:
st.warning(msg)
# ============================================================
# Live prediction
# ============================================================
# Column order MUST match the order used during training in preprocessing.py.
# This order follows the feature table you provided (carat, cut, color,
# clarity, depth, table, x, y, z). Adjust if your training pipeline differs.
input_data = pd.DataFrame({
"carat": [carat],
"x": [x],
"y": [y],
"z": [z],
})
try:
input_scaled = scaler.transform(input_data)
prediction = model.predict(input_scaled)
price = prediction[0]
st.success(f"Estimated Diamond Price ({model_choice}): ${price:,.2f}")
except Exception as e:
st.error(f"Prediction failed: {e}")
st.caption(
"This usually means the feature columns/order, the encoder's "
"expected structure, or the category label spelling doesn't match "
"what preprocessing.py used for training."
)
# py -m streamlit run app.py