Certainly! To generate a Python code that plots the trajectories of different gradient optimization algorithms on a non-convex function, you can use the matplotlib library for plotting and the numpy library for numerical computations.
Below is a code example that demonstrates how to visualize the optimization paths of different algorithms on the Rosenbrock function, a well-known non-convex function, in 3D. The Rosenbrock function is defined as:
f(x, y) = (a - x)^2 + b * (y - x^2)^2
For this example, we will use a = 1 and b = 100, which are common choices for the Rosenbrock function.
To animate the optimization process, we will use the FuncAnimation class from matplotlib.animation. The code will include simple gradient descent and momentum-based gradient descent as examples of gradient optimization algorithms.
Before running the code, make sure you have the necessary libraries installed:
pip install numpy matplotlib
Here's the full Python code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d import Axes3D
# Rosenbrock function
def rosenbrock(x, y, a=1, b=100):
return (a - x) ** 2 + b * (y - x ** 2) ** 2
# Gradient of the Rosenbrock function
def rosenbrock_grad(x, y, a=1, b=100):
grad_x = -2 * (a - x) - 4 * b * x * (y - x ** 2)
grad_y = 2 * b * (y - x ** 2)
return np.array([grad_x, grad_y])
# Gradient descent algorithm
def gradient_descent(grad, start, learn_rate, n_iter=50, tol=1e-6):
path = [start]
x = start
for i in range(n_iter):
gradient = grad(x[0], x[1])
if np.linalg.norm(gradient) < tol:
break
x = x - learn_rate * gradient
path.append(x)
return np.array(path)
# Momentum-based gradient descent algorithm
def gradient_descent_momentum(grad, start, learn_rate, momentum, n_iter=50, tol=1e-6):
path = [start]
x = start
v = np.zeros_like(start)
for i in range(n_iter):
gradient = grad(x[0], x[1])
if np.linalg.norm(gradient) < tol:
break
v = momentum * v - learn_rate * gradient
x = x + v
path.append(x)
return np.array(path)
# Parameters
start_point = np.array([-2, 2]) # Starting point for the optimization
learning_rate = 0.001 # Learning rate
momentum = 0.9 # Momentum term
n_iter = 100 # Number of iterations
# Calculate paths
path_gd = gradient_descent(rosenbrock_grad, start_point, learning_rate, n_iter)
path_gdm = gradient_descent_momentum(rosenbrock_grad, start_point, learning_rate, momentum, n_iter)
# Plotting
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
# Create grid and compute function values
x = np.linspace(-2, 2, 400)
y = np.linspace(-1, 3, 400)
x, y = np.meshgrid(x, y)
z = rosenbrock(x, y)
# Plot the surface
ax.plot_surface(x, y, z, rstride=10, cstride=10, cmap='viridis', alpha=0.8, edgecolor='none')
# Plot optimization paths
line_gd, = ax.plot([], [], [], 'r-', label='Gradient Descent', lw=2)
line_gdm, = ax.plot([], [], [], 'b-', label='Momentum GD', lw=2)
point_gd, = ax.plot([], [], [], 'ro')
point_gdm, = ax.plot([], [], [], 'bo')
# Initialization function for the animation
def init():
line_gd.set_data([], [])
line_gd.set_3d_properties([])
line_gdm.set_data([], [])
line_gdm.set_3d_properties([])
point_gd.set_data([], [])
point_gd.set_3d_properties([])
point_gdm.set_data([], [])
point_gdm.set_3d_properties([])
return line_gd, line_gdm, point_gd, point_gdm
# Animation update function
def update(i):
line_gd.set_data(path_gd[:i