CosmickVisions commited on
Commit
f21bc15
·
verified ·
1 Parent(s): 515cacf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -785
app.py CHANGED
@@ -1,816 +1,112 @@
1
  import streamlit as st
2
- import tensorflow as tf
3
- from tensorflow import keras
4
- import numpy as np
5
  import pandas as pd
6
- import plotly.express as px
7
- import plotly.graph_objects as go
8
- from sklearn.model_selection import train_test_split, GridSearchCV
9
- from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder
10
- from sklearn.decomposition import PCA, TruncatedSVD
11
- from sklearn.manifold import TSNE
12
- import umap.umap_ as umap
13
- import shap
14
- import joblib
15
- from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_curve, auc, mean_squared_error, mean_absolute_error, r2_score, classification_report, silhouette_score
16
- from sklearn.pipeline import Pipeline
17
- from sklearn.compose import ColumnTransformer
18
- from sklearn.impute import SimpleImputer
19
- from sklearn.cluster import KMeans, DBSCAN
20
- from sklearn.mixture import GaussianMixture
21
- from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
22
- from sklearn.linear_model import LogisticRegression, LinearRegression
23
- from sklearn.svm import SVC, SVR
24
- from xgboost import XGBClassifier, XGBRegressor
25
- import matplotlib.pyplot as plt
26
- from io import BytesIO
27
- import time
28
- from PIL import Image
29
- import zipfile
30
  import os
31
 
32
  # Set page config
33
  st.set_page_config(page_title="Neural-Vision Enhanced", layout="wide")
34
 
