trohith89 commited on
Commit
1e587a9
·
verified ·
1 Parent(s): 1e9625c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -51
app.py CHANGED
@@ -15,6 +15,10 @@ from keras.losses import MeanSquaredError, BinaryCrossentropy
15
  from keras.regularizers import l2, l1
16
  from keras.callbacks import Callback
17
 
 
 
 
 
18
  # Set wide layout and TensorFlow Playground CSS
19
  st.set_page_config(layout="wide")
20
  st.markdown("""
@@ -298,67 +302,68 @@ with col_right:
298
  self.X, self.y = X, y
299
  self.losses = {"Epoch": [], "Train Loss": [], "Val Loss": []}
300
  self.placeholder = st.empty()
301
- self.model = None # Store model instance explicitly
302
 
303
  def on_train_begin(self, logs=None):
304
- self.model = self.model_ # Assign the model from the fit method
305
 
306
  def on_epoch_end(self, epoch, logs=None):
307
- self.losses["Epoch"].append(epoch + 1)
308
- self.losses["Train Loss"].append(logs["loss"])
309
- self.losses["Val Loss"].append(logs.get("val_loss", logs["loss"])) # Handle missing val_loss
310
- with self.placeholder.container():
311
- col1, col2 = st.columns(2)
312
- with col1:
313
- plt.figure(figsize=(3, 3))
314
- if problem_type == "Classification":
315
- # Use only the first two features for 2D plotting
316
- X_2d = self.X[:, :2] # Ensure 2D input
317
- try:
318
- y_pred_proba = self.model.predict(X_2d, verbose=0)
319
  y_pred = (y_pred_proba > 0.5).astype(int).ravel()
320
- plot_decision_regions(X_2d, self.y, clf=self.model, legend=2, colors='blue,red')
321
- plt.scatter(X_2d[:, 0], X_2d[:, 1], c=self.y, cmap='coolwarm', edgecolors='k', alpha=0.7)
322
- # Add decision boundary contour
323
- xx, yy = np.meshgrid(np.linspace(X_2d[:, 0].min(), X_2d[:, 0].max(), 100),
324
- np.linspace(X_2d[:, 1].min(), X_2d[:, 1].max(), 100))
325
- grid = np.c_[xx.ravel(), yy.ravel()]
326
- Z = self.model.predict(grid, verbose=0)
327
- Z = (Z > 0.5).astype(int).reshape(xx.shape)
328
- plt.contour(xx, yy, Z, levels=[0.5], colors='black', linewidths=2)
329
- except Exception as e:
330
- st.warning(f"Decision region plot failed: {e}")
331
- xx, yy = np.meshgrid(np.linspace(X_2d[:, 0].min(), X_2d[:, 0].max(), 100),
332
- np.linspace(X_2d[:, 1].min(), X_2d[:, 1].max(), 100))
333
- grid = np.c_[xx.ravel(), yy.ravel()]
334
- Z = self.model.predict(grid, verbose=0) if self.model else np.zeros_like(grid[:, 0])
335
- Z = (Z > 0.5).astype(int).reshape(xx.shape)
336
- plt.contour(xx, yy, Z, levels=[0.5], colors='black', linewidths=2)
337
- plt.contourf(xx, yy, Z, alpha=0.3, cmap="coolwarm")
338
- plt.scatter(X_2d[:, 0], X_2d[:, 1], c=self.y, cmap="coolwarm", edgecolors="k", alpha=0.7)
339
- else:
340
- y_pred = self.model.predict(self.X, verbose=0) if self.model else np.zeros_like(self.X[:, 0])
341
- plt.scatter(self.X[:, 0], self.y, c="blue", alpha=0.5)
342
- plt.plot(self.X[:, 0], y_pred, "r-", linewidths=2)
343
- plt.gca().set_facecolor("#333")
344
- plt.xticks([])
345
- plt.yticks([])
346
- st.pyplot(plt)
347
- with col2:
348
- fig, ax = plt.subplots(figsize=(3, 3))
349
- ax.plot(self.losses["Epoch"], self.losses["Train Loss"], "b-", label="Train")
350
- ax.plot(self.losses["Epoch"], self.losses["Val Loss"], "r--", label="Val")
351
- ax.legend()
352
- ax.set_facecolor("#333")
353
- st.pyplot(fig)
 
 
354
 
355
  if st.session_state.training:
356
  try:
357
  model = create_model(len(selected_features), st.session_state.hidden_layer_neurons)
358
  callback = OutputCallback(selected_data, cv)
359
- callback.model_ = model # Explicitly set the model for the callback
360
- model.fit(selected_data, cv, epochs=100, # Reduced epochs for Spaces
361
- batch_size=batch_size, validation_split=1-train_ratio,
362
  callbacks=[callback], verbose=0)
363
  except Exception as e:
364
  st.error(f"Training failed: {e}")
 
15
  from keras.regularizers import l2, l1
16
  from keras.callbacks import Callback
17
 
18
+ # Debug versions
19
+ st.write(f"TensorFlow version: {tf.__version__}")
20
+ st.write(f"Keras version: {tf.keras.__version__}")
21
+
22
  # Set wide layout and TensorFlow Playground CSS
23
  st.set_page_config(layout="wide")
24
  st.markdown("""
 
302
  self.X, self.y = X, y
303
  self.losses = {"Epoch": [], "Train Loss": [], "Val Loss": []}
304
  self.placeholder = st.empty()
305
+ self.model = None
306
 
307
  def on_train_begin(self, logs=None):
308
+ self.model = self.model # Use the model passed implicitly by Keras
309
 
310
  def on_epoch_end(self, epoch, logs=None):
311
+ try:
312
+ self.losses["Epoch"].append(epoch + 1)
313
+ self.losses["Train Loss"].append(logs["loss"])
314
+ self.losses["Val Loss"].append(logs.get("val_loss", logs["loss"]))
315
+ with self.placeholder.container():
316
+ col1, col2 = st.columns(2)
317
+ with col1:
318
+ plt.figure(figsize=(3, 3))
319
+ if problem_type == "Classification":
320
+ X_2d = self.X[:, :2] # Use only first two features for 2D
321
+ y_pred_proba = self.model.predict(X_2d, verbose=0) if self.model else np.zeros((len(X_2d), 1))
 
322
  y_pred = (y_pred_proba > 0.5).astype(int).ravel()
323
+ try:
324
+ plot_decision_regions(X_2d, self.y, clf=self.model, legend=2, colors='blue,red')
325
+ plt.scatter(X_2d[:, 0], X_2d[:, 1], c=self.y, cmap='coolwarm', edgecolors='k', alpha=0.7)
326
+ xx, yy = np.meshgrid(np.linspace(X_2d[:, 0].min(), X_2d[:, 0].max(), 100),
327
+ np.linspace(X_2d[:, 1].min(), X_2d[:, 1].max(), 100))
328
+ grid = np.c_[xx.ravel(), yy.ravel()]
329
+ Z = self.model.predict(grid, verbose=0) if self.model else np.zeros((len(grid), 1))
330
+ Z = (Z > 0.5).astype(int).reshape(xx.shape)
331
+ plt.contour(xx, yy, Z, levels=[0.5], colors='black', linewidths=2)
332
+ except Exception as e:
333
+ st.warning(f"Decision region plot failed: {e}")
334
+ xx, yy = np.meshgrid(np.linspace(X_2d[:, 0].min(), X_2d[:, 0].max(), 100),
335
+ np.linspace(X_2d[:, 1].min(), X_2d[:, 1].max(), 100))
336
+ grid = np.c_[xx.ravel(), yy.ravel()]
337
+ Z = self.model.predict(grid, verbose=0) if self.model else np.zeros((len(grid), 1))
338
+ Z = (Z > 0.5).astype(int).reshape(xx.shape)
339
+ plt.contour(xx, yy, Z, levels=[0.5], colors='black', linewidths=2)
340
+ plt.contourf(xx, yy, Z, alpha=0.3, cmap="coolwarm")
341
+ plt.scatter(X_2d[:, 0], X_2d[:, 1], c=self.y, cmap="coolwarm", edgecolors="k", alpha=0.7)
342
+ else:
343
+ y_pred = self.model.predict(self.X, verbose=0) if self.model else np.zeros_like(self.X[:, 0])
344
+ plt.scatter(self.X[:, 0], self.y, c="blue", alpha=0.5)
345
+ plt.plot(self.X[:, 0], y_pred, "r-", linewidths=2)
346
+ plt.gca().set_facecolor("#333")
347
+ plt.xticks([])
348
+ plt.yticks([])
349
+ st.pyplot(plt)
350
+ with col2:
351
+ fig, ax = plt.subplots(figsize=(3, 3))
352
+ ax.plot(self.losses["Epoch"], self.losses["Train Loss"], "b-", label="Train")
353
+ ax.plot(self.losses["Epoch"], self.losses["Val Loss"], "r--", label="Val")
354
+ ax.legend()
355
+ ax.set_facecolor("#333")
356
+ st.pyplot(fig)
357
+ except Exception as e:
358
+ st.error(f"Error in epoch end: {e}")
359
 
360
  if st.session_state.training:
361
  try:
362
  model = create_model(len(selected_features), st.session_state.hidden_layer_neurons)
363
  callback = OutputCallback(selected_data, cv)
364
+ callback.model = model # Explicitly set the model for the callback
365
+ model.fit(selected_data, cv, epochs=100, # Reduced for Spaces
366
+ batch_size=batch_size, validation_split=1-train_ratio,
367
  callbacks=[callback], verbose=0)
368
  except Exception as e:
369
  st.error(f"Training failed: {e}")