mahesh1209 commited on
Commit
82e2823
·
verified ·
1 Parent(s): 8370645

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -0
app.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Convex vs Non-Convex Optimization Demo (Colab-ready)
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+
5
+ # Define convex and non-convex functions
6
+ def convex_fn(x): return x**2
7
+ def nonconvex_fn(x): return x**4 - 3*x**3 + 2
8
+
9
+ # Gradient functions
10
+ def grad_convex(x): return 2*x
11
+ def grad_nonconvex(x): return 4*x**3 - 9*x**2
12
+
13
+ # Gradient descent
14
+ def gradient_descent(f, grad_f, x0, lr=0.01, steps=50):
15
+ x_vals, y_vals = [x0], [f(x0)]
16
+ x = x0
17
+ for _ in range(steps):
18
+ x -= lr * grad_f(x)
19
+ x_vals.append(x)
20
+ y_vals.append(f(x))
21
+ return x_vals, y_vals
22
+
23
+ # Run optimization
24
+ x_c, y_c = gradient_descent(convex_fn, grad_convex, x0=5)
25
+ x_nc, y_nc = gradient_descent(nonconvex_fn, grad_nonconvex, x0=2)
26
+
27
+ # Plotting
28
+ fig, axs = plt.subplots(1, 2, figsize=(12, 4))
29
+ x = np.linspace(-1, 6, 100)
30
+
31
+ axs[0].plot(x, convex_fn(x), label='Convex Function')
32
+ axs[0].scatter(x_c, y_c, c='red', s=10, label='Gradient Descent Path')
33
+ axs[0].set_title('Convex Optimization')
34
+ axs[0].legend()
35
+
36
+ axs[1].plot(x, nonconvex_fn(x), label='Non-Convex Function')
37
+ axs[1].scatter(x_nc, y_nc, c='purple', s=10, label='Gradient Descent Path')
38
+ axs[1].set_title('Non-Convex Optimization')
39
+ axs[1].legend()
40
+
41
+ plt.tight_layout()
42
+ plt.show()