trohith89 commited on
Commit
79da4ed
·
verified ·
1 Parent(s): fa5386b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -93
app.py CHANGED
@@ -1,21 +1,11 @@
1
-
2
-
3
- import streamlit as st
4
-
5
- # Title
6
- st.title("It's Your Turn...")
7
-
8
  import streamlit as st
9
  import numpy as np
10
  import plotly.graph_objects as go
11
 
12
- # Title of the app
13
- st.title("Gradient Descent Visualizer with Tangent Lines")
14
-
15
  # Safe function evaluation
16
  def safe_eval(func_str, x_val):
17
  """ Safely evaluates the function at a given x value. """
18
- allowed_names = {"x": x_val, "np": np} # Only allow x and numpy
19
  return eval(func_str, {"__builtins__": None}, allowed_names)
20
 
21
  # Function derivative using finite difference method
@@ -23,7 +13,7 @@ def derivative(func_str, x_val, h=1e-5):
23
  """ Numerically compute the derivative of the function at x using finite differences. """
24
  return (safe_eval(func_str, x_val + h) - safe_eval(func_str, x_val - h)) / (2 * h)
25
 
26
- # Tangent Line Equation
27
  def tangent_line(func_str, x_val, x_range):
28
  """ Compute the tangent line at a given x value. """
29
  y_val = safe_eval(func_str, x_val)
@@ -37,84 +27,105 @@ def reset_state():
37
  st.session_state.x_vals = [st.session_state.starting_point]
38
  st.session_state.y_vals = [safe_eval(st.session_state.func_input, st.session_state.starting_point)]
39
 
