DasariHarshitha commited on
Commit
bfbd5a5
ยท
verified ยท
1 Parent(s): 48060b4

Update pages/Tensorflow.py

Browse files
Files changed (1) hide show
  1. pages/Tensorflow.py +88 -81
pages/Tensorflow.py CHANGED
@@ -12,114 +12,121 @@ from mlxtend.plotting import plot_decision_regions
12
  import numpy as np
13
  import tensorflow as tf
14
 
15
- # Load and encode background image
16
- def get_base64(file_path):
17
- with open(file_path, "rb") as f:
18
- data = f.read()
19
- return base64.b64encode(data).decode()
20
-
21
- #img_base64 = get_base64("ann.jpeg")
22
-
23
- # Inject CSS with base64 background
24
- # st.markdown(
25
- # f"""
26
- # <style>
27
- # .stApp {{
28
- # background-image: url("data:image/jpg;base64,{img_base64}");
29
- # background-size: cover;
30
- # background-position: center;
31
- # background-repeat: no-repeat;
32
- # background-attachment: fixed;
33
- # }}
34
- # </style>
35
- # """,
36
- # unsafe_allow_html=True
37
- # )
38
-
39
- # Page title
40
- st.markdown(
41
- "<h1 style='text-align: center; color: #FF6347;'>๐Ÿค– Neural Network Playground</h1>",
42
- unsafe_allow_html=True
43
- )
44
-
45
- # Sidebar configuration
46
- st.sidebar.title("โš™๏ธ Model Configuration")
47
-
48
- num_points = st.sidebar.slider("Number of Data Points", 100, 10000, 1000, step=100)
49
- noise = st.sidebar.slider("Noise", 0.01, 0.9, 0.1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  batch_size = st.sidebar.slider("Batch Size", 1, 512, 32)
51
- epochs = st.sidebar.slider("Epochs", 1, 100, 10)
52
  learning_rate = st.sidebar.slider("Learning Rate", 0.0001, 1.0, 0.01, step=0.0001, format="%.4f")
53
  hidden_layers = st.sidebar.slider("Hidden Layers", 1, 5, 2)
54
- neurons_per_layer = st.sidebar.slider("Neurons per Layer", 1, 512, 32)
55
- activation_name = st.sidebar.selectbox("Activation Function", ["relu", "tanh", "sigmoid", "linear"])
56
 
57
  # Dataset selection
58
- st.subheader("๐Ÿ“Š Dataset Selection")
59
- dataset_option = st.selectbox("Choose the dataset", ("circle", "moons", "classification"))
60
 
61
- # Dataset generation
62
  if dataset_option == "circle":
63
  x, y = make_circles(n_samples=num_points, noise=noise, factor=0.5, random_state=42)
64
  elif dataset_option == "moons":
65
  x, y = make_moons(n_samples=num_points, noise=noise, random_state=42)
66
  else:
67
- x, y = make_classification(n_samples=num_points, n_features=2, n_informative=2,
68
- n_redundant=0, n_clusters_per_class=1, random_state=42)
69
 
70
- # Display data
71
- if st.button("๐Ÿš€ Submit"):
72
- st.subheader("๐Ÿ“ Input Data")
73
  fig, ax = plt.subplots()
74
- sns.scatterplot(x=x[:, 0], y=x[:, 1], hue=y, palette='Set2', ax=ax)
75
  st.pyplot(fig)
76
 
77
- # Train the model
78
- if st.button("๐Ÿง  Train the model"):
79
- with st.spinner("โณ Training the model..."):
80
- x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1, stratify=y)
81
- scaler = StandardScaler()
82
- x_train = scaler.fit_transform(x_train)
83
- x_test = scaler.transform(x_test)
84
 
85
- model = Sequential()
86
- model.add(Dense(neurons_per_layer, input_shape=(2,), activation=activation_name))
87
- for _ in range(hidden_layers - 1):
88
- model.add(Dense(neurons_per_layer, activation=activation_name))
89
- model.add(Dense(1, activation='sigmoid'))
90
 
91
- sgd = SGD(learning_rate=learning_rate)
92
- model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy'])
93
- history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.2, verbose=0)
94
 
95
- st.success("โœ… Training Complete!")
96
 
97
- # Training plot
98
- st.subheader("๐Ÿ“ˆ Training Progress")
99
  fig, ax = plt.subplots()
100
- ax.plot(history.history['loss'], label='Training Loss')
101
- ax.plot(history.history['val_loss'], label='Validation Loss')
102
- ax.set_title("Training vs Validation Loss")
103
- ax.set_xlabel("Epoch")
104
  ax.legend()
105
  st.pyplot(fig)
106
 
107
- # Final metrics
108
- final_loss = history.history['loss'][-1]
109
- final_val_loss = history.history['val_loss'][-1]
110
- st.write(f"๐Ÿงฎ Final Training Loss: **{final_loss:.4f}**")
111
- st.write(f"โœ… Final Validation Loss: **{final_val_loss:.4f}**")
112
 
113
- # Decision boundary
114
- class KerasClassifierWrapper:
115
  def __init__(self, model):
116
  self.model = model
117
 
118
  def predict(self, X):
119
  return (self.model.predict(X) > 0.5).astype("int32")
120
 
121
- with st.spinner("๐Ÿ”ฎ Generating decision boundary..."):
122
- st.subheader("๐Ÿ“Œ Decision Boundary (Training Data)")
123
- fig, ax = plt.subplots()
124
- plot_decision_regions(X=x_train, y=y_train, clf=KerasClassifierWrapper(model), ax=ax)
125
- st.pyplot(fig)
 
12
  import numpy as np
13
  import tensorflow as tf
14
 
