Spaces:
Build error
Build error
Update app.py
Browse files
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}
|
| 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
|
| 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 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
st.
|
| 55 |
-
|
| 56 |
-
#
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
st.
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
#
|
| 104 |
-
fig.add_trace(go.Scatter(
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
)
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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}")
|