Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
#
|
| 6 |
-
st.
|
| 7 |
-
st.
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Safe function evaluation
|
| 10 |
-
def
|
| 11 |
-
"""
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
"""
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
st.
|
| 37 |
-
st.
|
| 38 |
-
|
| 39 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
st.
|
| 43 |
-
st.
|
| 44 |
-
|
| 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=
|
| 50 |
)
|
| 51 |
-
st.markdown("---")
|
| 52 |
|
| 53 |
-
#
|
| 54 |
-
st.
|
| 55 |
-
st.
|
| 56 |
-
|
| 57 |
-
st.session_state.
|
| 58 |
-
st.session_state.
|
| 59 |
-
st.session_state.x_points = [initial_point]
|
| 60 |
-
st.session_state.y_points = [evaluate_function(function_input, initial_point)]
|
| 61 |
|
| 62 |
-
|
|
|
|
| 63 |
try:
|
| 64 |
-
|
| 65 |
-
st.session_state.
|
| 66 |
-
st.session_state.
|
| 67 |
-
st.session_state.
|
| 68 |
-
st.session_state.
|
| 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 |
-
#
|
| 81 |
-
st.
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
f'<strong>Current f(x): </strong>{st.session_state.y_points[-1]:.4f}</div>',
|
| 86 |
-
unsafe_allow_html=True
|
| 87 |
-
)
|
| 88 |
|
| 89 |
-
#
|
| 90 |
-
|
| 91 |
-
|
| 92 |
|
| 93 |
# Create the plot
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
#
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 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(
|
|
|
|
| 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)
|