CoolFace
Apppublic

Mpavan45/Gradient_Descent

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py193 linesDownload Raw Back to root
1import streamlit as st2import numpy as np3import plotly.graph_objects as go4 5# Title of the app6st.set_page_config(page_title="Interactive Gradient Descent Visualizer", layout="wide")7st.markdown("<h1 style='text-align: center; color: #FFD700;'> ๐ŸŒŸ Gradient Descent Visualizer</h1>", unsafe_allow_html=True)8 9# Custom CSS for background and button color10st.markdown("""11    <style>12        body {13            background-color: #121212;  /* Dark gray background for modern look */14            color: white;  /* White text for contrast */15        }16        .stButton>button {17            background: linear-gradient(45deg, #FF7F50, #FF4500);  /* Coral to OrangeRed gradient */18            color: white;  /* White button text */19            border: none;20            border-radius: 8px;21            padding: 10px 20px;22            font-size: 16px;23            font-weight: bold;24            transition: transform 0.2s ease, box-shadow 0.3s ease, filter 0.3s ease; /* Smooth hover effects */25        }26        .stButton>button:hover {27            transform: scale(1.1);  /* Slight zoom effect on hover */28            box-shadow: 0 0 20px 10px rgba(255, 69, 0, 0.8);  /* Glowing shadow effect */29            background: linear-gradient(45deg, #FF4500, #FF7F50); /* Reverse gradient */30            filter: brightness(1.2);  /* Slightly brightens the button */31        }32        h1, h2, h3 {33            color: #00FFFF;  /* Aqua for headings */34        }35        .custom-text {36            color: #FFD700;  /* Gold for highlighted text */37            font-weight: bold;38        }39    </style>40""", unsafe_allow_html=True)41 42# Safe function evaluation43def evaluate_function(expression, x_value):44    """Safely evaluates the mathematical function."""45    allowed_names = {"x": x_value, "np": np}  # Allow only x and numpy46    return eval(expression, {"_builtins_": None}, allowed_names)47 48# Compute derivative using finite difference49def compute_derivative(expression, x_value, h=1e-5):50    """Numerically calculates the derivative at a given point."""51    return (evaluate_function(expression, x_value + h) - evaluate_function(expression, x_value - h)) / (2 * h)52 53# Tangent line calculation54def calculate_tangent(expression, x_value, x_range):55    """Generates the tangent line for a given point."""56    y_value = evaluate_function(expression, x_value)57    slope = compute_derivative(expression, x_value)58    return slope * (x_range - x_value) + y_value59 60# Reset state61def reset_session_state():62    """Resets the session state for a fresh start."""63    st.session_state.x_current = st.session_state.initial_point64    st.session_state.iter_count = 065    st.session_state.history = [66        (st.session_state.initial_point, evaluate_function(st.session_state.math_function, st.session_state.initial_point))67    ]68    st.session_state.current_index = 069 70# Initialize session state variables71if "x_current" not in st.session_state:72    st.session_state.x_current = 0.0  # Default starting point73if "iter_count" not in st.session_state:74    st.session_state.iter_count = 075if "history" not in st.session_state:76    st.session_state.history = [(0.0, evaluate_function("x**2 + x", 0.0))]  # Default function example77if "current_index" not in st.session_state:78    st.session_state.current_index = 079if "learning_rate" not in st.session_state:80    st.session_state.learning_rate = 0.181 82# Create two-column grid layout for the left side (more space for the right graph)83left_col, right_col = st.columns([1, 2])  # 1 for left, 2 for right grid proportion84 85# Left side content (Function Input and Gradient Descent Parameters)86with left_col:87    st.markdown("<h3 style='color: #7FFF00;'>Input Your Function</h3>", unsafe_allow_html=True)88    function_input = st.text_input(89        "Enter Function:`Ex:'x**2`,`np.sin(x)`", 90        "x**2 + x", 91        key="math_function", 92        on_change=reset_session_state93    )94    st.markdown("<h3 style='color: #FF69B4;'>Set Parameters</h3>", unsafe_allow_html=True)95    initial_point = st.number_input(96        "Initial Value of x", 97        value=4.0, 98        step=0.1, 99        format="%.2f", 100        key="initial_point", 101        on_change=reset_session_state102    )103    st.number_input(104        "Learning Rate", 105        value=st.session_state.learning_rate, 106        step=0.01, 107        format="%.2f", 108        key="learning_rate"109    )  # Updates session state directly without reset110    111    st.markdown("<h3 style='color: #1E90FF;'>Controls</h3>", unsafe_allow_html=True)112    113    if st.button("๐Ÿ”„ Run Descent Step", type="primary"):114        try:115            gradient = compute_derivative(function_input, st.session_state.x_current)116            st.session_state.x_current -= st.session_state.learning_rate * gradient117            st.session_state.iter_count += 1118            st.session_state.history.append(119                (st.session_state.x_current, evaluate_function(function_input, st.session_state.x_current))120            )121            st.session_state.current_index = st.session_state.iter_count122        except Exception as e:123            st.error(f"Error: {str(e)}")124    if st.button("๐Ÿ”„ Reset"):125        reset_session_state()126 127# Right side content (Visualization and Iteration Details)128with right_col:129    st.markdown("<h3 style='color: #FF6347;'>Gradient Descent Visualization</h3>", unsafe_allow_html=True)130    131    # Display iteration details using buttons132    col1, col2, col3 = st.columns(3)133    with col1:134        if st.button("โฌ…๏ธ Previous Iteration") and st.session_state.current_index > 0:135            st.session_state.current_index -= 1136    with col2:137        st.markdown(f"**Iteration:** {st.session_state.current_index}", unsafe_allow_html=True)138    with col3:139        if st.button("โžก๏ธ Next Iteration") and st.session_state.current_index < st.session_state.iter_count:140            st.session_state.current_index += 1141    142    try:143        selected_x, selected_y = st.session_state.history[st.session_state.current_index]144        st.markdown(f"x Value: <span style='color: #FFD700;'>{selected_x:.4f}</span>", unsafe_allow_html=True)145        st.markdown(f"f(x): <span style='color: #FFD700;'>{selected_y:.4f}</span>", unsafe_allow_html=True)146    except IndexError:147        st.warning("No iteration data available. Please run a descent step first.")148    149    # Prepare data for visualization150    x_range = np.linspace(-10, 10, 500)  # Define range for x151    y_range = [evaluate_function(function_input, x) for x in x_range]152    153    # Plot function curve with orange color154    fig = go.Figure()155    fig.add_trace(go.Scatter(156        x=x_range, 157        y=y_range, 158        mode='lines', 159        name='Function', 160        line=dict(color='orange')  # Curve color set to orange161    ))162    163    # Add current point164    x_current, y_current = st.session_state.history[st.session_state.current_index]165    fig.add_trace(go.Scatter(166        x=[x_current], 167        y=[y_current], 168        mode='markers', 169        name='Current Point', 170        marker=dict(size=10, color='red')171    ))172    173    # Add tangent line174    tangent_y = calculate_tangent(function_input, x_current, x_range)175    fig.add_trace(go.Scatter(176        x=x_range, 177        y=tangent_y, 178        mode='lines', 179        name='Tangent Line', 180        line=dict(dash='dash', color='blue')  # Tangent line in blue181    ))182    183    # Layout adjustments184    fig.update_layout(185        title="Gradient Descent Progress",186        xaxis_title="x",187        yaxis_title="f(x)",188        template="plotly_white",189        height=600190    )191    192    st.plotly_chart(fig, use_container_width=True)193