Mpavan45 commited on
Commit
3510c4a
·
verified ·
1 Parent(s): 5731672

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -119
app.py CHANGED
@@ -2,138 +2,126 @@ import streamlit as st
2
  import numpy as np
3
  import plotly.graph_objects as go
4
 
5
- # Title of the app
6
- st.title("Interactive Gradient Descent Visualizer")
7
- st.markdown("---") # Horizontal separator for cleaner layout
 
 
8
 
9
  # Safe function evaluation
10
- def evaluate_function(expression, x_value):
11
- """Safely evaluates the mathematical function."""
12
- allowed_names = {"x": x_value, "np": np} # Allow only x and numpy
13
- return eval(expression, {"_builtins_": None}, allowed_names)
14
-
15
- # Compute derivative using finite difference
16
- def compute_derivative(expression, x_value, h=1e-5):
17
- """Numerically calculates the derivative at a given point."""
18
- return (evaluate_function(expression, x_value + h) - evaluate_function(expression, x_value - h)) / (2 * h)
19
-
20
- # Tangent line calculation
21
- def calculate_tangent(expression, x_value, x_range):
22
- """Generates the tangent line for a given point."""
23
- y_value = evaluate_function(expression, x_value)
24
- slope = compute_derivative(expression, x_value)
25
- return slope * (x_range - x_value) + y_value
26
-
27
- # Reset state
28
- def reset_session_state():
29
- st.session_state.x_current = st.session_state.initial_point
30
- st.session_state.iter_count = 0
31
- st.session_state.x_points = [st.session_state.initial_point]
32
- st.session_state.y_points = [evaluate_function(st.session_state.math_function, st.session_state.initial_point)]
33
-
34
- # Left Side - Section 1: Input Your Function
35
- st.container()
36
- st.header("Input Your Function")
37
- st.markdown("Define a mathematical function (e.g., `x**2`, `np.sin(x)`, `x**3 - 3*x + 2`):")
38
- function_input = st.text_input("Enter Function:", "x**2 + x", key="math_function", on_change=reset_session_state)
39
- st.markdown("---")
 
 
 
 
 
 
 
 
 
40
 
41
- # Left Side - Section 2: Set Parameters for Gradient Descent
42
- st.container()
43
- st.header("Set Parameters for Gradient Descent")
44
- st.markdown("Configure the starting point and learning rate:")
45
- initial_point = st.number_input(
46
- "Initial Value of x", value=4.0, step=0.1, format="%.2f", key="initial_point", on_change=reset_session_state
47
  )
48
- learning_rate = st.number_input(
49
- "Learning Rate", value=0.1, step=0.01, format="%.2f", key="learning_rate", on_change=reset_session_state
50
  )
51
- st.markdown("---")
52
 
53
- # Right Side - Section 1: Gradient Descent Updates
54
- st.container()
55
- st.header("Gradient Descent Updates")
56
- if "x_current" not in st.session_state:
57
- st.session_state.x_current = initial_point
58
- st.session_state.iter_count = 0
59
- st.session_state.x_points = [initial_point]
60
- st.session_state.y_points = [evaluate_function(function_input, initial_point)]
61
 
62
- if st.button("Perform Gradient Descent Step", type="primary"):
 
63
  try:
64
- gradient = compute_derivative(function_input, st.session_state.x_current)
65
- st.session_state.x_current -= learning_rate * gradient
66
- st.session_state.iter_count += 1
67
- st.session_state.x_points.append(st.session_state.x_current)
68
- st.session_state.y_points.append(evaluate_function(function_input, st.session_state.x_current))
69
  except Exception as e:
70
- st.error(f"Error: {str(e)}")
71
-
72
- # Right Side - Section 2: Gradient Descent Progress (with custom style)
73
- st.container()
74
- st.subheader("Gradient Descent Progress")
75
- st.markdown(f"**Iteration:** {st.session_state.iter_count}")
76
- st.markdown(f"**Current x Value:** {st.session_state.x_current:.4f}")
77
- st.markdown(f"**Current Function Value (f(x)):** {st.session_state.y_points[-1]:.4f}")
78
- st.markdown("---")
79
 
