Skip to content

Numerical Optimization

This module implements numerical optimization techniques, such as Gradient Descent, for finding local minima of one- and multidimensional functions.

gradient_descent(f, grad_f, x0, learning_rate, max_iter, plotchoose, tol=1e-06)

Finds a local minimum of a function using gradient descent.

Parameters:

Name Type Description Default
f

Objective function f(x).

required
grad_f

Gradient (derivative) of the function grad_f(x).

required
x0

Initial guess (float for 1D or list/ndarray for nD).

required
learning_rate

Step size (alpha).

required
max_iter

Maximum number of iterations.

required
plotchoose

Boolean to plot the descent (in the 1D case).

required
tol

Stopping criterion (norm of the gradient).

1e-06

Returns:

Name Type Description
tuple

(x_min, history) - Found minimum and history of steps.

Source code in openum/opti.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def gradient_descent(f, grad_f, x0, learning_rate, max_iter, plotchoose, tol=1e-6):
    """
    Finds a local minimum of a function using gradient descent.

    Args:
        f: Objective function f(x).
        grad_f: Gradient (derivative) of the function grad_f(x).
        x0: Initial guess (float for 1D or list/ndarray for nD).
        learning_rate: Step size (alpha).
        max_iter: Maximum number of iterations.
        plotchoose: Boolean to plot the descent (in the 1D case).
        tol: Stopping criterion (norm of the gradient).

    Returns:
        tuple: (x_min, history) - Found minimum and history of steps.
    """
    x = np.array(x0, dtype=float)
    history = [x.copy()]

    for i in range(max_iter):
        grad = np.array(grad_f(x), dtype=float)

        # Stopping criterion: gradient is close enough to 0
        if np.linalg.norm(grad) < tol:
            break

        # Actual update step
        x = x - learning_rate * grad
        history.append(x.copy())

    history = np.array(history)

    # Integrated plot for the 1D case
    if plotchoose and x.ndim == 0:
        _plot_1d_descent(f, history)

    return x, history