40
- # Function input
41
- st.header("Define Your Function")
42
- func_input = st.text_input("Enter a function of 'x' (e.g., x**2 + x, sin(x), x**3 - 3*x + 2):", "x**2 + x", key="func_input", on_change=reset_state)
43
-
44
- # Starting Point and Learning Rate
45
- st.header("Gradient Descent Parameters")
46
- starting_point = st.number_input("Starting Point", value=4.0, step=0.1, format="%.2f", key="starting_point", on_change=reset_state)
47
- learning_rate = st.number_input("Learning Rate", value=0.1, step=0.01, format="%.2f", key="learning_rate", on_change=reset_state)
48
-
49
- # Initialize session state variables if they don't exist
50
- if "x" not in st.session_state:
51
- st.session_state.x = starting_point
52
- st.session_state.iteration = 0
53
- st.session_state.x_vals = [starting_point]
54
- st.session_state.y_vals = [safe_eval(func_input, starting_point)]
55
-
56
- # "Next Iteration" button logic
57
- if st.button("Next Iteration"):
58
- try:
59
- # Perform one iteration of gradient descent
60
- grad = derivative(func_input, st.session_state.x)
61
- st.session_state.x = st.session_state.x - learning_rate * grad
62
- st.session_state.iteration += 1
63
-
64
- # Save the new x and y values
65
- st.session_state.x_vals.append(st.session_state.x)
66
- st.session_state.y_vals.append(safe_eval(func_input, st.session_state.x))
67
- except Exception as e:
68
- st.error(f"Error: {str(e)}")
69
-
70
- # Display iteration results
71
- st.subheader("Gradient Descent Progress")
72
- st.write(f"Iteration: {st.session_state.iteration}")
73
- st.write(f"Current x: {st.session_state.x:.4f}")
74
- st.write(f"Current f(x): {st.session_state.y_vals[-1]:.4f}")
75
-
76
- # Plot the function, gradient descent points, and tangent line
77
- x_plot = np.linspace(-10, 10, 400)
78
- y_plot = [safe_eval(func_input, x) for x in x_plot]
79
-
80
- fig = go.Figure()
81
-
82
- # Add the function curve
83
- fig.add_trace(go.Scatter(x=x_plot, y=y_plot, mode="lines", name="Function"))
84
-
85
- # Add gradient descent points in red
86
- fig.add_trace(go.Scatter(
87
- x=st.session_state.x_vals,
88
- y=st.session_state.y_vals,
89
- mode="markers",
90
- marker=dict(color="red", size=8),
91
- name="Gradient Descent Points"
92
- ))
93
-
94
- # Add the tangent line at the current point
95
- current_x = st.session_state.x
96
- current_y = safe_eval(func_input, current_x)
97
- slope = derivative(func_input, current_x)
98
-
99
- # Generate tangent line range
100
- tangent_x = np.linspace(current_x - 2, current_x + 2, 100)
101
- tangent_y = tangent_line(func_input, current_x, tangent_x)
102
-
103
- # Plot the tangent line as a straight solid line
104
- fig.add_trace(go.Scatter(
105
- x=tangent_x,
106
- y=tangent_y,
107
- mode="lines",
108
- line=dict(color="orange", width=3),
109
- name="Tangent Line"
110
- ))
111
-
112
- # Update layout
113
- fig.update_layout(
114
- xaxis_title="x",
115
- yaxis_title="f(x)",
116
- title="Gradient Descent Visualization with Tangent Line"
117
- )
118
-
119
- # Display the plot
120
- st.plotly_chart(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import numpy as np
3
  import plotly.graph_objects as go
4
 
 
 
 
5
  # Safe function evaluation
6
  def safe_eval(func_str, x_val):
7
  """ Safely evaluates the function at a given x value. """
8
+ allowed_names = {"x": x_val, "np": np}
9
  return eval(func_str, {"__builtins__": None}, allowed_names)
10
 
11
  # Function derivative using finite difference method
 
13
  """ Numerically compute the derivative of the function at x using finite differences. """
14
  return (safe_eval(func_str, x_val + h) - safe_eval(func_str, x_val - h)) / (2 * h)
15
 
16
+ # Tangent line equation
17
  def tangent_line(func_str, x_val, x_range):
18
  """ Compute the tangent line at a given x value. """
19
  y_val = safe_eval(func_str, x_val)
 
27
  st.session_state.x_vals = [st.session_state.starting_point]
28
  st.session_state.y_vals = [safe_eval(st.session_state.func_input, st.session_state.starting_point)]
29
 
30
+ # Predefined function buttons
31
+ predefined_functions = {
32
+ "x²": "x**2",
33
+ "x³": "x**3",
34
+ "sin(x)": "np.sin(x)",
35
+ "log(x)": "np.log(x)",
36
+ "x³ - 3x² + 2x": "x**3 - 3*x**2 + 2*x"
37
+ }
38
+
39
+ # Create two sections using columns
40
+ left_col, right_col = st.columns(2)
41
+
42
+ # Left Section: User Input
43
+ with left_col:
44
+ st.header("It's Your Turn...")
45
+
46
+ # Function input and predefined buttons
47
+ st.subheader("Define Your Function")
48
+ func_input = st.text_input("Enter a function of 'x':", "x**2 + x", key="func_input", on_change=reset_state)
49
+ st.write("Or choose a predefined function:")
50
+
51
+ cols = st.columns(5)
52
+ for i, (btn_label, func_value) in enumerate(predefined_functions.items()):
53
+ with cols[i]:
54
+ if st.button(btn_label):
55
+ st.session_state.func_input = func_value
56
+ reset_state()
57
+
58
+ # Gradient Descent Parameters
59
+ st.subheader("Gradient Descent Parameters")
60
+ starting_point = st.number_input("Starting Point", value=4.0, step=0.1, format="%.2f", key="starting_point", on_change=reset_state)
61
+ learning_rate = st.number_input("Learning Rate", value=0.25, step=0.01, format="%.2f", key="learning_rate", on_change=reset_state)
62
+
63
+ # Set Up and Next Iteration Buttons
64
+ if "x" not in st.session_state:
65
+ st.session_state.x = starting_point
66
+ st.session_state.iteration = 0
67
+ st.session_state.x_vals = [starting_point]
68
+ st.session_state.y_vals = [safe_eval(func_input, starting_point)]
69
+
70
+ if st.button("Set Up Function"):
71
+ reset_state()
72
+
73
+ if st.button("Next Iteration"):
74
+ try:
75
+ grad = derivative(func_input, st.session_state.x)
76
+ st.session_state.x = st.session_state.x - learning_rate * grad
77
+ st.session_state.iteration += 1
78
+ st.session_state.x_vals.append(st.session_state.x)
79
+ st.session_state.y_vals.append(safe_eval(func_input, st.session_state.x))
80
+ except Exception as e:
81
+ st.error(f"Error: {str(e)}")
82
+
83
+ # Right Section: Visualization and Stats
84
+ with right_col:
85
+ st.subheader("Gradient Descent Visualization")
86
+
87
+ # Plot the function, gradient descent points, and tangent line
88
+ x_plot = np.linspace(-10, 10, 400)
89
+ y_plot = [safe_eval(func_input, x) for x in x_plot]
90
+
91
+ fig = go.Figure()
92
+
93
+ # Function curve
94
+ fig.add_trace(go.Scatter(x=x_plot, y=y_plot, mode="lines", name="Function"))
95
+
96
+ # Gradient descent points
97
+ fig.add_trace(go.Scatter(
98
+ x=st.session_state.x_vals,
99
+ y=st.session_state.y_vals,
100
+ mode="markers",
101
+ marker=dict(color="red", size=8),
102
+ name="Gradient Descent Points"
103
+ ))
104
+
105
+ # Tangent line at current point
106
+ current_x = st.session_state.x
107
+ tangent_x = np.linspace(current_x - 2, current_x + 2, 100)
108
+ tangent_y = tangent_line(func_input, current_x, tangent_x)
109
+
110
+ fig.add_trace(go.Scatter(
111
+ x=tangent_x,
112
+ y=tangent_y,
113
+ mode="lines",
114
+ line=dict(color="orange", width=3),
115
+ name="Tangent Line"
116
+ ))
117
+
118
+ # Update layout
119
+ fig.update_layout(
120
+ xaxis_title="x",
121
+ yaxis_title="f(x)",
122
+ title="Gradient Descent Visualization with Tangent Line"
123
+ )
124
+
125
+ # Display plot
126
+ st.plotly_chart(fig)
127
+
128
+ # Iteration and current point display
129
+ st.subheader("Iteration Counter")
130
+ st.info(f"Iteration: {st.session_state.iteration}")
131
+ st.success(f"Current x: {st.session_state.x:.4f}\nCurrent f(x): {st.session_state.y_vals[-1]:.4f}")