35
- # Helper Functions for Image Processing
36
- def preprocess_image(image_path, target_size=(224, 224)):
37
- """Preprocess an image by resizing and normalizing it."""
38
- img = Image.open(image_path).convert("RGB")
39
- img = img.resize(target_size)
40
- img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]
41
- return img_array
42
-
43
- def load_image_dataset(zip_path, target_size=(224, 224), problem_type="Classification"):
44
- """Load and preprocess an image dataset from a zip file."""
45
- # Check file size (5GB = 5 * 1024 * 1024 * 1024 bytes)
46
- file_size = os.path.getsize(zip_path) if isinstance(zip_path, str) else zip_path.size
47
- max_size = 5 * 1024 * 1024 * 1024 # 5GB in bytes
48
- if file_size > max_size:
49
- raise ValueError(f"Uploaded file size ({file_size / (1024 * 1024):.2f} MB) exceeds the 5GB limit.")
50
-
51
- # Extract zip file to a temporary directory
52
- with zipfile.ZipFile(zip_path, 'r') as zip_ref:
53
- zip_ref.extractall('temp_images')
54
-
55
- if problem_type == "Classification":
56
- image_paths = []
57
- labels = []
58
- class_names = sorted(os.listdir('temp_images'))
59
- for label, class_name in enumerate(class_names):
60
- class_dir = os.path.join('temp_images', class_name)
61
- if os.path.isdir(class_dir):
62
- for img_name in os.listdir(class_dir):
63
- image_path = os.path.join(class_dir, img_name)
64
- if os.path.isfile(image_path):
65
- image_paths.append(image_path)
66
- labels.append(label)
67
- images = [preprocess_image(path, target_size) for path in image_paths]
68
- images = np.array(images)
69
- labels = np.array(labels)
70
- data = (images, labels, class_names)
71
- else: # Compression or Clustering
72
- image_dir = 'temp_images'
73
- image_paths = [os.path.join(image_dir, img_name) for img_name in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, img_name))]
74
- images = [preprocess_image(path, target_size) for path in image_paths]
75
- images = np.array(images)
76
- data = (images, None, None)
77
-
78
- # Clean up temporary directory
79
- for root, dirs, files in os.walk('temp_images', topdown=False):
80
- for name in files:
81
- os.remove(os.path.join(root, name))
82
- for name in dirs:
83
- os.rmdir(os.path.join(root, name))
84
- os.rmdir('temp_images')
85
-
86
- return data
87
-
88
- # Model Building Functions
89
- def get_model_config(model_type, problem_type):
90
- configs = {
91
- "Random Forest": {
92
- "Regression": {"model_class": RandomForestRegressor, "params": {"n_estimators": 100, "random_state": 42},
93
- "grid_params": {"n_estimators": [50, 100, 200], "max_depth": [None, 10, 20]}},
94
- "Binary Classification": {"model_class": RandomForestClassifier, "params": {"n_estimators": 100, "random_state": 42},
95
- "grid_params": {"n_estimators": [50, 100, 200], "max_depth": [None, 10, 20]}},
96
- "Multi-Class": {"model_class": RandomForestClassifier, "params": {"n_estimators": 100, "random_state": 42},
97
- "grid_params": {"n_estimators": [50, 100, 200], "max_depth": [None, 10, 20]}}
98
- },
99
- "XGBoost": {
100
- "Regression": {"model_class": XGBRegressor, "params": {"n_estimators": 100, "random_state": 42},
101
- "grid_params": {"n_estimators": [50, 100, 200], "max_depth": [3, 5, 7], "learning_rate": [0.01, 0.1, 0.3]}},
102
- "Binary Classification": {"model_class": XGBClassifier, "params": {"n_estimators": 100, "random_state": 42, "use_label_encoder": False, "eval_metric": 'logloss'},
103
- "grid_params": {"n_estimators": [50, 100, 200], "max_depth": [3, 5, 7], "learning_rate": [0.01, 0.1, 0.3]}},
104
- "Multi-Class": {"model_class": XGBClassifier, "params": {"n_estimators": 100, "random_state": 42, "use_label_encoder": False, "eval_metric": 'mlogloss'},
105
- "grid_params": {"n_estimators": [50, 100, 200], "max_depth": [3, 5, 7], "learning_rate": [0.01, 0.1, 0.3]}}
106
- },
107
- "Logistic Regression": {
108
- "Binary Classification": {"model_class": LogisticRegression, "params": {"max_iter": 1000, "random_state": 42},
109
- "grid_params": {"C": [0.1, 1.0, 10.0], "solver": ["lbfgs", "liblinear"]}}
110
- },
111
- "Linear Regression": {
112
- "Regression": {"model_class": LinearRegression, "params": {}, "grid_params": {}}
113
- },
114
- "SVM": {
115
- "Regression": {"model_class": SVR, "params": {"kernel": "rbf"}, "grid_params": {"C": [0.1, 1, 10], "gamma": ["scale", "auto"]}},
116
- "Binary Classification": {"model_class": SVC, "params": {"kernel": "rbf", "random_state": 42}, "grid_params": {"C": [0.1, 1, 10], "gamma": ["scale", "auto"]}},
117
- "Multi-Class": {"model_class": SVC, "params": {"kernel": "rbf", "random_state": 42}, "grid_params": {"C": [0.1, 1, 10], "gamma": ["scale", "auto"]}}
118
- },
119
- "K-Means": {
120
- "Clustering": {"model_class": KMeans, "params": {"n_clusters": 3, "random_state": 42},
121
- "grid_params": {"n_clusters": [2, 3, 4, 5]}}
122
- },
123
- "DBSCAN": {
124
- "Clustering": {"model_class": DBSCAN, "params": {"eps": 0.5, "min_samples": 5},
125
- "grid_params": {"eps": [0.3, 0.5, 0.7], "min_samples": [3, 5, 10]}}
126
- },
127
- "Gaussian Mixture": {
128
- "Clustering": {"model_class": GaussianMixture, "params": {"n_components": 3, "random_state": 42},
129
- "grid_params": {"n_components": [2, 3, 4, 5]}}
130
- }
131
- }
132
- return configs.get(model_type, {}).get(problem_type, {"model_class": None, "params": {}, "grid_params": {}})
133
-
134
- def preprocess_data(X_train, X_test, numerical_features, categorical_features):
135
- numeric_transformer = Pipeline(steps=[
136
- ('imputer', SimpleImputer(strategy='mean')),
137
- ('scaler', StandardScaler())])
138
- categorical_transformer = Pipeline(steps=[
139
- ('imputer', SimpleImputer(strategy='most_frequent')),
140
- ('onehot', OneHotEncoder(handle_unknown='ignore', sparse_output=False))])
141
- preprocessor = ColumnTransformer(
142
- transformers=[
143
- ('num', numeric_transformer, numerical_features),
144
- ('cat', categorical_transformer, categorical_features)],
145
- remainder='drop')
146
- X_train_processed = preprocessor.fit_transform(X_train)
147
- X_test_processed = preprocessor.transform(X_test)
148
- if categorical_features:
149
- onehot_encoder = preprocessor.named_transformers_['cat'].named_steps['onehot']
150
- categorical_feature_names = onehot_encoder.get_feature_names_out(categorical_features)
151
- feature_names = numerical_features + list(categorical_feature_names)
152
- else:
153
- feature_names = numerical_features
154
- return X_train_processed, X_test_processed, feature_names, preprocessor
155
-
156
- def build_neural_network(input_shape, output_units, problem_type, layers_config, optimizer_name="Adam", learning_rate=0.001):
157
- model = keras.Sequential()
158
- model.add(keras.layers.InputLayer(input_shape=input_shape))
159
- for layer in layers_config:
160
- if layer['type'] == 'dense':
161
- model.add(keras.layers.Dense(layer['units'], activation=layer['activation']))
162
- elif layer['type'] == 'dropout':
163
- model.add(keras.layers.Dropout(layer['rate']))
164
- elif layer['type'] == 'conv2d':
165
- model.add(keras.layers.Conv2D(layer['filters'], tuple(layer['kernel_size']), activation=layer['activation'], padding='same'))
166
- elif layer['type'] == 'maxpooling2d':
167
- model.add(keras.layers.MaxPooling2D(pool_size=tuple(layer['pool_size'])))
168
- elif layer['type'] == 'flatten':
169
- model.add(keras.layers.Flatten())
170
- if problem_type == "Regression":
171
- model.add(keras.layers.Dense(1))
172
- loss_function = "mse"
173
- metrics = ["mse"]
174
- elif problem_type == "Binary Classification":
175
- model.add(keras.layers.Dense(1, activation='sigmoid'))
176
- loss_function = "binary_crossentropy"
177
- metrics = ["accuracy"]
178
- elif problem_type == "Multi-Class" or problem_type == "Image Classification":
179
- model.add(keras.layers.Dense(output_units, activation='softmax'))
180
- loss_function = "sparse_categorical_crossentropy" if problem_type == "Image Classification" else "categorical_crossentropy"
181
- metrics = ["accuracy"]
182
- else:
183
- raise ValueError("Unsupported problem type")
184
- optimizer = {"Adam": keras.optimizers.Adam, "SGD": keras.optimizers.SGD, "RMSprop": keras.optimizers.RMSprop}.get(optimizer_name)(learning_rate=learning_rate)
185
- model.compile(optimizer=optimizer, loss=loss_function, metrics=metrics)
186
- return model
187
-
188
- def build_autoencoder(input_shape, encoding_dim, layers_config, autoencoder_type="Standard", optimizer_name="Adam", learning_rate=0.001):
189
- if autoencoder_type == "Variational":
190
- inputs = keras.layers.Input(shape=input_shape)
191
- x = keras.layers.Flatten()(inputs) if len(input_shape) > 1 else inputs
192
- for layer in layers_config:
193
- if layer['type'] == 'dense':
194
- x = keras.layers.Dense(layer['units'], activation=layer['activation'])(x)
195
- z_mean = keras.layers.Dense(encoding_dim, name='z_mean')(x)
196
- z_log_var = keras.layers.Dense(encoding_dim, name='z_log_var')(x)
197
-
198
- def sampling(args):
199
- z_mean, z_log_var = args
200
- epsilon = keras.backend.random_normal(shape=(keras.backend.shape(z_mean)[0], encoding_dim))
201
- return z_mean + keras.backend.exp(0.5 * z_log_var) * epsilon
202
-
203
- z = keras.layers.Lambda(sampling, name='z')([z_mean, z_log_var])
204
- encoder = keras.Model(inputs, [z_mean, z_log_var, z], name='encoder')
205
-
206
- decoder_input = keras.layers.Input(shape=(encoding_dim,))
207
- x = decoder_input
208
- for layer in reversed(layers_config):
209
- if layer['type'] == 'dense':
210
- x = keras.layers.Dense(layer['units'], activation=layer['activation'])(x)
211
- x = keras.layers.Dense(np.prod(input_shape), activation='sigmoid')(x)
212
- outputs = keras.layers.Reshape(input_shape)(x) if len(input_shape) > 1 else x
213
- decoder = keras.Model(decoder_input, outputs, name='decoder')
214
-
215
- vae_outputs = decoder(encoder(inputs)[2])
216
- autoencoder = keras.Model(inputs, vae_outputs, name='vae')
217
-
218
- reconstruction_loss = keras.losses.binary_crossentropy(keras.backend.flatten(inputs), keras.backend.flatten(vae_outputs))
219
- reconstruction_loss *= np.prod(input_shape)
220
- kl_loss = 1 + z_log_var - keras.backend.square(z_mean) - keras.backend.exp(z_log_var)
221
- kl_loss = keras.backend.sum(kl_loss, axis=-1) * -0.5
222
- vae_loss = keras.backend.mean(reconstruction_loss + kl_loss)
223
- autoencoder.add_loss(vae_loss)
224
- else: # Standard or Denoising
225
- encoder = keras.Sequential([keras.layers.InputLayer(input_shape=input_shape)])
226
- for layer in layers_config:
227
- if layer['type'] == 'dense':
228
- encoder.add(keras.layers.Dense(layer['units'], activation=layer['activation']))
229
- elif layer['type'] == 'dropout':
230
- encoder.add(keras.layers.Dropout(layer['rate']))
231
- encoder.add(keras.layers.Dense(encoding_dim, activation='relu', name='encoded'))
232
-
233
- decoder = keras.Sequential([keras.layers.InputLayer(input_shape=(encoding_dim,))])
234
- for layer in reversed(layers_config):
235
- if layer['type'] == 'dense':
236
- decoder.add(keras.layers.Dense(layer['units'], activation=layer['activation']))
237
- decoder.add(keras.layers.Dense(np.prod(input_shape), activation='sigmoid'))
238
- decoder.add(keras.layers.Reshape(input_shape) if len(input_shape) > 1 else keras.layers.Lambda(lambda x: x))
239
-
240
- autoencoder_input = keras.layers.Input(shape=input_shape)
241
- encoded = encoder(autoencoder_input)
242
- decoded = decoder(encoded)
243
- autoencoder = keras.Model(autoencoder_input, decoded)
244
-
245
- optimizer = {"Adam": keras.optimizers.Adam, "SGD": keras.optimizers.SGD, "RMSprop": keras.optimizers.RMSprop}.get(optimizer_name)(learning_rate=learning_rate)
246
- autoencoder.compile(optimizer=optimizer, loss='mse', metrics=['mse'])
247
- return autoencoder, encoder, decoder
248
-
249
- class StreamlitCallback(keras.callbacks.Callback):
250
- def __init__(self, placeholder):
251
- super().__init__()
252
- self.placeholder = placeholder
253
- self.epoch_data = []
254
-
255
- def on_epoch_end(self, epoch, logs=None):
256
- # Append the logs for the current epoch
257
- self.epoch_data.append(logs)
258
-
259
- # Create a DataFrame from the logs
260
- df = pd.DataFrame(self.epoch_data)
261
-
262
- # Create the Plotly figure
263
- fig = go.Figure()
264
-
265
- # Add training loss trace
266
- fig.add_trace(go.Scatter(
267
- x=df.index, y=df['loss'], mode='lines', name='Training Loss'
268
- ))
269
-
270
- # Add validation loss trace (if available)
271
- if 'val_loss' in df.columns:
272
- fig.add_trace(go.Scatter(
273
- x=df.index, y=df['val_loss'], mode='lines', name='Validation Loss'
274
- ))
275
-
276
- # Add metric trace (e.g., accuracy or MSE)
277
- metric_name = 'accuracy' if 'accuracy' in df.columns else 'mse'
278
- if metric_name in df.columns:
279
- fig.add_trace(go.Scatter(
280
- x=df.index, y=df[metric_name], mode='lines', name=metric_name.capitalize()
281
- ))
282
-
283
- # Update the layout
284
- fig.update_layout(
285
- title="Training Progress",
286
- xaxis_title="Epoch",
287
- yaxis_title="Value",
288
- legend_title="Metrics"
289
- )
290
-
291
- # Update the placeholder with the new figure
292
- self.placeholder.plotly_chart(fig, use_container_width=True)
293
-
294
- def train_model(model, X_train, y_train, X_test, y_test, epochs, batch_size, problem_type, input_data=None, target_data=None, do_grid_search=False, params=None, grid_params=None, training_placeholder=None):
295
- """Train the model and optionally display live training progress for Keras models."""
296
- start_time = time.time()
297
- history = None
298
-
299
- if isinstance(model, keras.Model):
300
- if training_placeholder is not None:
301
- streamlit_callback = StreamlitCallback(training_placeholder)
302
- history = model.fit(
303
- input_data if input_data is not None else X_train,
304
- target_data if target_data is not None else y_train,
305
- epochs=epochs,
306
- batch_size=batch_size,
307
- validation_data=(X_test, y_test if y_test is not None else X_test),
308
- verbose=0,
309
- callbacks=[streamlit_callback]
310
- )
311
- else:
312
- history = model.fit(
313
- input_data if input_data is not None else X_train,
314
- target_data if target_data is not None else y_train,
315
- epochs=epochs,
316
- batch_size=batch_size,
317
- validation_data=(X_test, y_test if y_test is not None else X_test),
318
- verbose=1
319
- )
320
- else:
321
- if do_grid_search and grid_params:
322
- grid_search = GridSearchCV(model, grid_params, cv=3, n_jobs=-1, scoring='accuracy' if problem_type in ["Binary Classification", "Multi-Class"] else 'neg_mean_squared_error')
323
- grid_search.fit(X_train, y_train)
324
- model = grid_search.best_estimator_
325
- st.write("Best parameters found by Grid Search:", grid_search.best_params_)
326
- else:
327
- model.set_params(**params)
328
- model.fit(X_train, y_train)
329
-
330
- training_time = time.time() - start_time
331
- return history, model, training_time
332
-
333
- def evaluate_model(model, X_test, y_test, problem_type, le=None, encoder=None):
334
- y_pred = model.predict(X_test)
335
- metrics = {}
336
- if problem_type == "Regression":
337
- metrics['mse'] = mean_squared_error(y_test, y_pred)
338
- metrics['mae'] = mean_absolute_error(y_test, y_pred)
339
- metrics['rmse'] = np.sqrt(metrics['mse'])
340
- metrics['r2'] = r2_score(y_test, y_pred)
341
- return metrics, y_pred.flatten()
342
- elif problem_type in ["Binary Classification", "Multi-Class", "Image Classification"]:
343
- if problem_type == "Image Classification":
344
- y_pred_classes = np.argmax(y_pred, axis=1)
345
- y_test_classes = y_test
346
- else:
347
- y_pred_classes = (y_pred > 0.5).astype(int).flatten() if problem_type == "Binary Classification" else np.argmax(y_pred, axis=1)
348
- y_test_classes = y_test if problem_type == "Binary Classification" else np.argmax(y_test, axis=1)
349
- metrics['accuracy'] = accuracy_score(y_test_classes, y_pred_classes)
350
- metrics['precision'] = precision_score(y_test_classes, y_pred_classes, average='weighted', zero_division=0)
351
- metrics['recall'] = recall_score(y_test_classes, y_pred_classes, average='weighted', zero_division=0)
352
- metrics['f1'] = f1_score(y_test_classes, y_pred_classes, average='weighted', zero_division=0)
353
- return metrics, y_pred_classes
354
- elif problem_type == "Clustering":
355
- labels = model.labels_ if hasattr(model, 'labels_') else model.predict(X_test)
356
- metrics["n_clusters"] = len(np.unique(labels))
357
- if len(np.unique(labels)) > 1:
358
- metrics["silhouette"] = silhouette_score(X_test, labels)
359
- return metrics, labels
360
- elif problem_type == "Compression":
361
- metrics['mse'] = mean_squared_error(X_test, y_pred)
362
- metrics['mae'] = mean_absolute_error(X_test, y_pred)
363
- metrics['rmse'] = np.sqrt(metrics['mse'])
364
- compressed_data = encoder.predict(X_test) if encoder else None
365
- return metrics, y_pred, compressed_data
366
-
367
- def save_model(model, preprocessor, features, target, problem_type, filename="model.pkl"):
368
- model_data = {
369
- 'model': model,
370
- 'preprocessor': preprocessor,
371
- 'features': features,
372
- 'target': target,
373
- 'problem_type': problem_type,
374
- 'timestamp': time.strftime("%Y%m%d_%H%M%S")
375
- }
376
- if isinstance(model, keras.Model):
377
- model.save("temp_model.h5")
378
- model_data['model_path'] = "temp_model.h5"
379
- joblib.dump(model_data, filename)
380
- return filename
381
-
382
- def load_model(model_file):
383
- model_data = joblib.load(model_file)
384
- if 'model_path' in model_data:
385
- model_data['model'] = keras.models.load_model(model_data['model_path'])
386
- return model_data
387
-
388
  # Sidebar Navigation