80
- # Styling the updates section with custom HTML
81
- st.markdown(
82
- f'<div style="background-color:#f0f0f0; padding: 10px; border-radius: 5px;">'
83
- f'<strong>Iteration: </strong>{st.session_state.iter_count} <br>'
84
- f'<strong>Current x Value: </strong>{st.session_state.x_current:.4f} <br>'
85
- f'<strong>Current f(x): </strong>{st.session_state.y_points[-1]:.4f}</div>',
86
- unsafe_allow_html=True
87
- )
88
 
89
- # Generate plot data
90
- x_vals = np.linspace(-10, 10, 400)
91
- y_vals = [evaluate_function(function_input, x) for x in x_vals]
92
 
93
  # Create the plot
94
- plot = go.Figure()
95
-
96
- # Add function plot
97
- plot.add_trace(
98
- go.Scatter(x=x_vals, y=y_vals, mode="lines", line=dict(color="green", width=3), name="Function Curve")
99
- )
100
-
101
- # Add gradient descent points
102
- plot.add_trace(
103
- go.Scatter(
104
- x=st.session_state.x_points,
105
- y=st.session_state.y_points,
106
- mode="markers",
107
- marker=dict(color="red", size=10, symbol="diamond"),
108
- name="Descent Steps",
109
- )
110
- )
111
-
112
- # Add tangent line
113
- current_x = st.session_state.x_current
114
- current_y = evaluate_function(function_input, current_x)
115
- slope = compute_derivative(function_input, current_x)
116
- tangent_x = np.linspace(current_x - 2, current_x + 2, 100)
117
- tangent_y = calculate_tangent(function_input, current_x, tangent_x)
118
-
119
- plot.add_trace(
120
- go.Scatter(
121
- x=tangent_x,
122
- y=tangent_y,
123
- mode="lines",
124
- line=dict(color="blue", width=2, dash="dash"),
125
- name="Tangent Line",
126
- )
127
- )
128
-
129
- # Update plot layout
130
- plot.update_layout(
131
- title="Interactive Gradient Descent with Tangent Visualization",
132
- xaxis_title="x",
133
- yaxis_title="f(x)",
134
- template="plotly_dark",
135
- legend=dict(bgcolor="rgba(255,255,255,0.5)", bordercolor="gray", borderwidth=1),
136
  )
137
 
138
  # Display the plot
139
- st.plotly_chart(plot)
 
2
  import numpy as np
3
  import plotly.graph_objects as go
4
 
5
+ # Set up the page title and layout
6
+ st.set_page_config(page_title="Gradient Descent Visualizer", layout="wide")
7
+ st.title("🌟 Gradient Descent Visualizer")
8
+ st.markdown("## Visualizing Gradient Descent with Tangent Lines")
9
+ st.markdown("---")
10
 
11
  # Safe function evaluation
12
+ def safe_eval(func_str, x_val):
13
+ """
14
+ Safely evaluates the function at a given x value.
15
+ Only allows numpy operations and 'x' as the variable.
16
+ """
17
+ allowed_names = {"x": x_val, "np": np}
18
+ return eval(func_str, {"_builtins_": None}, allowed_names)
19
+
20
+ # Derivative using finite difference method
21
+ def derivative(func_str, x_val, h=1e-5):
22
+ """
23
+ Calculates the derivative of the function at a point x using numerical methods.
24
+ """
25
+ return (safe_eval(func_str, x_val + h) - safe_eval(func_str, x_val - h)) / (2 * h)
26
+
27
+ # Compute tangent line
28
+ def tangent_line(func_str, x_val, x_range):
29
+ """
30
+ Computes the tangent line at a given x value over a specified x range.
31
+ """
32
+ y_val = safe_eval(func_str, x_val)
33
+ slope = derivative(func_str, x_val)
34
+ return slope * (x_range - x_val) + y_val
35
+
36
+ # Reset state on input changes
37
+ def reset_state():
38
+ st.session_state.x = st.session_state.starting_point
39
+ st.session_state.iteration = 0
40
+ st.session_state.x_vals = [st.session_state.starting_point]
41
+ st.session_state.y_vals = [safe_eval(st.session_state.func_input, st.session_state.starting_point)]
42
+
43
+ # Sidebar for user input with customized background and font color
44
+ st.sidebar.header("🔧 Function and Parameters")
45
+ st.sidebar.markdown("<p style='color:#FF5733; font-size:16px;'>Enter a mathematical function for gradient descent:</p>", unsafe_allow_html=True)
46
+
47
+ # Function input
48
+ func_input = st.sidebar.text_input(
49
+ "Function of x (e.g., x*2 + x):", "x*2 + x", key="func_input", on_change=reset_state
50
+ )
51
 
