Mpavan45 commited on
Commit
bcde049
·
verified ·
1 Parent(s): 715a2b4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import seaborn as sns
3
+ import matplotlib.pyplot as plt
4
+ import streamlit as st
5
+
6
+ # Function definition
7
+ def loss_function(x):
8
+ return x**2
9
+
10
+ # Gradient of the loss function
11
+ def gradient(x):
12
+ return 2 * x
13
+
14
+ # Gradient descent algorithm
15
+ def gradient_descent(starting_point, learning_rate, iterations):
16
+ x_values = [starting_point]
17
+ for _ in range(iterations):
18
+ gradient_value = gradient(x_values[-1])
19
+ new_x = x_values[-1] - learning_rate * gradient_value
20
+ x_values.append(new_x)
21
+ return x_values
22
+
23
+ # Streamlit layout
24
+ st.title("Gradient Descent Visualization using Seaborn")
25
+
26
+ # Sidebar inputs
27
+ st.sidebar.header("Parameters")
28
+ starting_point = st.sidebar.slider("Starting Point", -10.0, 10.0, 5.0, 0.1)
29
+ learning_rate = st.sidebar.slider("Learning Rate", 0.01, 1.0, 0.1, 0.01)
30
+ iterations = st.sidebar.slider("Number of Iterations", 1, 50, 10, 1)
31
+
32
+ # Perform gradient descent
33
+ x_values = gradient_descent(starting_point, learning_rate, iterations)
34
+ y_values = [loss_function(x) for x in x_values]
35
+
36
+ # Generate plot using Seaborn
37
+ sns.set(style="whitegrid")
38
+ fig, ax = plt.subplots(figsize=(8, 5))
39
+ x_range = np.linspace(-10, 10, 500)
40
+ y_range = loss_function(x_range)
41
+
42
+ # Plot the loss function
43
+ sns.lineplot(x=x_range, y=y_range, ax=ax, label="Loss Function", color="blue")
44
+ # Plot gradient descent steps
45
+ sns.scatterplot(x=x_values, y=y_values, ax=ax, color="red", label="Gradient Steps", zorder=5)
46
+ sns.lineplot(x=x_values, y=y_values, ax=ax, color="orange", linestyle="--", label="Path")
47
+
48
+ # Annotate points
49
+ for i, (x, y) in enumerate(zip(x_values, y_values)):
50
+ ax.text(x, y, f"{i}", fontsize=8, ha="right")
51
+
52
+ ax.set_title("Gradient Descent")
53
+ ax.set_xlabel("x")
54
+ ax.set_ylabel("Loss")
55
+ ax.legend()
56
+
57
+ # Display in Streamlit
58
+ st.pyplot(fig)
59
+
60
+ # Display final results
61
+ st.write("### Gradient Descent Results")
62
+ st.write(f"**Starting Point:** {starting_point}")
63
+ st.write(f"**Learning Rate:** {learning_rate}")
64
+ st.write(f"**Number of Iterations:** {iterations}")
65
+ st.write(f"**Final x Value:** {x_values[-1]:.4f}")
66
+ st.write(f"**Final Loss Value:** {loss_function(x_values[-1]):.4f}")