389
  with st.sidebar:
390
  st.title("🔮 Neural-Vision Enhanced")
391
  st.markdown("Your AI-powered model toolbox.")
392
  st.markdown("---")
393
  app_mode = st.selectbox("Navigation", ["Data Upload", "Model Training", "Validation & Exploration"])
394
- data_type = st.selectbox("Data Type", ["Tabular", "Image"])
395
  st.markdown("---")
396
- st.markdown("**Dependencies**: `tensorflow`, `shap`, `umap-learn`, `joblib`, `scikit-learn`, `plotly`, `xgboost`, `pillow`")
397
- st.markdown("Created by Calvin Allen-Crawford | v1.3 | © 2025")
398
 
399
  # Main App Sections
400
  if app_mode == "Data Upload":
401
  st.title("📤 Data Upload")
402
- col1, col2, col3 = st.columns([1, 2, 1])
403
- with col2:
404
- if data_type == "Tabular":
405
- uploaded_file = st.file_uploader("Upload CSV Dataset", type=["csv"])
406
- if uploaded_file:
407
- df = pd.read_csv(uploaded_file)
408
- st.session_state.df = df
409
- st.write("---")
410
- st.subheader("Dataset Preview")
411
- st.dataframe(df.head(10))
412
- st.write("---")
413
- st.subheader("Statistics")
414
- col1, col2, col3 = st.columns(3)
415
- with col1: st.metric("Rows", df.shape[0])
416
- with col2: st.metric("Columns", df.shape[1])
417
- with col3: st.metric("Missing Values", df.isna().sum().sum())
418
- else: # Image
419
- uploaded_file = st.file_uploader("Upload Zip File with Images (Max 5GB)", type=["zip"])
420
- if uploaded_file:
421
- # Save uploaded file temporarily to check size
422
- with open("temp_upload.zip", "wb") as f:
423
- f.write(uploaded_file.getbuffer())
424
- try:
425
- problem_type = st.selectbox("Problem Type for Image Data", ["Image Classification", "Compression", "Clustering"])
426
- images, labels, class_names = load_image_dataset("temp_upload.zip", problem_type=problem_type)
427
- st.session_state.images = images
428
- st.session_state.labels = labels
429
- st.session_state.class_names = class_names if problem_type == "Image Classification" else None
430
- st.write(f"Loaded {len(images)} images.")
431
- if problem_type == "Image Classification":
432
- st.write(f"Classes: {class_names}")
433
- st.image(images[:5], caption=["Sample " + str(i+1) for i in range(min(5, len(images)))], width=100)
434
- except ValueError as e:
435
- st.error(str(e))
436
- finally:
437
- os.remove("temp_upload.zip")
438
 
