CosmickVisions commited on
Commit
b9cb478
·
verified ·
1 Parent(s): ff877e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -763
app.py CHANGED
@@ -1,314 +1,29 @@
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):
295
  start_time = time.time()
296
  history = None
297
 
298
- # Create a placeholder for the training progress chart
299
- training_placeholder = st.empty()
300
-
301
  if isinstance(model, keras.Model):
302
- streamlit_callback = StreamlitCallback(training_placeholder)
303
- history = model.fit(
304
- input_data if input_data is not None else X_train,
305
- target_data if target_data is not None else y_train,
306
- epochs=epochs,
307
- batch_size=batch_size,
308
- validation_data=(X_test, y_test if y_test is not None else X_test),
309
- verbose=0,
310
- callbacks=[streamlit_callback]
311
- )
 
 
 
 
 
 
 
 
 
 
312
  else:
313
  if do_grid_search and grid_params:
314
  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')
@@ -322,464 +37,106 @@ def train_model(model, X_train, y_train, X_test, y_test, epochs, batch_size, pro
322
  training_time = time.time() - start_time
323
  return history, model, training_time
324
 
325
- def evaluate_model(model, X_test, y_test, problem_type, le=None, encoder=None):
326
- y_pred = model.predict(X_test)
327
- metrics = {}
328
- if problem_type == "Regression":
329
- metrics['mse'] = mean_squared_error(y_test, y_pred)
330
- metrics['mae'] = mean_absolute_error(y_test, y_pred)
331
- metrics['rmse'] = np.sqrt(metrics['mse'])
332
- metrics['r2'] = r2_score(y_test, y_pred)
333
- return metrics, y_pred.flatten()
334
- elif problem_type in ["Binary Classification", "Multi-Class", "Image Classification"]:
335
- if problem_type == "Image Classification":
336
- y_pred_classes = np.argmax(y_pred, axis=1)
337
- y_test_classes = y_test
338
- else:
339
- y_pred_classes = (y_pred > 0.5).astype(int).flatten() if problem_type == "Binary Classification" else np.argmax(y_pred, axis=1)
340
- y_test_classes = y_test if problem_type == "Binary Classification" else np.argmax(y_test, axis=1)
341
- metrics['accuracy'] = accuracy_score(y_test_classes, y_pred_classes)
342
- metrics['precision'] = precision_score(y_test_classes, y_pred_classes, average='weighted', zero_division=0)
343
- metrics['recall'] = recall_score(y_test_classes, y_pred_classes, average='weighted', zero_division=0)
344
- metrics['f1'] = f1_score(y_test_classes, y_pred_classes, average='weighted', zero_division=0)
345
- return metrics, y_pred_classes
346
- elif problem_type == "Clustering":
347
- labels = model.labels_ if hasattr(model, 'labels_') else model.predict(X_test)
348
- metrics["n_clusters"] = len(np.unique(labels))
349
- if len(np.unique(labels)) > 1:
350
- metrics["silhouette"] = silhouette_score(X_test, labels)
351
- return metrics, labels
352
- elif problem_type == "Compression":
353
- metrics['mse'] = mean_squared_error(X_test, y_pred)
354
- metrics['mae'] = mean_absolute_error(X_test, y_pred)
355
- metrics['rmse'] = np.sqrt(metrics['mse'])
356
- compressed_data = encoder.predict(X_test) if encoder else None
357
- return metrics, y_pred, compressed_data
358
-
359
- def save_model(model, preprocessor, features, target, problem_type, filename="model.pkl"):
360
- model_data = {
361
- 'model': model,
362
- 'preprocessor': preprocessor,
363
- 'features': features,
364
- 'target': target,
365
- 'problem_type': problem_type,
366
- 'timestamp': time.strftime("%Y%m%d_%H%M%S")
367
- }
368
- if isinstance(model, keras.Model):
369
- model.save("temp_model.h5")
370
- model_data['model_path'] = "temp_model.h5"
371
- joblib.dump(model_data, filename)
372
- return filename
373
-
374
- def load_model(model_file):
375
- model_data = joblib.load(model_file)
376
- if 'model_path' in model_data:
377
- model_data['model'] = keras.models.load_model(model_data['model_path'])
378
- return model_data
379
-
380
- # Sidebar Navigation
381
- with st.sidebar:
382
- st.title("🔮 Neural-Vision Enhanced")
383
- st.markdown("Your AI-powered model toolbox.")
384
- st.markdown("---")
385
- app_mode = st.selectbox("Navigation", ["Data Upload", "Model Training", "Validation & Exploration"])
386
- data_type = st.selectbox("Data Type", ["Tabular", "Image"])
387
- st.markdown("---")
388
- st.markdown("**Dependencies**: `tensorflow`, `shap`, `umap-learn`, `joblib`, `scikit-learn`, `plotly`, `xgboost`, `pillow`")
389
- st.markdown("Created by Calvin Allen-Crawford | v1.3 | © 2025")
390
-
391
- # Main App Sections
392
- if app_mode == "Data Upload":
393
- st.title("📤 Data Upload")
394
- col1, col2, col3 = st.columns([1, 2, 1])
395
- with col2:
396
  if data_type == "Tabular":
397
- uploaded_file = st.file_uploader("Upload CSV Dataset", type=["csv"])
398
- if uploaded_file:
399
- df = pd.read_csv(uploaded_file)
400
- st.session_state.df = df
401
- st.write("---")
402
- st.subheader("Dataset Preview")
403
- st.dataframe(df.head(10))
404
- st.write("---")
405
- st.subheader("Statistics")
406
- col1, col2, col3 = st.columns(3)
407
- with col1: st.metric("Rows", df.shape[0])
408
- with col2: st.metric("Columns", df.shape[1])
409
- with col3: st.metric("Missing Values", df.isna().sum().sum())
 
410
  else: # Image
411
- uploaded_file = st.file_uploader("Upload Zip File with Images (Max 5GB)", type=["zip"])
412
- if uploaded_file:
413
- # Save uploaded file temporarily to check size
414
- with open("temp_upload.zip", "wb") as f:
415
- f.write(uploaded_file.getbuffer())
416
- try:
417
- problem_type = st.selectbox("Problem Type for Image Data", ["Image Classification", "Compression", "Clustering"])
418
- images, labels, class_names = load_image_dataset("temp_upload.zip", problem_type=problem_type)
419
- st.session_state.images = images
420
- st.session_state.labels = labels
421
- st.session_state.class_names = class_names if problem_type == "Image Classification" else None
422
- st.write(f"Loaded {len(images)} images.")
423
- if problem_type == "Image Classification":
424
- st.write(f"Classes: {class_names}")
425
- st.image(images[:5], caption=["Sample " + str(i+1) for i in range(min(5, len(images)))], width=100)
426
- except ValueError as e:
427
- st.error(str(e))
428
- finally:
429
- os.remove("temp_upload.zip")
430
-
431
- elif app_mode == "Model Training":
432
- st.title("🧠 Model Training")
433
- if data_type == "Tabular" and 'df' not in st.session_state:
434
- st.warning("Please upload a tabular dataset first.")
435
- st.stop()
436
- elif data_type == "Image" and 'images' not in st.session_state:
437
- st.warning("Please upload an image dataset first.")
438
- st.stop()
439
-
440
- if data_type == "Tabular":
441
- df = st.session_state.df
442
- problem_type = st.selectbox("Problem Type", ["Regression", "Binary Classification", "Multi-Class", "Clustering", "Compression"])
443
- features = st.multiselect("Select Features", df.columns)
444
- target = st.selectbox("Select Target", df.columns) if problem_type not in ["Clustering", "Compression"] else None
445
- else:
446
- problem_type = st.selectbox("Problem Type", ["Image Classification", "Compression", "Clustering"])
447
- features = ["images"]
448
- target = "labels" if problem_type == "Image Classification" else None
449
-
450
- if problem_type not in ["Clustering", "Compression"] and data_type == "Tabular" and target:
451
- unique_target_values = df[target].nunique()
452
- if problem_type == "Binary Classification" and unique_target_values != 2:
453
- st.error("Binary Classification requires exactly 2 unique target values.")
454
- st.stop()
455
- elif problem_type == "Multi-Class" and unique_target_values < 2:
456
- st.error("Multi-Class Classification requires at least 2 unique target values.")
457
- st.stop()
458
- elif problem_type == "Regression" and not pd.api.types.is_numeric_dtype(df[target]):
459
- st.error("Regression requires a numerical target variable.")
460
- st.stop()
461
-
462
- model_types = {
463
- "Regression": ["Neural Network", "Random Forest", "XGBoost", "Linear Regression", "SVM"],
464
- "Binary Classification": ["Neural Network", "Random Forest", "XGBoost", "Logistic Regression", "SVM"],
465
- "Multi-Class": ["Neural Network", "Random Forest", "XGBoost", "SVM"],
466
- "Clustering": ["K-Means", "DBSCAN", "Gaussian Mixture"],
467
- "Compression": ["Autoencoder"],
468
- "Image Classification": ["Neural Network", "SVM"]
469
- }[problem_type]
470
- model_type = st.selectbox("Model Type", model_types)
471
-
472
- if model_type == "Neural Network":
473
- st.subheader("Neural Network Configuration")
474
- optimizer_name = st.selectbox("Optimizer", ["Adam", "SGD", "RMSprop"])
475
- layers_config = st.session_state.get('layers_config', [])
476
- layer_type = st.selectbox("Layer Type", ["Dense", "Dropout"] if data_type == "Tabular" else ["Conv2D", "MaxPooling2D", "Flatten", "Dense", "Dropout"])
477
- if layer_type == "Dense":
478
- units = st.number_input("Units", min_value=1, value=64)
479
- activation = st.selectbox("Activation", ["relu", "sigmoid", "tanh"])
480
- if st.button("Add Layer"):
481
- layers_config.append({"type": "dense", "units": units, "activation": activation})
482
- elif layer_type == "Dropout":
483
- rate = st.number_input("Dropout Rate", 0.0, 1.0, 0.2)
484
- if st.button("Add Layer"):
485
- layers_config.append({"type": "dropout", "rate": rate})
486
- elif layer_type == "Conv2D":
487
- filters = st.number_input("Filters", min_value=1, value=32)
488
- kernel_size = st.multiselect("Kernel Size", options=[1, 3, 5], default=[3])
489
- activation = st.selectbox("Activation", ["relu", "sigmoid", "tanh"])
490
- if st.button("Add Layer"):
491
- layers_config.append({"type": "conv2d", "filters": filters, "kernel_size": kernel_size, "activation": activation})
492
- elif layer_type == "MaxPooling2D":
493
- pool_size = st.multiselect("Pool Size", options=[2, 3], default=[2])
494
- if st.button("Add Layer"):
495
- layers_config.append({"type": "maxpooling2d", "pool_size": pool_size})
496
- elif layer_type == "Flatten":
497
- if st.button("Add Layer"):
498
- layers_config.append({"type": "flatten"})
499
- if layers_config:
500
- st.write("Current Layers:", layers_config)
501
- if st.button("Clear Layers"):
502
- layers_config.clear()
503
- st.session_state.layers_config = layers_config
504
- st.rerun()
505
- st.session_state.layers_config = layers_config
506
- elif model_type == "Autoencoder":
507
- st.subheader("Autoencoder Configuration")
508
- encoding_dim = st.number_input("Encoding Dimension", min_value=1, value=32)
509
- optimizer_name = st.selectbox("Optimizer", ["Adam", "SGD", "RMSprop"])
510
- autoencoder_type = st.selectbox("Autoencoder Type", ["Standard", "Variational", "Denoising"])
511
- if autoencoder_type == "Denoising":
512
- noise_level = st.slider("Noise Level", 0.0, 1.0, 0.1)
513
- layers_config = st.session_state.get('layers_config', [])
514
- layer_type = st.selectbox("Layer Type (Encoder)", ["Dense", "Dropout"])
515
- if layer_type == "Dense":
516
- units = st.number_input("Units", min_value=1, value=64)
517
- activation = st.selectbox("Activation", ["relu", "sigmoid", "tanh"])
518
- if st.button("Add Layer"):
519
- layers_config.append({"type": "dense", "units": units, "activation": activation})
520
- elif layer_type == "Dropout":
521
- rate = st.number_input("Dropout Rate", 0.0, 1.0, 0.2)
522
- if st.button("Add Layer"):
523
- layers_config.append({"type": "dropout", "rate": rate})
524
- if layers_config:
525
- st.write("Current Encoder Layers:", layers_config)
526
- if st.button("Clear Layers"):
527
- layers_config.clear()
528
- st.session_state.layers_config = layers_config
529
- st.rerun()
530
- st.session_state.layers_config = layers_config
531
- else:
532
- st.subheader("Model Hyperparameters")
533
- config = get_model_config(model_type, problem_type)
534
- params = {}
535
- for param_name, param_values in config["grid_params"].items():
536
- if isinstance(param_values[0], (int, float)) and len(param_values) > 2:
537
- slider_value = st.slider(param_name, min_value=float(min(param_values)), max_value=float(max(param_values)), value=float(param_values[1]))
538
- if param_name in {'n_estimators', 'n_clusters', 'min_samples', 'n_components', 'max_depth'}:
539
- params[param_name] = int(slider_value)
540
- else:
541
- params[param_name] = slider_value
542
- else:
543
- params[param_name] = st.selectbox(param_name, param_values)
544
- do_grid_search = st.checkbox("Use Grid Search for Tuning", value=False)
545
-
546
- col1, col2, col3 = st.columns(3)
547
- with col1: epochs = st.number_input("Epochs", min_value=1, value=10) if model_type in ["Neural Network", "Autoencoder"] else 10
548
- with col2: batch_size = st.number_input("Batch Size", min_value=1, value=32) if model_type in ["Neural Network", "Autoencoder"] else 32
549
- 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
550
-
551
- uploaded_model = st.file_uploader("Upload Pre-trained Model (.h5)", type=["h5"]) if model_type in ["Neural Network", "Autoencoder"] else None
552
- base_model = keras.models.load_model(uploaded_model) if uploaded_model else None
553
-
554
- if st.button("Train Model"):
555
- with st.spinner("Preparing data..."):
556
- if data_type == "Tabular":
557
- X = df[features]
558
- y = df[target] if problem_type not in ["Clustering", "Compression"] else None
559
- 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)
560
- numerical_features = X.select_dtypes(include=np.number).columns.tolist()
561
- categorical_features = X.select_dtypes(exclude=np.number).columns.tolist()
562
- X_train_processed, X_test_processed, feature_names, preprocessor = preprocess_data(X_train, X_test, numerical_features, categorical_features)
563
- le = None
564
- if problem_type in ["Binary Classification", "Multi-Class"] and y is not None:
565
- le = LabelEncoder()
566
- y_train = le.fit_transform(y_train)
567
- y_test = le.transform(y_test)
568
- if problem_type == "Multi-Class":
569
- y_train = tf.keras.utils.to_categorical(y_train)
570
- y_test = tf.keras.utils.to_categorical(y_test)
571
- else: # Image
572
- 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)
573
- preprocessor = None
574
- feature_names = ["image_features"]
575
- le = None
576
-
577
- with st.spinner("Training model..."):
578
- training_placeholder = st.empty()
579
- if model_type == "Neural Network":
580
- if not layers_config and not base_model:
581
- st.error("Please add layers or upload a pre-trained model.")
582
- st.stop()
583
- input_shape = (X_train_processed.shape[1],) if data_type == "Tabular" else (224, 224, 3)
584
- 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)
585
- model = base_model if base_model else build_neural_network(input_shape, output_units, problem_type, layers_config, optimizer_name, learning_rate)
586
- history, model, training_time = train_model(model, X_train_processed if data_type == "Tabular" else X_train, y_train,
587
- X_test_processed if data_type == "Tabular" else X_test, y_test,
588
- epochs, batch_size, problem_type, training_placeholder=training_placeholder)
589
- elif model_type == "Autoencoder":
590
- if not layers_config and not base_model:
591
- st.error("Please add layers to the encoder or upload a pre-trained model.")
592
- st.stop()
593
- input_shape = (X_train_processed.shape[1],) if data_type == "Tabular" else (224, 224, 3)
594
- 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)
595
- if autoencoder_type == "Denoising":
596
- 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)
597
- input_data = X_train_noisy
598
- target_data = X_train_processed if data_type == "Tabular" else X_train
599
- else:
600
- input_data = X_train_processed if data_type == "Tabular" else X_train
601
- target_data = X_train_processed if data_type == "Tabular" else X_train
602
- history, model, training_time = train_model(model, X_train_processed if data_type == "Tabular" else X_train, None,
603
- X_test_processed if data_type == "Tabular" else X_test, None,
604
- epochs, batch_size, problem_type, input_data=input_data, target_data=target_data,
605
- training_placeholder=training_placeholder)
606
- st.session_state.encoder = encoder
607
- st.session_state.decoder = decoder
608
- else:
609
- config = get_model_config(model_type, problem_type)
610
- model = config['model_class'](**config['params'])
611
- X_train_flat = X_train_processed if data_type == "Tabular" else X_train.reshape(X_train.shape[0], -1)
612
- X_test_flat = X_test_processed if data_type == "Tabular" else X_test.reshape(X_test.shape[0], -1)
613
- history, model, training_time = train_model(model, X_train_flat, y_train, X_test_flat, y_test, epochs, batch_size, problem_type,
614
- do_grid_search=do_grid_search, params=params, grid_params=config['grid_params'],
615
- training_placeholder=training_placeholder)
616
-
617
- st.session_state.model = model
618
- st.session_state.preprocessor = preprocessor
619
- st.session_state.features = features
620
- st.session_state.target = target
621
- st.session_state.problem_type = problem_type
622
- st.session_state.le = le
623
-
624
- filename = save_model(model, preprocessor, features, target, problem_type)
625
- with open(filename, 'rb') as f:
626
- st.download_button("Download Model", f, file_name=filename)
627
- st.success(f"Model trained in {training_time:.2f}s and saved!")
628
-
629
- elif app_mode == "Validation & Exploration":
630
- st.title("🔍 Validation & Exploration")
631
- if data_type == "Tabular" and ('model' not in st.session_state or 'df' not in st.session_state):
632
- st.warning("Please upload a tabular dataset and train a model first.")
633
- st.stop()
634
- elif data_type == "Image" and ('model' not in st.session_state or 'images' not in st.session_state):
635
- st.warning("Please upload an image dataset and train a model first.")
636
- st.stop()
637
-
638
- if data_type == "Tabular":
639
- df = st.session_state.df
640
- X = df[st.session_state.features]
641
- y = df[st.session_state.target] if st.session_state.problem_type not in ["Clustering", "Compression"] else None
642
- 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)
643
- numerical_features = X.select_dtypes(include=np.number).columns.tolist()
644
- categorical_features = X.select_dtypes(exclude=np.number).columns.tolist()
645
- X_train_processed, X_test_processed, feature_names, _ = preprocess_data(X_train, X_test, numerical_features, categorical_features)
646
- if st.session_state.problem_type in ["Binary Classification", "Multi-Class"] and y is not None:
647
- y_train = st.session_state.le.transform(y_train) if st.session_state.le else y_train
648
- y_test = st.session_state.le.transform(y_test) if st.session_state.le else y_test
649
- if st.session_state.problem_type == "Multi-Class":
650
- y_train = tf.keras.utils.to_categorical(y_train)
651
- y_test = tf.keras.utils.to_categorical(y_test)
652
- else:
653
- 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)
654
- X_train_processed, X_test_processed = X_train, X_test
655
- feature_names = ["image_features"]
656
- if st.session_state.problem_type == "Image Classification":
657
  le = None
