To implement a gradient descent algorithm for the function ( f(x) = x^2 + a \cdot e^{b \cdot x} ), we need to compute its derivative, update the parameters iteratively, and visualize the optimization process. Let's proceed step-by-step:
-
Define the Function and its Derivative:
The function is ( f(x) = x^2 + a \cdot e^{b \cdot x} ).
Its derivative ( f'(x) ) is ( f'(x) = 2x + a \cdot b \cdot e^{b \cdot x} ).
-
Gradient Descent Algorithm:
We'll implement the gradient descent algorithm where we iteratively update ( x ) using the rule:
( x_{\text{new}} = x_{\text{old}} - \gamma \cdot f'(x_{\text{old}}) )
Here, (\gamma) is the learning rate.
-
Visualization:
We'll use matplotlib to visualize the function and show the path taken by the gradient descent algorithm.
Here's a complete implementation:
import numpy as np
import matplotlib.pyplot as plt
# Define the function f(x) = x^2 + a * e^(b * x)
def f(x, a, b):
return x**2 + a * np.exp(b * x)
# Define the derivative of the function
def f_prime(x, a, b):
return 2 * x + a * b * np.exp(b * x)
# Gradient descent algorithm
def gradient_descent(starting_x, learning_rate, num_iterations, a, b):
x = starting_x
# To record the history of x and f(x) for visualization
x_history = [x]
f_history = [f(x, a, b)]
for _ in range(num_iterations):
gradient = f_prime(x, a, b)
x = x - learning_rate * gradient
x_history.append(x)
f_history.append(f(x, a, b))
return x, x_history, f_history
# Parameters for the function
a = 1
b = 1
# Gradient descent parameters
starting_x = -3 # Start from some point
learning_rate = 0.1
num_iterations = 50
# Perform gradient descent
final_x, x_history, f_history = gradient_descent(starting_x, learning_rate, num_iterations, a, b)
# Visualization
x_vals = np.linspace(-5, 5, 400)
y_vals = f(x_vals, a, b)
plt.figure(figsize=(10, 6))
plt.plot(x_vals, y_vals, label='f(x) = x^2 + a e^(b x)', color='k')
plt.scatter(x_history, f_history, color='red', label='Gradient Descent Path', zorder=5)
plt.plot(x_history, f_history, color='red', linestyle='--', alpha=0.4)
plt.title('Gradient Descent Optimization')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.show()
Explanation:
- Function: We define
f(x, a, b) and its derivative f_prime(x, a, b).
- Gradient Descent: The
gradient_descent function updates ( x ) iteratively using the derivative.
- Visualization: The function values across iterations are recorded and plotted over the function curve.
This implementation visualizes the descent path taken toward a minimum, illustrating how the algorithm navigates the function landscape. Adjust the starting point, learning rate, and number of iterations as needed.