439
  elif app_mode == "Model Training":
440
  st.title("🧠 Model Training")
441
- if data_type == "Tabular" and 'df' not in st.session_state:
442
- st.warning("Please upload a tabular dataset first.")
443
  st.stop()
444
- elif data_type == "Image" and 'images' not in st.session_state:
445
- st.warning("Please upload an image dataset first.")
446
- st.stop()
447
-
448
- if data_type == "Tabular":
449
- df = st.session_state.df
450
- problem_type = st.selectbox("Problem Type", ["Regression", "Binary Classification", "Multi-Class", "Clustering", "Compression"])
451
- features = st.multiselect("Select Features", df.columns)
452
- target = st.selectbox("Select Target", df.columns) if problem_type not in ["Clustering", "Compression"] else None
453
- else:
454
- problem_type = st.selectbox("Problem Type", ["Image Classification", "Compression", "Clustering"])
455
- features = ["images"]
456
- target = "labels" if problem_type == "Image Classification" else None
457
-
458
- if problem_type not in ["Clustering", "Compression"] and data_type == "Tabular" and target:
459
- unique_target_values = df[target].nunique()
460
- if problem_type == "Binary Classification" and unique_target_values != 2:
461
- st.error("Binary Classification requires exactly 2 unique target values.")
462
- st.stop()
463
- elif problem_type == "Multi-Class" and unique_target_values < 2:
464
- st.error("Multi-Class Classification requires at least 2 unique target values.")
465
- st.stop()
466
- elif problem_type == "Regression" and not pd.api.types.is_numeric_dtype(df[target]):
467
- st.error("Regression requires a numerical target variable.")
468
- st.stop()
469
 