658
 
659
- model = st.session_state.model
660
- problem_type = st.session_state.problem_type
661
- encoder = st.session_state.get('encoder', None)
662
-
663
- # Validation
664
- st.subheader("Model Validation")
665
- if problem_type == "Compression":
666
- metrics, y_pred, compressed_data = evaluate_model(model, X_test_processed, None, problem_type, None, encoder)
667
- else:
668
- metrics, y_pred = evaluate_model(model, X_test_processed, y_test, problem_type, st.session_state.le if data_type == "Tabular" else None)
669
-
670
- col1, col2 = st.columns(2)
671
- with col1:
672
- for metric, value in metrics.items():
673
- st.metric(metric, f"{value:.4f}" if isinstance(value, float) else value)
674
- with col2:
675
- if problem_type == "Regression":
676
- fig = px.scatter(x=y_test, y=y_pred, labels={"x": "Actual", "y": "Predicted"}, title="Predicted vs Actual")
677
- st.plotly_chart(fig)
678
- elif problem_type in ["Binary Classification", "Image Classification"]:
679
- if problem_type == "Binary Classification":
680
- y_pred_proba = model.predict_proba(X_test_processed)[:, 1] if hasattr(model, 'predict_proba') else y_pred
681
- fpr, tpr, _ = roc_curve(y_test, y_pred_proba)
682
- roc_auc = auc(fpr, tpr)
683
- fig = px.area(x=fpr, y=tpr, title=f"ROC Curve (AUC = {roc_auc:.2f})", labels={"x": "False Positive Rate", "y": "True Positive Rate"})
684
- st.plotly_chart(fig)
 
 
 
 
685
  else:
686
- cm = np.zeros((len(st.session_state.class_names), len(st.session_state.class_names)))
687
- for i, j in zip(y_test, y_pred):
688
- cm[i, j] += 1
689
- fig = px.imshow(cm, title="Confusion Matrix", labels={"x": "Predicted", "y": "Actual"})
690
- st.plotly_chart(fig)
691
- report = classification_report(y_test, y_pred, target_names=st.session_state.class_names, zero_division=0)
692
- st.text("Classification Report:\n" + report)
693
- elif problem_type == "Multi-Class":
694
- y_pred_classes = np.argmax(model.predict(X_test_processed), axis=1)
695
- y_test_classes = np.argmax(y_test, axis=1)
696
- cm = np.zeros((y_train.shape[1], y_train.shape[1]))
697
- for i, j in zip(y_test_classes, y_pred_classes):
698
- cm[i, j] += 1
699
- fig = px.imshow(cm, title="Confusion Matrix", labels={"x": "Predicted", "y": "Actual"})
700
- st.plotly_chart(fig)
701
- 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)
702
- st.text("Classification Report:\n" + report)
703
- elif problem_type == "Clustering":
704
- labels = y_pred
705
- 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],
706
- y=X_test_processed[:, 1] if X_test_processed.shape[-1] == 1 else X_test_processed.reshape(X_test_processed.shape[0], -1)[:, 1],
707
- color=labels, title="Cluster Visualization")
708
- st.plotly_chart(fig)
709
- elif problem_type == "Compression":
710
- st.image([X_test_processed[0], y_pred[0]], caption=["Original", "Reconstructed"], width=200) if data_type == "Image" else None
711
- 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)")
712
- st.plotly_chart(fig)
713
-
714
- # Dimensionality Reduction
715
- st.subheader("Dimensionality Reduction")
716
- methods = ["PCA", "SVD", "t-SNE", "UMAP"]
717
- if problem_type == "Compression" and 'encoder' in st.session_state:
718
- methods.append("Autoencoder")
719
- method = st.selectbox("Method", methods)
720
- n_components = st.slider("Components", 2, min(10 if data_type == "Tabular" else X_train_processed.shape[1], 10), 2)
721
-
722
- if method == "Autoencoder" and 'encoder' in st.session_state:
723
- X_reduced = st.session_state.encoder.predict(X_train_processed)
724
- if X_reduced.shape[1] < n_components:
725
- st.warning(f"Autoencoder encoding dimension is {X_reduced.shape[1]}, using that instead of {n_components}.")
726
- n_components = X_reduced.shape[1]
727
- else:
728
- X_flat = X_train_processed if data_type == "Tabular" else X_train_processed.reshape(X_train_processed.shape[0], -1)
729
- if method == "PCA":
730
- reducer = PCA(n_components=n_components)
731
- X_reduced = reducer.fit_transform(X_flat)
732
- fig = px.bar(x=range(n_components), y=reducer.explained_variance_ratio_, title="Explained Variance Ratio")
733
- st.plotly_chart(fig)
734
- elif method == "SVD":
735
- reducer = TruncatedSVD(n_components=n_components)
736
- X_reduced = reducer.fit_transform(X_flat)
737
- fig = px.bar(x=range(n_components), y=reducer.explained_variance_ratio_, title="Explained Variance Ratio")
738
- st.plotly_chart(fig)
739
- elif method == "t-SNE":
740
- with st.spinner("Running t-SNE..."):
741
- X_reduced = TSNE(n_components=n_components, random_state=42).fit_transform(X_flat)
742
- elif method == "UMAP":
743
- with st.spinner("Running UMAP..."):
744
- X_reduced = umap.UMAP(n_components=n_components, random_state=42).fit_transform(X_flat)
745
-
746
- if n_components >= 2:
747
- if n_components == 2:
748
- fig = px.scatter(x=X_reduced[:, 0], y=X_reduced[:, 1], color=y_train if problem_type not in ["Clustering", "Compression"] else y_pred,
749
- title=f"{method} Visualization")
750
- elif n_components == 3:
751
- 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,
752
- title=f"{method} Visualization")
753
- st.plotly_chart(fig)
754
-
755
- # Interpretability
756
- if problem_type not in ["Compression", "Clustering"]:
757
- st.subheader("Interpretability")
758
- try:
759
- X_flat = X_test_processed if data_type == "Tabular" else X_test_processed.reshape(X_test_processed.shape[0], -1)
760
- if isinstance(model, keras.Model):
761
- explainer = shap.DeepExplainer(model, X_train_processed[:50] if data_type == "Tabular" else X_train_processed[:50])
762
- shap_values = explainer.shap_values(X_flat[:50])
763
- else:
764
- explainer = shap.Explainer(model, X_flat)
765
- shap_values = explainer.shap_values(X_flat[:50])
766
- if problem_type == "Regression":
767
- shap_fig, ax = plt.subplots()
768
- shap.summary_plot(shap_values, X_flat[:50], feature_names=feature_names, show=False)
769
- st.pyplot(shap_fig)
770
- elif problem_type in ["Binary Classification", "Multi-Class", "Image Classification"]:
771
- 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])]
772
- for i in range(min(len(class_names), len(shap_values))):
773
- shap_fig, ax = plt.subplots()
774
- 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)
775
- st.pyplot(shap_fig)
776
- except Exception as e:
777
- st.error(f"Error generating SHAP plot: {e}")
778
-
779
- # Custom CSS
780
- st.markdown("""
781
- <style>
782
- .stButton>button {background-color: #4CAF50; color: white;}
783
- h1, h2 {color: #1e3a8a;}
784
- </style>
785
- """, unsafe_allow_html=True)
 
