Create a function in Python to optimize a cost function using gradient descent. A cost…
- User
Create a function in Python to optimize a cost function using gradient descent. A cost function of the form f(x) = x^2 + 10.
Assistant
Create a function in Python to optimize a cost function using gradient descent. A cost function of the form f(x) = x^2 + 10.
1. Analyze the Mathematics:
2. Design the Python Code:
gradient_descent should take parameters:
starting_x: Initial guess.learning_rate: Step size ().iterations: Max number of steps to prevent infinite loops.tolerance: (Optional) Stop if the change is negligible.3. Step-by-Step Implementation Plan:
func(x): returns .func_derivative(x): returns .gradient_descent(...):
x.n_iterations.grad at current x.x: x = x - learning_rate * grad.x and minimum cost.4. Refinement:
Here is the step-by-step reasoning and the Python solution to optimize the cost function using gradient descent.
To write the code, we first need to define the derivatives (gradients) that drive the algorithm.
Below is a clean, commented Python script implementing this logic.
def cost_function(x):
"""
The function we want to minimize: f(x) = x^2 + 10
"""
return x**2 + 10
def gradient(x):
"""
The derivative of the cost function: f'(x) = 2x
This represents the slope at point x.
"""
return 2 * x
def gradient_descent(start_x, learning_rate, n_iterations, tolerance=1e-6):
"""
Performs gradient descent optimization.
Args:
- start_x: The initial guess for x.
- learning_rate: The step size (alpha).
- n_iterations: Maximum number of steps to take.
- tolerance: Stop if the step size is smaller than this.
Returns:
- x: The optimized value of x.
- history: A list of x values during the process (for visualization).
"""
x = start_x
history = [x]
print(f"Starting at x = {x}")
for i in range(n_iterations):
# 1. Calculate the slope (gradient) at the current point
grad = gradient(x)
# 2. Calculate the new position (step)
# We subtract because we want to move against the gradient (downhill)
step = learning_rate * grad
new_x = x - step
# Store history
hi