Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import streamlit as st | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| from sympy import symbols, diff, lambdify, sympify, latex | |
| bu = False | |
| # Define symbol | |
| x = symbols('x') | |
| st.title("Gradient Descent Visualizer") | |
| st.header("Minimize your custom function using gradient descent") | |
| with st.sidebar: | |
| func_input = st.text_input("Enter a function in terms of x (e.g., x**2 - 4*x + 4):") | |
| learning_rate = st.number_input("Learning Rate (α)", step=0.1) | |
| start_point = st.number_input("Starting Point (x₀)") | |
| if st.button("Set"): | |
| st.session_state.x_val = start_point | |
| if st.button("Next Iteration"): | |
| bu = True | |
| # f_expr = sympify(func_input) | |
| #st.write(f_expr) | |
| if func_input: | |
| f_prime = diff(func_input, x) | |
| # Numerical functions | |
| f_lamb = lambdify(x, func_input) | |
| f_prime_lamb = lambdify(x, f_prime) | |
| if bu: | |
| current_x = st.session_state.x_val | |
| gradient = f_prime_lamb(current_x) | |
| next_x = current_x - learning_rate * gradient | |
| st.session_state.x_val = next_x | |
| x1 = np.linspace(-10, 10, 400) | |
| # x1 = np.linspace(st.session_state.x_val - 10, st.session_state.x_val + 10, 400) | |
| y1 = f_lamb(x1) | |
| fig, ax = plt.subplots() | |
| #ax.figure(figsize=(5,5)) | |
| ax.plot(x1, y1, label=r"$y = x^2$") | |
| ax.plot(next_x, f_lamb(next_x), 'ro',label="Current Point") | |
| ax.set_xlabel("x") | |
| ax.set_ylabel("y") | |
| ax.set_title(f"Plot of y = {func_input}") | |
| ax.legend() | |
| bu = False | |
| st.pyplot(fig) | |
| with st.sidebar: | |
| st.write(f"**Current x:** {current_x}") | |
| st.write(f"**Gradient (f') at x:** {gradient}") | |
| st.write(f"**Updated x:** {next_x}") | |