470
- model_types = {
471
- "Regression": ["Neural Network", "Random Forest", "XGBoost", "Linear Regression", "SVM"],
472
- "Binary Classification": ["Neural Network", "Random Forest", "XGBoost", "Logistic Regression", "SVM"],
473
- "Multi-Class": ["Neural Network", "Random Forest", "XGBoost", "SVM"],
474
- "Clustering": ["K-Means", "DBSCAN", "Gaussian Mixture"],
475
- "Compression": ["Autoencoder"],
476
- "Image Classification": ["Neural Network", "SVM"]
477
- }[problem_type]
478
- model_type = st.selectbox("Model Type", model_types)
479
-
480
- if model_type == "Neural Network":
481
- st.subheader("Neural Network Configuration")
482
- optimizer_name = st.selectbox("Optimizer", ["Adam", "SGD", "RMSprop"])
483
- layers_config = st.session_state.get('layers_config', [])
484
- layer_type = st.selectbox("Layer Type", ["Dense", "Dropout"] if data_type == "Tabular" else ["Conv2D", "MaxPooling2D", "Flatten", "Dense", "Dropout"])
485
- if layer_type == "Dense":
486
- units = st.number_input("Units", min_value=1, value=64)
487
- activation = st.selectbox("Activation", ["relu", "sigmoid", "tanh"])
488
- if st.button("Add Layer"):
489
- layers_config.append({"type": "dense", "units": units, "activation": activation})
490
- elif layer_type == "Dropout":
491
- rate = st.number_input("Dropout Rate", 0.0, 1.0, 0.2)
492
- if st.button("Add Layer"):
493
- layers_config.append({"type": "dropout", "rate": rate})
494
- elif layer_type == "Conv2D":
495
- filters = st.number_input("Filters", min_value=1, value=32)
496
- kernel_size = st.multiselect("Kernel Size", options=[1, 3, 5], default=[3])
497
- activation = st.selectbox("Activation", ["relu", "sigmoid", "tanh"])
498
- if st.button("Add Layer"):
499
- layers_config.append({"type": "conv2d", "filters": filters, "kernel_size": kernel_size, "activation": activation})
500
- elif layer_type == "MaxPooling2D":
501
- pool_size = st.multiselect("Pool Size", options=[2, 3], default=[2])
502
- if st.button("Add Layer"):
503
- layers_config.append({"type": "maxpooling2d", "pool_size": pool_size})
504
- elif layer_type == "Flatten":
505
- if st.button("Add Layer"):
506
- layers_config.append({"type": "flatten"})
507
- if layers_config:
508
- st.write("Current Layers:", layers_config)
509
- if st.button("Clear Layers"):
510
- layers_config.clear()
511
- st.session_state.layers_config = layers_config
512
- st.rerun()
513
- st.session_state.layers_config = layers_config
514
- elif model_type == "Autoencoder":
515
- st.subheader("Autoencoder Configuration")
516
- encoding_dim = st.number_input("Encoding Dimension", min_value=1, value=32)
517
- optimizer_name = st.selectbox("Optimizer", ["Adam", "SGD", "RMSprop"])
518
- autoencoder_type = st.selectbox("Autoencoder Type", ["Standard", "Variational", "Denoising"])
519
- if autoencoder_type == "Denoising":
520
- noise_level = st.slider("Noise Level", 0.0, 1.0, 0.1)
521
- layers_config = st.session_state.get('layers_config', [])
522
- layer_type = st.selectbox("Layer Type (Encoder)", ["Dense", "Dropout"])
523
- if layer_type == "Dense":
524
- units = st.number_input("Units", min_value=1, value=64)
525
- activation = st.selectbox("Activation", ["relu", "sigmoid", "tanh"])
526
- if st.button("Add Layer"):
527
- layers_config.append({"type": "dense", "units": units, "activation": activation})
528
- elif layer_type == "Dropout":
529
- rate = st.number_input("Dropout Rate", 0.0, 1.0, 0.2)
530
- if st.button("Add Layer"):
531
- layers_config.append({"type": "dropout", "rate": rate})
532
- if layers_config:
533
- st.write("Current Encoder Layers:", layers_config)
534
- if st.button("Clear Layers"):
535
- layers_config.clear()
536
- st.session_state.layers_config = layers_config
537
- st.rerun()
538
- st.session_state.layers_config = layers_config
539
- else:
540
- st.subheader("Model Hyperparameters")
541
- config = get_model_config(model_type, problem_type)
542
- params = {}
543
- for param_name, param_values in config["grid_params"].items():
544
- if isinstance(param_values[0], (int, float)) and len(param_values) > 2:
545
- slider_value = st.slider(param_name, min_value=float(min(param_values)), max_value=float(max(param_values)), value=float(param_values[1]))
546
- if param_name in {'n_estimators', 'n_clusters', 'min_samples', 'n_components', 'max_depth'}:
547
- params[param_name] = int(slider_value)
548
- else:
549
- params[param_name] = slider_value
550
- else:
551
- params[param_name] = st.selectbox(param_name, param_values)
552
- do_grid_search = st.checkbox("Use Grid Search for Tuning", value=False)
553
-
554
- col1, col2, col3 = st.columns(3)
555
- with col1: epochs = st.number_input("Epochs", min_value=1, value=10) if model_type in ["Neural Network", "Autoencoder"] else 10
556
- with col2: batch_size = st.number_input("Batch Size", min_value=1, value=32) if model_type in ["Neural Network", "Autoencoder"] else 32
557
- with col3: learning_rate = st.number_input("Learning Rate", min_value=0.0, value=0.001, step=0.0001) if model_type in ["Neural Network", "Autoencoder"] else 0.001
558
-
559
- uploaded_model = st.file_uploader("Upload Pre-trained Model (.h5)", type=["h5"]) if model_type in ["Neural Network", "Autoencoder"] else None
560
- base_model = keras.models.load_model(uploaded_model) if uploaded_model else None
561
-
562
- if st.button("Train Model"):
563
- with st.spinner("Preparing data..."):
564
- if data_type == "Tabular":
565
- X = df[features]
566
- y = df[target] if problem_type not in ["Clustering", "Compression"] else None
567
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) if problem_type not in ["Clustering", "Compression"] else (X, X.copy(), None, None)
568
- numerical_features = X.select_dtypes(include=np.number).columns.tolist()
569
- categorical_features = X.select_dtypes(exclude=np.number).columns.tolist()
570
- X_train_processed, X_test_processed, feature_names, preprocessor = preprocess_data(X_train, X_test, numerical_features, categorical_features)
571
- le = None
572
- if problem_type in ["Binary Classification", "Multi-Class"] and y is not None:
573
- le = LabelEncoder()
574
- y_train = le.fit_transform(y_train)
575
- y_test = le.transform(y_test)
576
- if problem_type == "Multi-Class":
577
- y_train = tf.keras.utils.to_categorical(y_train)
578
- y_test = tf.keras.utils.to_categorical(y_test)
579
- else: # Image
580
- X_train, X_test, y_train, y_test = train_test_split(st.session_state.images, st.session_state.labels, test_size=0.2, random_state=42) if problem_type == "Image Classification" else (st.session_state.images, st.session_state.images.copy(), None, None)
581
- preprocessor = None
582
- feature_names = ["image_features"]
583
- le = None
584
-
585
- with st.spinner("Training model..."):
586
- training_placeholder = st.empty() # Define the placeholder here
587
- if model_type == "Neural Network":
588
- if not layers_config and not base_model:
589
- st.error("Please add layers or upload a pre-trained model.")
590
- st.stop()
591
- input_shape = (X_train_processed.shape[1],) if data_type == "Tabular" else (224, 224, 3)
592
- output_units = len(st.session_state.class_names) if problem_type == "Image Classification" else (y_train.shape[1] if problem_type == "Multi-Class" else 1)
593
- model = base_model if base_model else build_neural_network(input_shape, output_units, problem_type, layers_config, optimizer_name, learning_rate)
594
- history, model, training_time = train_model(
595
- model,
596
- X_train_processed if data_type == "Tabular" else X_train,
597
- y_train,
598
- X_test_processed if data_type == "Tabular" else X_test,
599
- y_test,
600
- epochs,
601
- batch_size,
602
- problem_type,
603
- training_placeholder=training_placeholder
604
- )
605
- elif model_type == "Autoencoder":
606
- if not layers_config and not base_model:
607
- st.error("Please add layers to the encoder or upload a pre-trained model.")
608
- st.stop()
609
- input_shape = (X_train_processed.shape[1],) if data_type == "Tabular" else (224, 224, 3)
610
- model, encoder, decoder = (base_model, None, None) if base_model else build_autoencoder(input_shape, encoding_dim, layers_config, autoencoder_type, optimizer_name, learning_rate)
611
- if autoencoder_type == "Denoising":
612
- X_train_noisy = X_train_processed + noise_level * np.random.normal(size=X_train_processed.shape) if data_type == "Tabular" else X_train + noise_level * np.random.normal(size=X_train.shape)
613
- input_data = X_train_noisy
614
- target_data = X_train_processed if data_type == "Tabular" else X_train
615
- else:
616
- input_data = X_train_processed if data_type == "Tabular" else X_train
617
- target_data = X_train_processed if data_type == "Tabular" else X_train
618
- history, model, training_time = train_model(
619
- model,
620
- X_train_processed if data_type == "Tabular" else X_train,
621
- None,
622
- X_test_processed if data_type == "Tabular" else X_test,
623
- None,
624
- epochs,
625
- batch_size,
626
- problem_type,
627
- input_data=input_data,
628
- target_data=target_data,
629
- training_placeholder=training_placeholder
630
- )
631
- st.session_state.encoder = encoder
632
- st.session_state.decoder = decoder
633
- else:
634
- config = get_model_config(model_type, problem_type)
635
- model = config['model_class'](**config['params'])
636
- X_train_flat = X_train_processed if data_type == "Tabular" else X_train.reshape(X_train.shape[0], -1)
637
- X_test_flat = X_test_processed if data_type == "Tabular" else X_test.reshape(X_test.shape[0], -1)
638
- history, model, training_time = train_model(
639
- model,
640
- X_train_flat,
641
- y_train,
642
- X_test_flat,
643
- y_test,
644
- epochs,
645
- batch_size,
646
- problem_type,
647
- do_grid_search=do_grid_search,
648
- params=params,
649
- grid_params=config['grid_params'],
650
- training_placeholder=training_placeholder
651
- )
652
-
653
- st.session_state.model = model
654
- st.session_state.preprocessor = preprocessor
655
- st.session_state.features = features
656
- st.session_state.target = target
657
- st.session_state.problem_type = problem_type
658
- st.session_state.le = le
659
-
660
- filename = save_model(model, preprocessor, features, target, problem_type)
661
- with open(filename, 'rb') as f:
662
- st.download_button("Download Model", f, file_name=filename)
663
- st.success(f"Model trained in {training_time:.2f}s and saved!")
664
 