15
+ # Set page configuration
16
+ st.set_page_config(page_title="๐Ÿง  Neural Network Explorer", layout="wide")
17
+
18
+ # Function to apply blurred background image
19
+ def set_blurred_background(image_path):
20
+ with open(image_path, "rb") as img_file:
21
+ img_base64 = base64.b64encode(img_file.read()).decode()
22
+ st.markdown(
23
+ f"""
24
+ <style>
25
+ .stApp {{
26
+ background-image: url("data:image/png;base64,{img_base64}");
27
+ background-size: cover;
28
+ background-attachment: fixed;
29
+ background-position: center;
30
+ filter: blur(4px);
31
+ }}
32
+ .main > div {{
33
+ background-color: rgba(255, 255, 255, 0.9);
34
+ padding: 2rem;
35
+ border-radius: 15px;
36
+ }}
37
+ </style>
38
+ """,
39
+ unsafe_allow_html=True
40
+ )
41
+
42
+ # Uncomment and set your image path
43
+ # set_blurred_background("ann.jpeg")
44
+
45
+ # Title
46
+ st.markdown("""
47
+ <h1 style='text-align: center; color: #4B0082;'>โœจ Neural Network Explorer</h1>
48
+ <h4 style='text-align: center; color: #2F4F4F;'>Visualize and train simple neural networks interactively</h4>
49
+ """, unsafe_allow_html=True)
50
+
51
+ # Customized sidebar layout and colors
52
+ st.sidebar.markdown("""
53
+ <style>
54
+ section[data-testid="stSidebar"] > div:first-child {{
55
+ background-color: #F0F8FF;
56
+ padding: 1rem;
57
+ border-radius: 10px;
58
+ }}
59
+ </style>
60
+ """, unsafe_allow_html=True)
61
+
62
+ st.sidebar.header("๐Ÿ”ง Configure Model")
63
+ num_points = st.sidebar.slider("Number of Samples", 100, 10000, 1000, step=100)
64
+ noise = st.sidebar.slider("Dataset Noise", 0.01, 0.9, 0.1)
65
  batch_size = st.sidebar.slider("Batch Size", 1, 512, 32)
66
+ epochs = st.sidebar.slider("Epochs", 1, 100, 20)
67
  learning_rate = st.sidebar.slider("Learning Rate", 0.0001, 1.0, 0.01, step=0.0001, format="%.4f")
68
  hidden_layers = st.sidebar.slider("Hidden Layers", 1, 5, 2)
69
+ neurons_per_layer = st.sidebar.slider("Neurons per Layer", 1, 128, 16)
70
+ activation_name = st.sidebar.selectbox("Activation", ["relu", "tanh", "sigmoid", "linear"])
71
 
72
  # Dataset selection
73
+ st.markdown("## ๐Ÿงช Dataset Selection")
74
+ dataset_option = st.selectbox("Select a dataset", ("circle", "moons", "classification"))
75
 
 
76
  if dataset_option == "circle":
77
  x, y = make_circles(n_samples=num_points, noise=noise, factor=0.5, random_state=42)
78
  elif dataset_option == "moons":
79
  x, y = make_moons(n_samples=num_points, noise=noise, random_state=42)
80
  else:
81
+ x, y = make_classification(n_samples=num_points, n_features=2, n_informative=2, n_redundant=0,
82
+ n_clusters_per_class=1, random_state=42)
83
 
84
+ # Show input data
85
+ if st.button("๐Ÿ“Š Show Dataset"):
86
+ st.subheader("๐ŸŽฏ Sample Distribution")
87
  fig, ax = plt.subplots()
88
+ sns.scatterplot(x=x[:, 0], y=x[:, 1], hue=y, palette="coolwarm", ax=ax)
89
  st.pyplot(fig)
90
 
91
+ # Train model
92
+ if st.button("๐Ÿš€ Train Model"):
93
+ st.subheader("โš™๏ธ Training the Model...")
94
+ x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42, stratify=y)
95
+ scaler = StandardScaler()
96
+ x_train = scaler.fit_transform(x_train)
97
+ x_test = scaler.transform(x_test)
98
 
99
+ model = Sequential()
100
+ model.add(Dense(neurons_per_layer, input_shape=(2,), activation=activation_name))
101
+ for _ in range(hidden_layers - 1):
102
+ model.add(Dense(neurons_per_layer, activation=activation_name))
103
+ model.add(Dense(1, activation="sigmoid"))
104
 
105
+ optimizer = SGD(learning_rate=learning_rate)
106
+ model.compile(optimizer=optimizer, loss="binary_crossentropy", metrics=["accuracy"])
107
+ history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.2, verbose=0)
108
 
109
+ st.success("โœ… Model trained successfully!")
110
 
111
+ st.subheader("๐Ÿ“‰ Training Metrics")
 
112
  fig, ax = plt.subplots()
113
+ ax.plot(history.history['loss'], label='Train Loss')
114
+ ax.plot(history.history['val_loss'], label='Val Loss')
115
+ ax.set_title("Loss Over Epochs")
 
116
  ax.legend()
117
  st.pyplot(fig)
118
 
119
+ st.write(f"๐Ÿ”ข Final Training Loss: **{history.history['loss'][-1]:.4f}**")
120
+ st.write(f"๐Ÿ” Final Validation Loss: **{history.history['val_loss'][-1]:.4f}**")
 
 
 
121
 
122
+ class ModelWrapper:
 
123
  def __init__(self, model):
124
  self.model = model
125
 
126
  def predict(self, X):
127
  return (self.model.predict(X) > 0.5).astype("int32")
128
 
129
+ st.subheader("๐ŸŒˆ Decision Boundary")
130
+ fig, ax = plt.subplots()
131
+ plot_decision_regions(X=x_train, y=y_train, clf=ModelWrapper(model), ax=ax)
132
+ st.pyplot(fig)