|
| 1 | +"""AdaMax Optimizer. |
| 2 | +
|
| 3 | +This module implements the AdaMax optimization algorithm. AdaMax is a variant of Adam |
| 4 | +that uses the infinity norm instead of the L2 norm for the second moment estimate. |
| 5 | +This makes it less sensitive to outliers in gradients and can be more stable in some cases. |
| 6 | +
|
| 7 | +AdaMax performs the following update rule: |
| 8 | + m = beta1 * m + (1 - beta1) * gradient |
| 9 | + u = max(beta2 * u, |gradient|) |
| 10 | + x = x - (learning_rate / (1 - beta1^t)) * (m / u) |
| 11 | +
|
| 12 | +where: |
| 13 | + - x: current solution |
| 14 | + - m: first moment estimate (exponential moving average of gradients) |
| 15 | + - u: second moment estimate (exponential moving average of infinity norm of gradients) |
| 16 | + - learning_rate: step size for parameter updates |
| 17 | + - beta1, beta2: exponential decay rates for moment estimates |
| 18 | + - t: time step |
| 19 | +
|
| 20 | +Example: |
| 21 | + optimizer = AdaMax(func=objective_function, learning_rate=0.002, beta1=0.9, beta2=0.999, |
| 22 | + lower_bound=-5, upper_bound=5, dim=2) |
| 23 | + best_solution, best_fitness = optimizer.search() |
| 24 | +
|
| 25 | +Attributes: |
| 26 | + func (Callable): The objective function to optimize. |
| 27 | + learning_rate (float): The learning rate for the optimization. |
| 28 | + beta1 (float): Exponential decay rate for first moment estimates. |
| 29 | + beta2 (float): Exponential decay rate for second moment estimates. |
| 30 | + epsilon (float): Small constant for numerical stability. |
| 31 | +
|
| 32 | +Methods: |
| 33 | + search(): Perform the AdaMax optimization. |
| 34 | +""" |
| 35 | + |
| 36 | +from __future__ import annotations |
| 37 | + |
| 38 | +from typing import TYPE_CHECKING |
| 39 | + |
| 40 | +import numpy as np |
| 41 | + |
| 42 | +from scipy.optimize import approx_fprime |
| 43 | + |
| 44 | +from opt.abstract_optimizer import AbstractOptimizer |
| 45 | +from opt.benchmark.functions import shifted_ackley |
| 46 | + |
| 47 | + |
| 48 | +if TYPE_CHECKING: |
| 49 | + from collections.abc import Callable |
| 50 | + |
| 51 | + from numpy import ndarray |
| 52 | + |
| 53 | + |
| 54 | +class AdaMax(AbstractOptimizer): |
| 55 | + """AdaMax optimizer implementation. |
| 56 | +
|
| 57 | + Args: |
| 58 | + func (Callable[[ndarray], float]): The objective function to be optimized. |
| 59 | + lower_bound (float): The lower bound of the search space. |
| 60 | + upper_bound (float): The upper bound of the search space. |
| 61 | + dim (int): The dimensionality of the search space. |
| 62 | + max_iter (int, optional): The maximum number of iterations. Defaults to 1000. |
| 63 | + learning_rate (float, optional): The learning rate. Defaults to 0.002. |
| 64 | + beta1 (float, optional): Exponential decay rate for first moment estimates. Defaults to 0.9. |
| 65 | + beta2 (float, optional): Exponential decay rate for second moment estimates. Defaults to 0.999. |
| 66 | + epsilon (float, optional): Small constant for numerical stability. Defaults to 1e-8. |
| 67 | + seed (int | None, optional): The seed value for random number generation. Defaults to None. |
| 68 | + """ |
| 69 | + |
| 70 | + def __init__( |
| 71 | + self, |
| 72 | + func: Callable[[ndarray], float], |
| 73 | + lower_bound: float, |
| 74 | + upper_bound: float, |
| 75 | + dim: int, |
| 76 | + max_iter: int = 1000, |
| 77 | + learning_rate: float = 0.002, |
| 78 | + beta1: float = 0.9, |
| 79 | + beta2: float = 0.999, |
| 80 | + epsilon: float = 1e-8, |
| 81 | + seed: int | None = None, |
| 82 | + ) -> None: |
| 83 | + """Initialize the AdaMax optimizer.""" |
| 84 | + super().__init__( |
| 85 | + func=func, |
| 86 | + lower_bound=lower_bound, |
| 87 | + upper_bound=upper_bound, |
| 88 | + dim=dim, |
| 89 | + max_iter=max_iter, |
| 90 | + seed=seed, |
| 91 | + ) |
| 92 | + self.learning_rate = learning_rate |
| 93 | + self.beta1 = beta1 |
| 94 | + self.beta2 = beta2 |
| 95 | + self.epsilon = epsilon |
| 96 | + |
| 97 | + def search(self) -> tuple[np.ndarray, float]: |
| 98 | + """Perform the AdaMax optimization search. |
| 99 | +
|
| 100 | + Returns: |
| 101 | + tuple[np.ndarray, float]: A tuple containing the best solution found and its fitness value. |
| 102 | + """ |
| 103 | + # Initialize solution randomly |
| 104 | + best_solution = np.random.default_rng(self.seed).uniform( |
| 105 | + self.lower_bound, self.upper_bound, self.dim |
| 106 | + ) |
| 107 | + best_fitness = self.func(best_solution) |
| 108 | + |
| 109 | + current_solution = best_solution.copy() |
| 110 | + m = np.zeros(self.dim) # First moment estimate |
| 111 | + u = np.zeros(self.dim) # Infinity norm-based second moment estimate |
| 112 | + |
| 113 | + for t in range(1, self.max_iter + 1): |
| 114 | + # Compute gradient at current position |
| 115 | + gradient = self._compute_gradient(current_solution) |
| 116 | + |
| 117 | + # Update biased first moment estimate |
| 118 | + m = self.beta1 * m + (1 - self.beta1) * gradient |
| 119 | + |
| 120 | + # Update the exponentially weighted infinity norm |
| 121 | + u = np.maximum(self.beta2 * u, np.abs(gradient)) |
| 122 | + |
| 123 | + # Compute bias-corrected first moment estimate |
| 124 | + bias_correction = 1 - np.power(self.beta1, t) |
| 125 | + |
| 126 | + # Update solution using AdaMax rule |
| 127 | + current_solution = current_solution - ( |
| 128 | + self.learning_rate / bias_correction |
| 129 | + ) * (m / (u + self.epsilon)) |
| 130 | + |
| 131 | + # Apply bounds |
| 132 | + current_solution = np.clip( |
| 133 | + current_solution, self.lower_bound, self.upper_bound |
| 134 | + ) |
| 135 | + |
| 136 | + # Evaluate fitness |
| 137 | + current_fitness = self.func(current_solution) |
| 138 | + |
| 139 | + # Update best solution if improved |
| 140 | + if current_fitness < best_fitness: |
| 141 | + best_solution = current_solution.copy() |
| 142 | + best_fitness = current_fitness |
| 143 | + |
| 144 | + return best_solution, best_fitness |
| 145 | + |
| 146 | + def _compute_gradient(self, x: np.ndarray) -> np.ndarray: |
| 147 | + """Compute the gradient of the objective function at a given point. |
| 148 | +
|
| 149 | + Args: |
| 150 | + x (np.ndarray): The point at which to compute the gradient. |
| 151 | +
|
| 152 | + Returns: |
| 153 | + np.ndarray: The gradient vector. |
| 154 | + """ |
| 155 | + epsilon = np.sqrt(np.finfo(float).eps) |
| 156 | + return approx_fprime(x, self.func, epsilon) |
| 157 | + |
| 158 | + |
| 159 | +if __name__ == "__main__": |
| 160 | + optimizer = AdaMax( |
| 161 | + func=shifted_ackley, lower_bound=-2.768, upper_bound=+2.768, dim=2 |
| 162 | + ) |
| 163 | + best_solution, best_fitness = optimizer.search() |
| 164 | + print(f"Best solution: {best_solution}") |
| 165 | + print(f"Best fitness: {best_fitness}") |
0 commit comments