1
+ 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):
2
+ """Train the model and optionally display live training progress for Keras models."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  start_time = time.time()
4
  history = None
5
 
 
 
 
6
  if isinstance(model, keras.Model):
7
+ if training_placeholder is not None:
8
+ streamlit_callback = StreamlitCallback(training_placeholder)
9
+ history = model.fit(
10
+ input_data if input_data is not None else X_train,
11
+ target_data if target_data is not None else y_train,
12
+ epochs=epochs,
13
+ batch_size=batch_size,
14
+ validation_data=(X_test, y_test if y_test is not None else X_test),
15
+ verbose=0,
16
+ callbacks=[streamlit_callback]
17
+ )
18
+ else:
19
+ history = model.fit(
20
+ input_data if input_data is not None else X_train,
21
+ target_data if target_data is not None else y_train,
22
+ epochs=epochs,
23
+ batch_size=batch_size,
24
+ validation_data=(X_test, y_test if y_test is not None else X_test),
25
+ verbose=1
26
+ )
27
  else:
28
  if do_grid_search and grid_params:
29
  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')
 
37
  training_time = time.time() - start_time
38
  return history, model, training_time
39
 
40
+ # In the "Model Training" section, update the training block:
41
+ if st.button("Train Model"):
42
+ with st.spinner("Preparing data..."):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  if data_type == "Tabular":
44
+ X = df[features]
45
+ y = df[target] if problem_type not in ["Clustering", "Compression"] else None
46
+ 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)
47
+ numerical_features = X.select_dtypes(include=np.number).columns.tolist()
48
+ categorical_features = X.select_dtypes(exclude=np.number).columns.tolist()
49
+ X_train_processed, X_test_processed, feature_names, preprocessor = preprocess_data(X_train, X_test, numerical_features, categorical_features)
50
+ le = None
51
+ if problem_type in ["Binary Classification", "Multi-Class"] and y is not None:
52
+ le = LabelEncoder()
53
+ y_train = le.fit_transform(y_train)
54
+ y_test = le.transform(y_test)
55
+ if problem_type == "Multi-Class":
56
+ y_train = tf.keras.utils.to_categorical(y_train)
57
+ y_test = tf.keras.utils.to_categorical(y_test)
58
  else: # Image
59
+ 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)
60
+ preprocessor = None
61
+ feature_names = ["image_features"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  le = None
63
 
64
+ with st.spinner("Training model..."):
65
+ training_placeholder = st.empty() # Define the placeholder here
66
+ if model_type == "Neural Network":
67
+ if not layers_config and not base_model:
68
+ st.error("Please add layers or upload a pre-trained model.")
69
+ st.stop()
70
+ input_shape = (X_train_processed.shape[1],) if data_type == "Tabular" else (224, 224, 3)
71
+ 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)
72
+ model = base_model if base_model else build_neural_network(input_shape, output_units, problem_type, layers_config, optimizer_name, learning_rate)
73
+ history, model, training_time = train_model(
74
+ model,
75
+ X_train_processed if data_type == "Tabular" else X_train,
76
+ y_train,
77
+ X_test_processed if data_type == "Tabular" else X_test,
78
+ y_test,
79
+ epochs,
80
+ batch_size,
81
+ problem_type,
82
+ training_placeholder=training_placeholder
83
+ )
84
+ elif model_type == "Autoencoder":
85
+ if not layers_config and not base_model:
86
+ st.error("Please add layers to the encoder or upload a pre-trained model.")
87
+ st.stop()
88
+ input_shape = (X_train_processed.shape[1],) if data_type == "Tabular" else (224, 224, 3)
89
+ 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)
90
+ if autoencoder_type == "Denoising":
91
+ 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)
92
+ input_data = X_train_noisy
93
+ target_data = X_train_processed if data_type == "Tabular" else X_train
94
  else:
95
+ input_data = X_train_processed if data_type == "Tabular" else X_train
96
+ target_data = X_train_processed if data_type == "Tabular" else X_train
97
+ history, model, training_time = train_model(
98
+ model,
99
+ X_train_processed if data_type == "Tabular" else X_train,
100
+ None,
101
+ X_test_processed if data_type == "Tabular" else X_test,
102
+ None,
103
+ epochs,
104
+ batch_size,
105
+ problem_type,
106
+ input_data=input_data,
107
+ target_data=target_data,
108
+ training_placeholder=training_placeholder
109
+ )
110
+ st.session_state.encoder = encoder
111
+ st.session_state.decoder = decoder
112
+ else:
113
+ config = get_model_config(model_type, problem_type)
114
+ model = config['model_class'](**config['params'])
115
+ X_train_flat = X_train_processed if data_type == "Tabular" else X_train.reshape(X_train.shape[0], -1)
116
+ X_test_flat = X_test_processed if data_type == "Tabular" else X_test.reshape(X_test.shape[0], -1)
117
+ history, model, training_time = train_model(
118
+ model,
119
+ X_train_flat,
120
+ y_train,
121
+ X_test_flat,
122
+ y_test,
123
+ epochs,
124
+ batch_size,
125
+ problem_type,
126
+ do_grid_search=do_grid_search,
127
+ params=params,
128
+ grid_params=config['grid_params'],
129
+ training_placeholder=training_placeholder
130
+ )
131
+
132
+ st.session_state.model = model
133
+ st.session_state.preprocessor = preprocessor
134
+ st.session_state.features = features
135
+ st.session_state.target = target
136
+ st.session_state.problem_type = problem_type
137
+ st.session_state.le = le
138
+
139
+ filename = save_model(model, preprocessor, features, target, problem_type)
140
+ with open(filename, 'rb') as f:
141
+ st.download_button("Download Model", f, file_name=filename)
142
+ st.success(f"Model trained in {training_time:.2f}s and saved!")