Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
import plotly.graph_objs as go
|
| 5 |
+
|
| 6 |
+
st.markdown("""
|
| 7 |
+
<style>
|
| 8 |
+
.stApp {
|
| 9 |
+
background-color: #f9f9f9;
|
| 10 |
+
font-family: 'Segoe UI', sans-serif;
|
| 11 |
+
}
|
| 12 |
+
h1 {
|
| 13 |
+
text-align: center;
|
| 14 |
+
color: #2C3E50;
|
| 15 |
+
font-size: 38px !important;
|
| 16 |
+
font-weight: bold;
|
| 17 |
+
margin-bottom: 20px;
|
| 18 |
+
}
|
| 19 |
+
.stTextInput > div > div > input {
|
| 20 |
+
border: 2px solid #3498DB;
|
| 21 |
+
border-radius: 8px;
|
| 22 |
+
padding: 8px;
|
| 23 |
+
}
|
| 24 |
+
div.stButton > button {
|
| 25 |
+
background-color: #3498DB;
|
| 26 |
+
color: white;
|
| 27 |
+
border-radius: 10px;
|
| 28 |
+
padding: 10px 24px;
|
| 29 |
+
font-size: 16px;
|
| 30 |
+
border: none;
|
| 31 |
+
transition: 0.3s;
|
| 32 |
+
}
|
| 33 |
+
div.stButton > button:hover {
|
| 34 |
+
background-color: #2980B9;
|
| 35 |
+
transform: scale(1.05);
|
| 36 |
+
}
|
| 37 |
+
.stAlert {
|
| 38 |
+
border-radius: 8px;
|
| 39 |
+
}
|
| 40 |
+
.block-container {
|
| 41 |
+
padding-top: 2rem;
|
| 42 |
+
padding-bottom: 2rem;
|
| 43 |
+
max-width: 1200px;
|
| 44 |
+
}
|
| 45 |
+
</style>
|
| 46 |
+
""", unsafe_allow_html=True)
|
| 47 |
+
|
| 48 |
+
st.title("Gradient Descent Visualizer")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
func_input = st.text_input("Enter Function of x", "x**2")
|
| 52 |
+
start_point = float(st.text_input("Starting Point", "2"))
|
| 53 |
+
learning_rate = float(st.text_input("Learning Rate", "0.01"))
|
| 54 |
+
num_iterations = int(st.text_input("Number of Iterations", "10"))
|
| 55 |
+
|
| 56 |
+
def make_function(expr: str):
|
| 57 |
+
"""Dynamically create a function in torch"""
|
| 58 |
+
def func(x):
|
| 59 |
+
return eval(expr, {"x": x, "torch": torch})
|
| 60 |
+
return func
|
| 61 |
+
|
| 62 |
+
if st.button("Set Up") or 'func' not in st.session_state or 'points' not in st.session_state:
|
| 63 |
+
try:
|
| 64 |
+
func = make_function(func_input)
|
| 65 |
+
|
| 66 |
+
st.session_state.func = func
|
| 67 |
+
st.session_state.points = [start_point]
|
| 68 |
+
st.session_state.step = 0
|
| 69 |
+
st.success("Function Set Up Successfully with PyTorch!")
|
| 70 |
+
except Exception as e:
|
| 71 |
+
st.error(f"Error setting up function: {e}")
|
| 72 |
+
|
| 73 |
+
# ------------------------ ITERATION STEP ------------------------
|
| 74 |
+
def gradient_step(x_val, func, lr):
|
| 75 |
+
x = torch.tensor([x_val], dtype=torch.float32, requires_grad=True)
|
| 76 |
+
y = func(x)
|
| 77 |
+
y.backward()
|
| 78 |
+
grad = x.grad.item()
|
| 79 |
+
new_x = x_val - lr * grad
|
| 80 |
+
return new_x, grad
|
| 81 |
+
|
| 82 |
+
if 'func' in st.session_state:
|
| 83 |
+
if st.button("Next Iteration"):
|
| 84 |
+
try:
|
| 85 |
+
x_old = float(st.session_state.points[-1])
|
| 86 |
+
x_new, grad_val = gradient_step(x_old, st.session_state.func, learning_rate)
|
| 87 |
+
st.session_state.points.append(x_new)
|
| 88 |
+
st.session_state.step += 1
|
| 89 |
+
st.success(f"Iteration {st.session_state.step} Complete! (grad={grad_val:.6f})")
|
| 90 |
+
except Exception as e:
|
| 91 |
+
st.error(f"Error in iteration: {e}")
|
| 92 |
+
|
| 93 |
+
if st.button("Run Iterations"):
|
| 94 |
+
try:
|
| 95 |
+
for i in range(num_iterations):
|
| 96 |
+
x_old = float(st.session_state.points[-1])
|
| 97 |
+
x_new, grad_val = gradient_step(x_old, st.session_state.func, learning_rate)
|
| 98 |
+
st.session_state.points.append(x_new)
|
| 99 |
+
st.session_state.step += 1
|
| 100 |
+
st.success(f"Ran {st.session_state.step} Iterations in total")
|
| 101 |
+
except Exception as e:
|
| 102 |
+
st.error(f"Error in multiple iterations: {e}")
|
| 103 |
+
|
| 104 |
+
# ------------------------ PLOTTING ------------------------
|
| 105 |
+
if 'func' in st.session_state and len(st.session_state.points) > 0:
|
| 106 |
+
try:
|
| 107 |
+
x_val = np.linspace(-10, 10, 500)
|
| 108 |
+
x_torch = torch.tensor(x_val, dtype=torch.float32)
|
| 109 |
+
y_val = st.session_state.func(x_torch).detach().numpy()
|
| 110 |
+
|
| 111 |
+
iter_points = np.array(st.session_state.points)
|
| 112 |
+
iter_torch = torch.tensor(iter_points, dtype=torch.float32)
|
| 113 |
+
iter_y = st.session_state.func(iter_torch).detach().numpy()
|
| 114 |
+
|
| 115 |
+
trace1 = go.Scatter(x=x_val, y=y_val, mode="lines", name="Function", line=dict(color="blue"))
|
| 116 |
+
trace2 = go.Scatter(x=iter_points, y=iter_y, mode="markers+lines",
|
| 117 |
+
name="Gradient Descent Path", marker=dict(color="red"))
|
| 118 |
+
trace3 = go.Scatter(x=[iter_points[-1]], y=[iter_y[-1]], mode='markers+text',
|
| 119 |
+
marker=dict(color='green', size=15),
|
| 120 |
+
text=[f"{iter_points[-1]:.6f}"], textposition="top center",
|
| 121 |
+
name="Current Point")
|
| 122 |
+
|
| 123 |
+
layout = go.Layout(
|
| 124 |
+
title=f"Iteration {st.session_state.step}",
|
| 125 |
+
xaxis=dict(title="x - axis"),
|
| 126 |
+
yaxis=dict(title="y - axis"),
|
| 127 |
+
width=1000,
|
| 128 |
+
height=600
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
fig = go.Figure(data=[trace1, trace2, trace3], layout=layout)
|
| 132 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 133 |
+
st.success(f"Current Point = {iter_points[-1]}")
|
| 134 |
+
except Exception as e:
|
| 135 |
+
st.error(f"Plot error: {e}")
|