Update src/streamlit_app.py
Browse files- src/streamlit_app.py +115 -95
src/streamlit_app.py
CHANGED
|
@@ -8,18 +8,16 @@ from pathlib import Path
|
|
| 8 |
# Page config
|
| 9 |
# -------------------------
|
| 10 |
st.set_page_config(
|
| 11 |
-
page_title='Clustering Predictor (
|
| 12 |
page_icon='🧩',
|
| 13 |
layout='centered'
|
| 14 |
)
|
| 15 |
|
| 16 |
-
st.title('🧩 Clustering Predictor
|
| 17 |
-
st.write(
|
| 18 |
-
'Upload a CSV file and get cluster predictions using your saved preprocessing (Scaler + PCA) and model.'
|
| 19 |
-
)
|
| 20 |
|
| 21 |
# -------------------------
|
| 22 |
-
# Paths
|
| 23 |
# -------------------------
|
| 24 |
BASE_DIR = Path(__file__).resolve().parent
|
| 25 |
|
|
@@ -35,15 +33,11 @@ GMM_PATH = BASE_DIR / 'gmm_model.pkl'
|
|
| 35 |
# -------------------------
|
| 36 |
@st.cache_resource
|
| 37 |
def load_assets():
|
| 38 |
-
|
| 39 |
-
for p in
|
| 40 |
-
if not p.exists():
|
| 41 |
-
missing.append(p.name)
|
| 42 |
-
|
| 43 |
if missing:
|
| 44 |
raise FileNotFoundError(
|
| 45 |
-
f'Missing required files in repo root: {missing}. '
|
| 46 |
-
'Please upload them next to app.py.'
|
| 47 |
)
|
| 48 |
|
| 49 |
feature_names = joblib.load(FEATURES_PATH)
|
|
@@ -51,14 +45,14 @@ def load_assets():
|
|
| 51 |
pca = joblib.load(PCA_PATH)
|
| 52 |
|
| 53 |
models = {}
|
| 54 |
-
if KMEANS_PATH.exists():
|
| 55 |
-
models['KMeans (k=9)'] = joblib.load(KMEANS_PATH)
|
| 56 |
if GMM_PATH.exists():
|
| 57 |
-
models['GMM (
|
|
|
|
|
|
|
| 58 |
|
| 59 |
if not models:
|
| 60 |
raise FileNotFoundError(
|
| 61 |
-
"No model
|
| 62 |
)
|
| 63 |
|
| 64 |
return feature_names, scaler, pca, models
|
|
@@ -70,92 +64,118 @@ except Exception as e:
|
|
| 70 |
st.stop()
|
| 71 |
|
| 72 |
# -------------------------
|
| 73 |
-
# Model
|
| 74 |
# -------------------------
|
| 75 |
-
model_name = st.selectbox('Select model', list(models.keys()))
|
| 76 |
model = models[model_name]
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
# -------------------------
|
| 83 |
-
# Upload CSV
|
| 84 |
-
# -------------------------
|
| 85 |
-
uploaded = st.file_uploader('Upload CSV', type=['csv'])
|
| 86 |
-
|
| 87 |
-
def preprocess_df(df_in: pd.DataFrame) -> tuple[pd.DataFrame, pd.Series | None]:
|
| 88 |
-
# Accept either 'id' or 'Id' columns (optional)
|
| 89 |
-
id_col = None
|
| 90 |
-
if 'id' in df_in.columns:
|
| 91 |
-
id_col = 'id'
|
| 92 |
-
elif 'Id' in df_in.columns:
|
| 93 |
-
id_col = 'Id'
|
| 94 |
-
|
| 95 |
-
ids = df_in[id_col].copy() if id_col else None
|
| 96 |
-
|
| 97 |
-
X = df_in.drop(columns=[id_col], errors='ignore').copy()
|
| 98 |
-
|
| 99 |
-
# Validate columns
|
| 100 |
-
missing_cols = [c for c in feature_names if c not in X.columns]
|
| 101 |
-
extra_cols = [c for c in X.columns if c not in feature_names]
|
| 102 |
-
|
| 103 |
-
if missing_cols:
|
| 104 |
-
raise ValueError(f'Missing required columns: {missing_cols}')
|
| 105 |
-
|
| 106 |
-
# Keep only expected columns + correct order
|
| 107 |
-
X = X[feature_names]
|
| 108 |
|
| 109 |
-
# Convert to numeric
|
| 110 |
-
for c in
|
| 111 |
-
|
| 112 |
|
| 113 |
-
if
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
raise ValueError(
|
| 117 |
-
f'Found NaNs after converting to numeric. Check these columns: {bad_cols}. '
|
| 118 |
-
'Make sure your CSV has valid numeric values.'
|
| 119 |
-
)
|
| 120 |
-
|
| 121 |
-
return X, ids
|
| 122 |
|
| 123 |
-
|
| 124 |
-
X_scaled = scaler.transform(X)
|
| 125 |
X_pca = pca.transform(X_scaled)
|
| 126 |
-
|
| 127 |
-
# KMeans and GMM both have predict()
|
| 128 |
preds = model.predict(X_pca)
|
| 129 |
return preds
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
# Page config
|
| 9 |
# -------------------------
|
| 10 |
st.set_page_config(
|
| 11 |
+
page_title='Clustering Predictor (GMM / KMeans)',
|
| 12 |
page_icon='🧩',
|
| 13 |
layout='centered'
|
| 14 |
)
|
| 15 |
|
| 16 |
+
st.title('🧩 Clustering Predictor')
|
| 17 |
+
st.write('Predict cluster labels using saved preprocessing (Scaler + PCA) and a clustering model.')
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# -------------------------
|
| 20 |
+
# Paths
|
| 21 |
# -------------------------
|
| 22 |
BASE_DIR = Path(__file__).resolve().parent
|
| 23 |
|
|
|
|
| 33 |
# -------------------------
|
| 34 |
@st.cache_resource
|
| 35 |
def load_assets():
|
| 36 |
+
required = [FEATURES_PATH, SCALER_PATH, PCA_PATH]
|
| 37 |
+
missing = [p.name for p in required if not p.exists()]
|
|
|
|
|
|
|
|
|
|
| 38 |
if missing:
|
| 39 |
raise FileNotFoundError(
|
| 40 |
+
f'Missing required files in repo root: {missing}. Put them next to app.py.'
|
|
|
|
| 41 |
)
|
| 42 |
|
| 43 |
feature_names = joblib.load(FEATURES_PATH)
|
|
|
|
| 45 |
pca = joblib.load(PCA_PATH)
|
| 46 |
|
| 47 |
models = {}
|
|
|
|
|
|
|
| 48 |
if GMM_PATH.exists():
|
| 49 |
+
models['GMM (best)'] = joblib.load(GMM_PATH)
|
| 50 |
+
if KMEANS_PATH.exists():
|
| 51 |
+
models['KMeans'] = joblib.load(KMEANS_PATH)
|
| 52 |
|
| 53 |
if not models:
|
| 54 |
raise FileNotFoundError(
|
| 55 |
+
"No model found. Upload 'gmm_model_k9.pkl' (and optionally 'kmeans_model_k9.pkl') next to app.py."
|
| 56 |
)
|
| 57 |
|
| 58 |
return feature_names, scaler, pca, models
|
|
|
|
| 64 |
st.stop()
|
| 65 |
|
| 66 |
# -------------------------
|
| 67 |
+
# Model selection
|
| 68 |
# -------------------------
|
| 69 |
+
model_name = st.selectbox('Select model', list(models.keys()), index=0)
|
| 70 |
model = models[model_name]
|
| 71 |
|
| 72 |
+
def predict_from_features(df_features: pd.DataFrame) -> np.ndarray:
|
| 73 |
+
# Ensure correct order
|
| 74 |
+
df_features = df_features[feature_names].copy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
# Convert to numeric
|
| 77 |
+
for c in df_features.columns:
|
| 78 |
+
df_features[c] = pd.to_numeric(df_features[c], errors='coerce')
|
| 79 |
|
| 80 |
+
if df_features.isna().any().any():
|
| 81 |
+
bad_cols = df_features.columns[df_features.isna().any()].tolist()
|
| 82 |
+
raise ValueError(f'NaN values found in columns: {bad_cols}. Please provide valid numeric values.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
+
X_scaled = scaler.transform(df_features)
|
|
|
|
| 85 |
X_pca = pca.transform(X_scaled)
|
|
|
|
|
|
|
| 86 |
preds = model.predict(X_pca)
|
| 87 |
return preds
|
| 88 |
|
| 89 |
+
# -------------------------
|
| 90 |
+
# UI Tabs
|
| 91 |
+
# -------------------------
|
| 92 |
+
tab_csv, tab_single = st.tabs(['📁 CSV Upload', '🧮 Single Prediction'])
|
| 93 |
+
|
| 94 |
+
# =========================
|
| 95 |
+
# Tab 1: CSV Upload
|
| 96 |
+
# =========================
|
| 97 |
+
with tab_csv:
|
| 98 |
+
st.subheader('Upload a CSV and predict clusters')
|
| 99 |
+
uploaded = st.file_uploader('Upload CSV', type=['csv'])
|
| 100 |
+
|
| 101 |
+
if uploaded is not None:
|
| 102 |
+
try:
|
| 103 |
+
df_up = pd.read_csv(uploaded)
|
| 104 |
+
|
| 105 |
+
# id handling (optional)
|
| 106 |
+
id_col = None
|
| 107 |
+
if 'id' in df_up.columns:
|
| 108 |
+
id_col = 'id'
|
| 109 |
+
elif 'Id' in df_up.columns:
|
| 110 |
+
id_col = 'Id'
|
| 111 |
+
|
| 112 |
+
ids = df_up[id_col].copy() if id_col else None
|
| 113 |
+
X_up = df_up.drop(columns=[id_col], errors='ignore')
|
| 114 |
+
|
| 115 |
+
missing_cols = [c for c in feature_names if c not in X_up.columns]
|
| 116 |
+
if missing_cols:
|
| 117 |
+
st.error(f'Missing required columns: {missing_cols}')
|
| 118 |
+
st.stop()
|
| 119 |
+
|
| 120 |
+
X_up = X_up[feature_names]
|
| 121 |
+
preds = predict_from_features(X_up)
|
| 122 |
+
|
| 123 |
+
out = pd.DataFrame({'Predicted': preds})
|
| 124 |
+
if ids is not None:
|
| 125 |
+
out.insert(0, 'Id', ids)
|
| 126 |
+
|
| 127 |
+
st.success('✅ Predictions created successfully.')
|
| 128 |
+
st.dataframe(out.head(30), use_container_width=True)
|
| 129 |
+
|
| 130 |
+
st.download_button(
|
| 131 |
+
'Download predictions as CSV',
|
| 132 |
+
data=out.to_csv(index=False).encode('utf-8'),
|
| 133 |
+
file_name='predictions.csv',
|
| 134 |
+
mime='text/csv'
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
st.subheader('Cluster distribution')
|
| 138 |
+
st.write(pd.Series(preds).value_counts().sort_index())
|
| 139 |
+
|
| 140 |
+
except Exception as e:
|
| 141 |
+
st.error(str(e))
|
| 142 |
+
|
| 143 |
+
else:
|
| 144 |
+
st.info('Upload a CSV file to generate cluster predictions.')
|
| 145 |
+
|
| 146 |
+
# =========================
|
| 147 |
+
# Tab 2: Single Prediction
|
| 148 |
+
# =========================
|
| 149 |
+
with tab_single:
|
| 150 |
+
st.subheader('Enter one row of features and predict its cluster')
|
| 151 |
+
|
| 152 |
+
# Optional: user-friendly note
|
| 153 |
+
st.caption('Tip: If you don’t know values, use a row from your dataset as an example.')
|
| 154 |
+
|
| 155 |
+
# Build form inputs dynamically
|
| 156 |
+
with st.form('single_pred_form'):
|
| 157 |
+
cols = st.columns(2)
|
| 158 |
+
values = {}
|
| 159 |
+
|
| 160 |
+
for i, feat in enumerate(feature_names):
|
| 161 |
+
# Default 0.0 is safe; you can also set dataset mean if you want
|
| 162 |
+
if i % 2 == 0:
|
| 163 |
+
values[feat] = cols[0].number_input(feat, value=0.0)
|
| 164 |
+
else:
|
| 165 |
+
values[feat] = cols[1].number_input(feat, value=0.0)
|
| 166 |
+
|
| 167 |
+
submitted = st.form_submit_button('Predict cluster')
|
| 168 |
+
|
| 169 |
+
if submitted:
|
| 170 |
+
try:
|
| 171 |
+
one_row = pd.DataFrame([values], columns=feature_names)
|
| 172 |
+
pred = predict_from_features(one_row)[0]
|
| 173 |
+
st.success(f'✅ Predicted cluster: **{int(pred)}**')
|
| 174 |
+
except Exception as e:
|
| 175 |
+
st.error(str(e))
|
| 176 |
|
| 177 |
+
# -------------------------
|
| 178 |
+
# Footer
|
| 179 |
+
# -------------------------
|
| 180 |
+
with st.expander('Show expected feature columns'):
|
| 181 |
+
st.write(feature_names)
|