665
  elif app_mode == "Validation & Exploration":
666
  st.title("🔍 Validation & Exploration")
667
- if data_type == "Tabular" and ('model' not in st.session_state or 'df' not in st.session_state):
668
- st.warning("Please upload a tabular dataset and train a model first.")
669
- st.stop()
670
- elif data_type == "Image" and ('model' not in st.session_state or 'images' not in st.session_state):
671
- st.warning("Please upload an image dataset and train a model first.")
672
  st.stop()
673
 
674
- if data_type == "Tabular":
675
- df = st.session_state.df
676
- X = df[st.session_state.features]
677
- y = df[st.session_state.target] if st.session_state.problem_type not in ["Clustering", "Compression"] else None
678
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) if st.session_state.problem_type not in ["Clustering", "Compression"] else (X, X.copy(), None, None)
679
- numerical_features = X.select_dtypes(include=np.number).columns.tolist()
680
- categorical_features = X.select_dtypes(exclude=np.number).columns.tolist()
681
- X_train_processed, X_test_processed, feature_names, _ = preprocess_data(X_train, X_test, numerical_features, categorical_features)
682
- if st.session_state.problem_type in ["Binary Classification", "Multi-Class"] and y is not None:
683
- y_train = st.session_state.le.transform(y_train) if st.session_state.le else y_train
684
- y_test = st.session_state.le.transform(y_test) if st.session_state.le else y_test
685
- if st.session_state.problem_type == "Multi-Class":
686
- y_train = tf.keras.utils.to_categorical(y_train)
687
- y_test = tf.keras.utils.to_categorical(y_test)
688
- else:
689
- X_train, X_test, y_train, y_test = train_test_split(st.session_state.images, st.session_state.labels, test_size=0.2, random_state=42) if st.session_state.problem_type == "Image Classification" else (st.session_state.images, st.session_state.images.copy(), None, None)
690
- X_train_processed, X_test_processed = X_train, X_test
691
- feature_names = ["image_features"]
692
- if st.session_state.problem_type == "Image Classification":
693
- le = None
694
-
695
- model = st.session_state.model
696
- problem_type = st.session_state.problem_type
697
- encoder = st.session_state.get('encoder', None)
698
-
699
- # Validation
700
- st.subheader("Model Validation")
701
- if problem_type == "Compression":
702
- metrics, y_pred, compressed_data = evaluate_model(model, X_test_processed, None, problem_type, None, encoder)
703
- else:
704
- metrics, y_pred = evaluate_model(model, X_test_processed, y_test, problem_type, st.session_state.le if data_type == "Tabular" else None)
705
-
706
- col1, col2 = st.columns(2)
707
- with col1:
708
- for metric, value in metrics.items():
709
- st.metric(metric, f"{value:.4f}" if isinstance(value, float) else value)
710
- with col2:
711
- if problem_type == "Regression":
712
- fig = px.scatter(x=y_test, y=y_pred, labels={"x": "Actual", "y": "Predicted"}, title="Predicted vs Actual")
713
- st.plotly_chart(fig)
714
- elif problem_type in ["Binary Classification", "Image Classification"]:
715
- if problem_type == "Binary Classification":
716
- y_pred_proba = model.predict_proba(X_test_processed)[:, 1] if hasattr(model, 'predict_proba') else y_pred
717
- fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
718
- roc_auc = auc(fpr, tpr)
719
- fig = px.area(x=fpr, y=tpr, title=f"ROC Curve (AUC = {roc_auc:.2f})", labels={"x": "False Positive Rate", "y": "True Positive Rate"})
720
- st.plotly_chart(fig)
721
- else:
722
- cm = np.zeros((len(st.session_state.class_names), len(st.session_state.class_names)))
723
- for i, j in zip(y_test, y_pred):
724
- cm[i, j] += 1
725
- fig = px.imshow(cm, title="Confusion Matrix", labels={"x": "Predicted", "y": "Actual"})
726
- st.plotly_chart(fig)
727
- report = classification_report(y_test, y_pred, target_names=st.session_state.class_names, zero_division=0)
728
- st.text("Classification Report:\n" + report)
729
- elif problem_type == "Multi-Class":
730
- y_pred_classes = np.argmax(model.predict(X_test_processed), axis=1)
731
- y_test_classes = np.argmax(y_test, axis=1)
732
- cm = np.zeros((y_train.shape[1], y_train.shape[1]))
733
- for i, j in zip(y_test_classes, y_pred_classes):
734
- cm[i, j] += 1
735
- fig = px.imshow(cm, title="Confusion Matrix", labels={"x": "Predicted", "y": "Actual"})
736
- st.plotly_chart(fig)
737
- report = classification_report(y_test_classes, y_pred_classes, target_names=st.session_state.le.classes_ if st.session_state.le else [str(i) for i in range(y_train.shape[1])], zero_division=0)
738
- st.text("Classification Report:\n" + report)
739
- elif problem_type == "Clustering":
740
- labels = y_pred
741
- fig = px.scatter(x=X_test_processed[:, 0] if X_test_processed.shape[-1] == 1 else X_test_processed.reshape(X_test_processed.shape[0], -1)[:, 0],
742
- y=X_test_processed[:, 1] if X_test_processed.shape[-1] == 1 else X_test_processed.reshape(X_test_processed.shape[0], -1)[:, 1],
743
- color=labels, title="Cluster Visualization")
744
- st.plotly_chart(fig)
745
- elif problem_type == "Compression":
746
- st.image([X_test_processed[0], y_pred[0]], caption=["Original", "Reconstructed"], width=200) if data_type == "Image" else None
747
- fig = px.scatter(x=X_test_processed.flatten()[:1000], y=y_pred.flatten()[:1000], labels={"x": "Original", "y": "Reconstructed"}, title="Original vs Reconstructed (First 1000 Values)")
748
- st.plotly_chart(fig)
749
-
750
- # Dimensionality Reduction
751
- st.subheader("Dimensionality Reduction")
752
- methods = ["PCA", "SVD", "t-SNE", "UMAP"]
753
- if problem_type == "Compression" and 'encoder' in st.session_state:
754
- methods.append("Autoencoder")
755
- method = st.selectbox("Method", methods)
756
- n_components = st.slider("Components", 2, min(10 if data_type == "Tabular" else X_train_processed.shape[1], 10), 2)
757
-
758
- if method == "Autoencoder" and 'encoder' in st.session_state:
759
- X_reduced = st.session_state.encoder.predict(X_train_processed)
760
- if X_reduced.shape[1] < n_components:
761
- st.warning(f"Autoencoder encoding dimension is {X_reduced.shape[1]}, using that instead of {n_components}.")
762
- n_components = X_reduced.shape[1]
763
- else:
764
- X_flat = X_train_processed if data_type == "Tabular" else X_train_processed.reshape(X_train_processed.shape[0], -1)
765
- if method == "PCA":
766
- reducer = PCA(n_components=n_components)
767
- X_reduced = reducer.fit_transform(X_flat)
768
- fig = px.bar(x=range(n_components), y=reducer.explained_variance_ratio_, title="Explained Variance Ratio")
769
- st.plotly_chart(fig)
770
- elif method == "SVD":
771
- reducer = TruncatedSVD(n_components=n_components)
772
- X_reduced = reducer.fit_transform(X_flat)
773
- fig = px.bar(x=range(n_components), y=reducer.explained_variance_ratio_, title="Explained Variance Ratio")
774
- st.plotly_chart(fig)
775
- elif method == "t-SNE":
776
- with st.spinner("Running t-SNE..."):
777
- X_reduced = TSNE(n_components=n_components, random_state=42).fit_transform(X_flat)
778
- elif method == "UMAP":
779
- with st.spinner("Running UMAP..."):
780
- X_reduced = umap.UMAP(n_components=n_components, random_state=42).fit_transform(X_flat)
781
-
782
- if n_components >= 2:
783
- if n_components == 2:
784
- fig = px.scatter(x=X_reduced[:, 0], y=X_reduced[:, 1], color=y_train if problem_type not in ["Clustering", "Compression"] else y_pred,
785
- title=f"{method} Visualization")
786
- elif n_components == 3:
787
- fig = px.scatter_3d(x=X_reduced[:, 0], y=X_reduced[:, 1], z=X_reduced[:, 2], color=y_train if problem_type not in ["Clustering", "Compression"] else y_pred,
788
- title=f"{method} Visualization")
789
- st.plotly_chart(fig)
790
-
791
- # Interpretability
792
- if problem_type not in ["Compression", "Clustering"]:
793
- st.subheader("Interpretability")
794
- try:
795
- X_flat = X_test_processed if data_type == "Tabular" else X_test_processed.reshape(X_test_processed.shape[0], -1)
796
- if isinstance(model, keras.Model):
797
- explainer = shap.DeepExplainer(model, X_train_processed[:50] if data_type == "Tabular" else X_train_processed[:50])
798
- shap_values = explainer.shap_values(X_flat[:50])
799
- else:
800
- explainer = shap.Explainer(model, X_flat)
801
- shap_values = explainer.shap_values(X_flat[:50])
802
- if problem_type == "Regression":
803
- shap_fig, ax = plt.subplots()
804
- shap.summary_plot(shap_values, X_flat[:50], feature_names=feature_names, show=False)
805
- st.pyplot(shap_fig)
806
- elif problem_type in ["Binary Classification", "Multi-Class", "Image Classification"]:
807
- class_names = st.session_state.le.classes_ if st.session_state.le and data_type == "Tabular" else st.session_state.class_names if problem_type == "Image Classification" else [str(i) for i in range(y_train.shape[1])]
808
- for i in range(min(len(class_names), len(shap_values))):
809
- shap_fig, ax = plt.subplots()
810
- shap.summary_plot(shap_values[i] if isinstance(shap_values, list) else shap_values, X_flat[:50], feature_names=feature_names, class_names=class_names, show=False)
811
- st.pyplot(shap_fig)
812
- except Exception as e:
813
- st.error(f"Error generating SHAP plot: {e}")
814
 
