NeonSamurai commited on
Commit
f5972d3
·
verified ·
1 Parent(s): 73e34c6

Update Home.py

Browse files
Files changed (1) hide show
  1. Home.py +269 -269
Home.py CHANGED
@@ -1,269 +1,269 @@
1
- import streamlit as st
2
- import numpy as np
3
- import pandas as pd
4
- import base64
5
- import plotly.graph_objects as go
6
-
7
- st.set_page_config(layout="wide")
8
-
9
- # Function parser to evaluate the mathematical function
10
- def parse_function(func_str, x):
11
- try:
12
- return eval(func_str)
13
- except Exception as e:
14
- st.error(f"Error evaluating function: {e}")
15
- return np.zeros_like(x)
16
-
17
- # Compute the gradient (derivative) at a point using numerical differentiation
18
- def compute_gradient(func_str, x):
19
- delta = 1e-8
20
- grad = (parse_function(func_str, x + delta) - parse_function(func_str, x)) / delta
21
- return grad
22
-
23
- # Streamlit App
24
- def encode_image(image_path):
25
- with open(image_path, "rb") as image_file:
26
- return base64.b64encode(image_file.read()).decode()
27
-
28
- def add_bg_from_local(image_file):
29
- encoded_string = encode_image(image_file)
30
- st.markdown(
31
- f"""
32
- <style>
33
- .stApp {{
34
- background-image: url(data:image/{"png"};base64,{encoded_string});
35
- background-size: cover;
36
- background-repeat: no-repeat;
37
- background-attachment: fixed;
38
- }}
39
- </style>
40
- """,
41
- unsafe_allow_html=True
42
- )
43
-
44
- add_bg_from_local("Icons/rm183-kul-21.jpg")
45
-
46
- st.markdown(
47
- """
48
- <style>
49
- .reportview-container {
50
- background: "white"
51
- }
52
- </style>
53
- """,
54
- unsafe_allow_html=True
55
- )
56
-
57
- st.markdown("""
58
- <style>
59
- body {
60
- font-family: 'Roboto', sans-serif;
61
- }
62
- .stButton>button {
63
- color: white;
64
- border-radius: 8px;
65
- padding: 10px 20px;
66
- font-weight: bold;
67
- transition: background-color 0.3s ease;
68
- }
69
- .stButton>button:hover {
70
- background-color: Black;
71
- border-color: white;
72
- color: white;
73
- }
74
- .sidebar .sidebar-content {
75
- padding: 2rem;
76
- }
77
- .stApp {
78
- font-family: 'Roboto', sans-serif;
79
- }
80
- </style>
81
- """, unsafe_allow_html=True)
82
-
83
- file_ = open("Icons/wave-chart-ezgif.com-gif-maker.gif", "rb").read()
84
- base64_gif = base64.b64encode(file_).decode("utf-8")
85
-
86
- st.markdown(
87
- f"""
88
- <h1 style='text-align: center; color: Black; margin-top: -50px; padding-top: 0px;'>
89
- Interactive Gradient Descent Visualizer
90
- <img src="data:image/gif;base64,{base64_gif}" alt="Icon" style="width: 85px; margin-right: 10px;">
91
- </h1>
92
- """,
93
- unsafe_allow_html=True
94
- )
95
- st.markdown("""
96
- <p style="color: black;">
97
- Explore how gradient descent works visually and interactively.
98
- Adjust parameters and watch as the algorithm converges towards the minimum of a function.
99
- </p>
100
- """,
101
- unsafe_allow_html=True)
102
-
103
- st.sidebar.header("Input Parameters")
104
-
105
- # Dropdown menu
106
- function_options = ["x**2", "x**3", "np.sin(x)", "1/x", "Custom Polynomial"]
107
- selected_function = st.sidebar.selectbox("Choose a function:", function_options)
108
-
109
- if selected_function == "Custom Polynomial":
110
- func_str = st.sidebar.text_input("Enter custom polynomial in terms of x:", value="x**2 - 4*x + 4")
111
- else:
112
- func_str = st.sidebar.text_input(f"Modify the selected function ({selected_function}):", value=selected_function)
113
-
114
- # Initialize session state variables if not already initialized
115
- if "x_vals" not in st.session_state:
116
- st.session_state.x_vals = []
117
- if "y_vals" not in st.session_state:
118
- st.session_state.y_vals = []
119
- if "current_step" not in st.session_state:
120
- st.session_state.current_step = 0
121
-
122
- # Input for initial x point and learning rate
123
- initial_x = st.sidebar.number_input("Initial Point (x):", value=0.00)
124
- learning_rate = st.sidebar.number_input("Learning Rate:", value=0.1, step=0.01, format="%.2f")
125
-
126
- # Update session state with initial values
127
- if st.session_state.current_step == 0:
128
- st.session_state.x_vals = [initial_x]
129
- st.session_state.y_vals = [parse_function(func_str, initial_x)]
130
-
131
- col1, col2 = st.sidebar.columns(2)
132
-
133
- if col1.button("Reset Graph"):
134
- st.session_state.x_vals = [initial_x]
135
- st.session_state.y_vals = [parse_function(func_str, initial_x)]
136
- st.session_state.current_step = 0
137
-
138
- if col2.button("Next Iteration"):
139
- current_x = st.session_state.x_vals[-1]
140
- grad = compute_gradient(func_str, current_x)
141
- next_x = current_x - learning_rate * grad
142
- st.session_state.x_vals.append(next_x)
143
- st.session_state.y_vals.append(parse_function(func_str, next_x))
144
- st.session_state.current_step += 1
145
-
146
- x_vals = np.linspace(-20, 30, 1000)
147
- y_vals = parse_function(func_str, x_vals)
148
-
149
- fig = go.Figure()
150
-
151
- # Add the function curve to the plot
152
- fig.add_trace(go.Scatter(x=x_vals, y=y_vals, mode='lines', name='Function Curve', line=dict(color='teal')))
153
-
154
- # Add the gradient descent steps (if any)
155
- if st.session_state.current_step > 0:
156
- fig.add_trace(go.Scatter(
157
- x=st.session_state.x_vals, y=st.session_state.y_vals,
158
- mode='markers+lines', name='Gradient Descent Steps',
159
- marker=dict(color='red', size=10), line=dict(dash='dash', width=1.5)
160
- ))
161
-
162
- # Function to draw the tangent line at the current point
163
- def draw_tangent(fig, func_str, x_point):
164
- y_point = parse_function(func_str, x_point)
165
- grad = compute_gradient(func_str, x_point)
166
- tangent_x = np.linspace(-20, 30, 1000)
167
- tangent_y = grad * (tangent_x - x_point) + y_point
168
-
169
- fig.add_trace(go.Scatter(
170
- x=tangent_x, y=tangent_y, mode='lines', name=f'Tangent at x={x_point:.2f}',
171
- line=dict(dash='dot', color='green', width=2)
172
- ))
173
- fig.add_trace(go.Scatter(
174
- x=[x_point], y=[y_point], mode='markers', name='Tangent Point',
175
- marker=dict(color='blue', size=12, symbol='circle')
176
- ))
177
-
178
- # Draw tangent at the last gradient descent point
179
- if len(st.session_state.x_vals) > 0:
180
- draw_tangent(fig, func_str, st.session_state.x_vals[-1])
181
-
182
- fig.update_layout(
183
- shapes=[
184
- dict(type="line", x0=-20, y0=0, x1=30, y1=0, line=dict(color="black", width=2)),
185
- dict(type="line", x0=0, y0=-110, x1=0, y1=120, line=dict(color="black", width=2))
186
- ],
187
- xaxis=dict(
188
- title='x',
189
- range=[-20, 30],
190
- showline=True,
191
- linecolor='black',
192
- linewidth=2,
193
- mirror=True,
194
- ticks='inside',
195
- tickfont=dict(color='black'),
196
- titlefont=dict(color='black'),
197
- ),
198
- yaxis=dict(
199
- title='y',
200
- range=[-110, 120],
201
- showline=True,
202
- linecolor='Black',
203
- linewidth=2,
204
- mirror=True,
205
- ticks='inside',
206
- tickfont=dict(color='black'),
207
- titlefont=dict(color='black'),
208
- ),
209
-
210
- plot_bgcolor= 'rgba(0, 0, 0, 0)',
211
- paper_bgcolor= 'rgba(0, 0, 0, 0)',
212
- font=dict(color='black'),
213
- legend=dict(
214
- font=dict(color='black'),
215
- x=1.05,
216
- xanchor='left',
217
- y=1,
218
- yanchor='top'
219
- ),
220
-
221
- width=800, height=500,
222
- template="plotly_white",
223
- title="Gradient Descent on the Selected Function",
224
- titlefont=dict(color='black'),
225
- margin=dict(l=50, r=50, t=50, b=50),
226
- )
227
-
228
- st.plotly_chart(fig, use_container_width=True)
229
-
230
- if st.session_state.current_step > 0:
231
- iteration_data = {
232
- "Iteration": list(range(st.session_state.current_step + 1)),
233
- "x Value": [f"{x_val:.5f}" for x_val in st.session_state.x_vals],
234
- "y Value": [f"{y_val:.5f}" for y_val in st.session_state.y_vals]
235
- }
236
-
237
- iteration_df = pd.DataFrame(iteration_data)
238
-
239
- st.markdown("<h3 style='color: black;'>Iteration Details</h3>", unsafe_allow_html=True)
240
- st.markdown(
241
- iteration_df.to_html(index=False, escape=False),
242
- unsafe_allow_html=True
243
- )
244
-
245
-
246
- st.markdown("""
247
- <style>
248
- .dataframe {
249
- color: black;
250
- font-size: 14px;
251
- border-collapse: collapse;
252
- width: 100%;
253
- }
254
- .dataframe th, .dataframe td {
255
- padding: 8px;
256
- text-align: center;
257
- border: 1px solid black;
258
- }
259
- .dataframe th {
260
- background-color: #f2f2f2;
261
- border: 2px solid black;
262
- }
263
- </style>
264
- """, unsafe_allow_html=True)
265
-
266
- st.sidebar.subheader("Current Status")
267
- st.sidebar.write(f"Iteration: {st.session_state.current_step}")
268
- st.sidebar.write(f"Current x: {st.session_state.x_vals[-1]:.5f}")
269
- st.sidebar.write(f"Current y: {st.session_state.y_vals[-1]:.5f}")
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import pandas as pd
4
+ import base64
5
+ import plotly.graph_objects as go
6
+
7
+ st.set_page_config(layout="wide")
8
+
9
+ # Function parser to evaluate the mathematical function
10
+ def parse_function(func_str, x):
11
+ try:
12
+ return eval(func_str)
13
+ except Exception as e:
14
+ st.error(f"Error evaluating function: {e}")
15
+ return np.zeros_like(x)
16
+
17
+ # Compute the gradient (derivative) at a point using numerical differentiation
18
+ def compute_gradient(func_str, x):
19
+ delta = 1e-8
20
+ grad = (parse_function(func_str, x + delta) - parse_function(func_str, x)) / delta
21
+ return grad
22
+
23
+ # Streamlit App
24
+ def encode_image(image_path):
25
+ with open(image_path, "rb") as image_file:
26
+ return base64.b64encode(image_file.read()).decode()
27
+
28
+ def add_bg_from_local(image_file):
29
+ encoded_string = encode_image(image_file)
30
+ st.markdown(
31
+ f"""
32
+ <style>
33
+ .stApp {{
34
+ background-image: url(data:image/{"png"};base64,{encoded_string});
35
+ background-size: cover;
36
+ background-repeat: no-repeat;
37
+ background-attachment: fixed;
38
+ }}
39
+ </style>
40
+ """,
41
+ unsafe_allow_html=True
42
+ )
43
+
44
+ add_bg_from_local("Icon/rm183-kul-21.jpg")
45
+
46
+ st.markdown(
47
+ """
48
+ <style>
49
+ .reportview-container {
50
+ background: "white"
51
+ }
52
+ </style>
53
+ """,
54
+ unsafe_allow_html=True
55
+ )
56
+
57
+ st.markdown("""
58
+ <style>
59
+ body {
60
+ font-family: 'Roboto', sans-serif;
61
+ }
62
+ .stButton>button {
63
+ color: white;
64
+ border-radius: 8px;
65
+ padding: 10px 20px;
66
+ font-weight: bold;
67
+ transition: background-color 0.3s ease;
68
+ }
69
+ .stButton>button:hover {
70
+ background-color: Black;
71
+ border-color: white;
72
+ color: white;
73
+ }
74
+ .sidebar .sidebar-content {
75
+ padding: 2rem;
76
+ }
77
+ .stApp {
78
+ font-family: 'Roboto', sans-serif;
79
+ }
80
+ </style>
81
+ """, unsafe_allow_html=True)
82
+
83
+ file_ = open("Icon/wave-chart-ezgif.com-gif-maker.gif", "rb").read()
84
+ base64_gif = base64.b64encode(file_).decode("utf-8")
85
+
86
+ st.markdown(
87
+ f"""
88
+ <h1 style='text-align: center; color: Black; margin-top: -50px; padding-top: 0px;'>
89
+ Interactive Gradient Descent Visualizer
90
+ <img src="data:image/gif;base64,{base64_gif}" alt="Icon" style="width: 85px; margin-right: 10px;">
91
+ </h1>
92
+ """,
93
+ unsafe_allow_html=True
94
+ )
95
+ st.markdown("""
96
+ <p style="color: black;">
97
+ Explore how gradient descent works visually and interactively.
98
+ Adjust parameters and watch as the algorithm converges towards the minimum of a function.
99
+ </p>
100
+ """,
101
+ unsafe_allow_html=True)
102
+
103
+ st.sidebar.header("Input Parameters")
104
+
105
+ # Dropdown menu
106
+ function_options = ["x**2", "x**3", "np.sin(x)", "1/x", "Custom Polynomial"]
107
+ selected_function = st.sidebar.selectbox("Choose a function:", function_options)
108
+
109
+ if selected_function == "Custom Polynomial":
110
+ func_str = st.sidebar.text_input("Enter custom polynomial in terms of x:", value="x**2 - 4*x + 4")
111
+ else:
112
+ func_str = st.sidebar.text_input(f"Modify the selected function ({selected_function}):", value=selected_function)
113
+
114
+ # Initialize session state variables if not already initialized
115
+ if "x_vals" not in st.session_state:
116
+ st.session_state.x_vals = []
117
+ if "y_vals" not in st.session_state:
118
+ st.session_state.y_vals = []
119
+ if "current_step" not in st.session_state:
120
+ st.session_state.current_step = 0
121
+
122
+ # Input for initial x point and learning rate
123
+ initial_x = st.sidebar.number_input("Initial Point (x):", value=0.00)
124
+ learning_rate = st.sidebar.number_input("Learning Rate:", value=0.1, step=0.01, format="%.2f")
125
+
126
+ # Update session state with initial values
127
+ if st.session_state.current_step == 0:
128
+ st.session_state.x_vals = [initial_x]
129
+ st.session_state.y_vals = [parse_function(func_str, initial_x)]
130
+
131
+ col1, col2 = st.sidebar.columns(2)
132
+
133
+ if col1.button("Reset Graph"):
134
+ st.session_state.x_vals = [initial_x]
135
+ st.session_state.y_vals = [parse_function(func_str, initial_x)]
136
+ st.session_state.current_step = 0
137
+
138
+ if col2.button("Next Iteration"):
139
+ current_x = st.session_state.x_vals[-1]
140
+ grad = compute_gradient(func_str, current_x)
141
+ next_x = current_x - learning_rate * grad
142
+ st.session_state.x_vals.append(next_x)
143
+ st.session_state.y_vals.append(parse_function(func_str, next_x))
144
+ st.session_state.current_step += 1
145
+
146
+ x_vals = np.linspace(-20, 30, 1000)
147
+ y_vals = parse_function(func_str, x_vals)
148
+
149
+ fig = go.Figure()
150
+
151
+ # Add the function curve to the plot
152
+ fig.add_trace(go.Scatter(x=x_vals, y=y_vals, mode='lines', name='Function Curve', line=dict(color='teal')))
153
+
154
+ # Add the gradient descent steps (if any)
155
+ if st.session_state.current_step > 0:
156
+ fig.add_trace(go.Scatter(
157
+ x=st.session_state.x_vals, y=st.session_state.y_vals,
158
+ mode='markers+lines', name='Gradient Descent Steps',
159
+ marker=dict(color='red', size=10), line=dict(dash='dash', width=1.5)
160
+ ))
161
+
162
+ # Function to draw the tangent line at the current point
163
+ def draw_tangent(fig, func_str, x_point):
164
+ y_point = parse_function(func_str, x_point)
165
+ grad = compute_gradient(func_str, x_point)
166
+ tangent_x = np.linspace(-20, 30, 1000)
167
+ tangent_y = grad * (tangent_x - x_point) + y_point
168
+
169
+ fig.add_trace(go.Scatter(
170
+ x=tangent_x, y=tangent_y, mode='lines', name=f'Tangent at x={x_point:.2f}',
171
+ line=dict(dash='dot', color='green', width=2)
172
+ ))
173
+ fig.add_trace(go.Scatter(
174
+ x=[x_point], y=[y_point], mode='markers', name='Tangent Point',
175
+ marker=dict(color='blue', size=12, symbol='circle')
176
+ ))
177
+
178
+ # Draw tangent at the last gradient descent point
179
+ if len(st.session_state.x_vals) > 0:
180
+ draw_tangent(fig, func_str, st.session_state.x_vals[-1])
181
+
182
+ fig.update_layout(
183
+ shapes=[
184
+ dict(type="line", x0=-20, y0=0, x1=30, y1=0, line=dict(color="black", width=2)),
185
+ dict(type="line", x0=0, y0=-110, x1=0, y1=120, line=dict(color="black", width=2))
186
+ ],
187
+ xaxis=dict(
188
+ title='x',
189
+ range=[-20, 30],
190
+ showline=True,
191
+ linecolor='black',
192
+ linewidth=2,
193
+ mirror=True,
194
+ ticks='inside',
195
+ tickfont=dict(color='black'),
196
+ titlefont=dict(color='black'),
197
+ ),
198
+ yaxis=dict(
199
+ title='y',
200
+ range=[-110, 120],
201
+ showline=True,
202
+ linecolor='Black',
203
+ linewidth=2,
204
+ mirror=True,
205
+ ticks='inside',
206
+ tickfont=dict(color='black'),
207
+ titlefont=dict(color='black'),
208
+ ),
209
+
210
+ plot_bgcolor= 'rgba(0, 0, 0, 0)',
211
+ paper_bgcolor= 'rgba(0, 0, 0, 0)',
212
+ font=dict(color='black'),
213
+ legend=dict(
214
+ font=dict(color='black'),
215
+ x=1.05,
216
+ xanchor='left',
217
+ y=1,
218
+ yanchor='top'
219
+ ),
220
+
221
+ width=800, height=500,
222
+ template="plotly_white",
223
+ title="Gradient Descent on the Selected Function",
224
+ titlefont=dict(color='black'),
225
+ margin=dict(l=50, r=50, t=50, b=50),
226
+ )
227
+
228
+ st.plotly_chart(fig, use_container_width=True)
229
+
230
+ if st.session_state.current_step > 0:
231
+ iteration_data = {
232
+ "Iteration": list(range(st.session_state.current_step + 1)),
233
+ "x Value": [f"{x_val:.5f}" for x_val in st.session_state.x_vals],
234
+ "y Value": [f"{y_val:.5f}" for y_val in st.session_state.y_vals]
235
+ }
236
+
237
+ iteration_df = pd.DataFrame(iteration_data)
238
+
239
+ st.markdown("<h3 style='color: black;'>Iteration Details</h3>", unsafe_allow_html=True)
240
+ st.markdown(
241
+ iteration_df.to_html(index=False, escape=False),
242
+ unsafe_allow_html=True
243
+ )
244
+
245
+
246
+ st.markdown("""
247
+ <style>
248
+ .dataframe {
249
+ color: black;
250
+ font-size: 14px;
251
+ border-collapse: collapse;
252
+ width: 100%;
253
+ }
254
+ .dataframe th, .dataframe td {
255
+ padding: 8px;
256
+ text-align: center;
257
+ border: 1px solid black;
258
+ }
259
+ .dataframe th {
260
+ background-color: #f2f2f2;
261
+ border: 2px solid black;
262
+ }
263
+ </style>
264
+ """, unsafe_allow_html=True)
265
+
266
+ st.sidebar.subheader("Current Status")
267
+ st.sidebar.write(f"Iteration: {st.session_state.current_step}")
268
+ st.sidebar.write(f"Current x: {st.session_state.x_vals[-1]:.5f}")
269
+ st.sidebar.write(f"Current y: {st.session_state.y_vals[-1]:.5f}")