52
+ # Gradient Descent parameters
53
+ st.sidebar.markdown("<p style='color:#FF5733; font-size:16px;'>Set the starting point and learning rate:</p>", unsafe_allow_html=True)
54
+ starting_point = st.sidebar.number_input(
55
+ "Starting Point", value=4.0, step=0.1, format="%.2f", key="starting_point", on_change=reset_state
 
 
56
  )
57
+ learning_rate = st.sidebar.number_input(
58
+ "Learning Rate", value=0.1, step=0.01, format="%.2f", key="learning_rate", on_change=reset_state
59
  )
 
60
 
61
+ # Initialize session state variables
62
+ if "x" not in st.session_state:
63
+ st.session_state.x = starting_point
64
+ st.session_state.iteration = 0
65
+ st.session_state.x_vals = [starting_point]
66
+ st.session_state.y_vals = [safe_eval(func_input, starting_point)]
 
 
67
 
68
+ # Perform one iteration when the button is pressed
69
+ if st.sidebar.button("🔄 Perform Iteration"):
70
  try:
71
+ grad = derivative(func_input, st.session_state.x)
72
+ st.session_state.x -= learning_rate * grad
73
+ st.session_state.iteration += 1
74
+ st.session_state.x_vals.append(st.session_state.x)
75
+ st.session_state.y_vals.append(safe_eval(func_input, st.session_state.x))
76
  except Exception as e:
77
+ st.sidebar.error(f"Error: {str(e)}")
 
 
 
 
 
 
 
 
78
 
79
+ # Display gradient descent progress
80
+ st.subheader("🧮 Gradient Descent Progress")
81
+ st.write(f"*Iteration:* {st.session_state.iteration}")
82
+ st.write(f"*Current x:* {st.session_state.x:.4f}")
83
+ st.write(f"*Current f(x):* {st.session_state.y_vals[-1]:.4f}")
 
 
 
84
 
85
+ # Plotting
86
+ x_range = np.linspace(-2, 6, 400) # Zoomed-in x-axis range for better visualization
87
+ y_range = [safe_eval(func_input, x) for x in x_range]
88
 
89
  # Create the plot
90
+ fig = go.Figure()
91
+
92
+ # Plot the function with a cool gradient color
93
+ fig.add_trace(go.Scatter(x=x_range, y=y_range, mode="lines", line=dict(color="royalblue", width=3), name="Function"))
94
+
95
+ # Plot gradient descent points with purple color
96
+ fig.add_trace(go.Scatter(
97
+ x=st.session_state.x_vals, y=st.session_state.y_vals,
98
+ mode="markers", marker=dict(color="mediumvioletred", size=10, symbol="circle"), name="Gradient Descent Points"
99
+ ))
100
+
101
+ # Plot tangent line at current point with dotted line
102
+ current_x = st.session_state.x
103
+ current_y = safe_eval(func_input, current_x)
104
+ slope = derivative(func_input, current_x)
105
+
106
+ tangent_x = np.linspace(current_x - 1, current_x + 1, 100) # Smaller range for tangent line
107
+ tangent_y = tangent_line(func_input, current_x, tangent_x)
108
+
109
+ fig.add_trace(go.Scatter(
110
+ x=tangent_x, y=tangent_y, mode="lines",
111
+ line=dict(color="orange", dash="dot", width=2), name="Tangent Line"
112
+ ))
113
+
114
+ # Customize the layout with a soft gradient background
115
+ fig.update_layout(
116
+ title="📉 Gradient Descent Visualization",
117
+ xaxis=dict(title="x", range=[-2, 6], showgrid=False),
118
+ yaxis=dict(title="f(x)", showgrid=False),
119
+ template="plotly",
120
+ plot_bgcolor="rgb(243, 243, 243)", # Soft background color
121
+ paper_bgcolor="rgb(243, 243, 243)", # Soft background color
122
+ font=dict(family="Arial, sans-serif", size=14, color="black"),
123
+ legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
 
 
 
 
 
 
 
 
124
  )
125
 
126
  # Display the plot
127
+ st.plotly_chart(fig, use_container_width=True)