815
  # Custom CSS
816
  st.markdown("""
 
1
  import streamlit as st
 
 
 
2
  import pandas as pd
3
+ from pycaret.classification import *
4
+ from pycaret.regression import *
5
+ from pycaret.clustering import *
6
+ from sklearn.model_selection import train_test_split
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  import os
8
 
9
  # Set page config
10
  st.set_page_config(page_title="Neural-Vision Enhanced", layout="wide")
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  # Sidebar Navigation
13
  with st.sidebar:
14
  st.title("🔮 Neural-Vision Enhanced")
15
  st.markdown("Your AI-powered model toolbox.")
16
  st.markdown("---")
17
  app_mode = st.selectbox("Navigation", ["Data Upload", "Model Training", "Validation & Exploration"])
18
+ data_type = st.selectbox("Data Type", ["Tabular"])
19
  st.markdown("---")
20
+ st.markdown("**Dependencies**: `pycaret`, `pandas`, `streamlit`")
21
+ st.markdown("Created by Calvin Allen-Crawford | v2.0 | © 2025")
22
 
23
  # Main App Sections
24
  if app_mode == "Data Upload":
25
  st.title("📤 Data Upload")
26
+ uploaded_file = st.file_uploader("Upload CSV Dataset", type=["csv"])
27
+ if uploaded_file:
28
+ df = pd.read_csv(uploaded_file)
29
+ st.session_state.df = df
30
+ st.write("---")
31
+ st.subheader("Dataset Preview")
32
+ st.dataframe(df.head(10))
33
+ st.write("---")
34
+ st.subheader("Statistics")
35
+ col1, col2, col3 = st.columns(3)
36
+ with col1: st.metric("Rows", df.shape[0])
37
+ with col2: st.metric("Columns", df.shape[1])
38
+ with col3: st.metric("Missing Values", df.isna().sum().sum())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  elif app_mode == "Model Training":
41
  st.title("🧠 Model Training")
42
+ if 'df' not in st.session_state:
43
+ st.warning("Please upload a dataset first.")
44
  st.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ df = st.session_state.df
47
+ problem_type = st.selectbox("Problem Type", ["Classification", "Regression", "Clustering"])
48
+ target = st.selectbox("Select Target Column", df.columns) if problem_type != "Clustering" else None
49
+
50
+ if problem_type == "Clustering":
51
+ st.info("Clustering does not require a target column. PyCaret will automatically group the data.")
52
+
53
+ if st.button("Setup PyCaret"):
54
+ with st.spinner("Setting up PyCaret..."):
55
+ if problem_type == "Classification":
56
+ setup(data=df, target=target, session_id=123, verbose=False)
57
+ st.session_state.problem_type = "Classification"
58
+ elif problem_type == "Regression":
59
+ setup(data=df, target=target, session_id=123, verbose=False)
60
+ st.session_state.problem_type = "Regression"
61
+ elif problem_type == "Clustering":
62
+ setup(data=df, session_id=123, verbose=False)
63
+ st.session_state.problem_type = "Clustering"
64
+ st.success("PyCaret setup complete! You can now train models.")
65
+
66
+ if 'problem_type' in st.session_state:
67
+ st.subheader("Train Models")
68
+ if st.button("Compare Models"):
69
+ with st.spinner("Comparing models..."):
70
+ best_model = compare_models()
71
+ st.session_state.best_model = best_model
72
+ st.success(f"Best Model: {best_model}")
73
+
74
+ if 'best_model' in st.session_state:
75
+ st.subheader("Model Evaluation")
76
+ if st.button("Evaluate Model"):
77
+ with st.spinner("Evaluating model..."):
78
+ if st.session_state.problem_type == "Classification":
79
+ evaluate_model(st.session_state.best_model)
80
+ elif st.session_state.problem_type == "Regression":
81
+ evaluate_model(st.session_state.best_model)
82
+ elif st.session_state.problem_type == "Clustering":
83
+ evaluate_model(st.session_state.best_model)
84
+ st.success("Model evaluation complete!")
85
+
86
+ if st.button("Save Model"):
87
+ save_model(st.session_state.best_model, "best_model")
88
+ st.success("Model saved as `best_model.pkl`!")
89
+ with open("best_model.pkl", "rb") as f:
90
+ st.download_button("Download Model", f, file_name="best_model.pkl")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  elif app_mode == "Validation & Exploration":
93
  st.title("🔍 Validation & Exploration")
94
+ if 'best_model' not in st.session_state:
95
+ st.warning("Please train a model first.")
 
 
 
96
  st.stop()
97
 
98
+ st.subheader("Model Performance")
99
+ if st.session_state.problem_type == "Classification":
100
+ st.write("Classification Report:")
101
+ plot_model(st.session_state.best_model, plot="confusion_matrix", display_format="streamlit")
102
+ plot_model(st.session_state.best_model, plot="auc", display_format="streamlit")
103
+ elif st.session_state.problem_type == "Regression":
104
+ st.write("Regression Metrics:")
105
+ plot_model(st.session_state.best_model, plot="residuals", display_format="streamlit")
106
+ plot_model(st.session_state.best_model, plot="error", display_format="streamlit")
107
+ elif st.session_state.problem_type == "Clustering":
108
+ st.write("Clustering Results:")
109
+ plot_model(st.session_state.best_model, plot="cluster", display_format="streamlit")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  # Custom CSS
112
  st.markdown("""