useful-optimizer 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. useful_optimizer-0.1.1/LICENSE +21 -0
  2. useful_optimizer-0.1.1/PKG-INFO +163 -0
  3. useful_optimizer-0.1.1/README.md +144 -0
  4. useful_optimizer-0.1.1/opt/__init__.py +6 -0
  5. useful_optimizer-0.1.1/opt/abstract_optimizer.py +74 -0
  6. useful_optimizer-0.1.1/opt/adadelta.py +148 -0
  7. useful_optimizer-0.1.1/opt/adagrad.py +111 -0
  8. useful_optimizer-0.1.1/opt/adaptive_moment_estimation.py +140 -0
  9. useful_optimizer-0.1.1/opt/ant_colony.py +194 -0
  10. useful_optimizer-0.1.1/opt/artificial_fish_swarm_algorithm.py +189 -0
  11. useful_optimizer-0.1.1/opt/augmented_lagrangian_method.py +177 -0
  12. useful_optimizer-0.1.1/opt/bat_algorithm.py +191 -0
  13. useful_optimizer-0.1.1/opt/bee_algorithm.py +166 -0
  14. useful_optimizer-0.1.1/opt/benchmark/__init__.py +6 -0
  15. useful_optimizer-0.1.1/opt/benchmark/functions.py +333 -0
  16. useful_optimizer-0.1.1/opt/cat_swarm_optimization.py +188 -0
  17. useful_optimizer-0.1.1/opt/cma_es.py +180 -0
  18. useful_optimizer-0.1.1/opt/colliding_bodies_optimization.py +107 -0
  19. useful_optimizer-0.1.1/opt/cross_entropy_method.py +126 -0
  20. useful_optimizer-0.1.1/opt/cuckoo_search.py +142 -0
  21. useful_optimizer-0.1.1/opt/cultural_algorithm.py +168 -0
  22. useful_optimizer-0.1.1/opt/differential_evolution.py +150 -0
  23. useful_optimizer-0.1.1/opt/eagle_strategy.py +113 -0
  24. useful_optimizer-0.1.1/opt/estimation_of_distribution_algorithm.py +164 -0
  25. useful_optimizer-0.1.1/opt/firefly_algorithm.py +144 -0
  26. useful_optimizer-0.1.1/opt/genetic_algorithm.py +192 -0
  27. useful_optimizer-0.1.1/opt/glowworm_swarm_optimization.py +204 -0
  28. useful_optimizer-0.1.1/opt/grey_wolf_optimizer.py +127 -0
  29. useful_optimizer-0.1.1/opt/harmony_search.py +172 -0
  30. useful_optimizer-0.1.1/opt/hill_climbing.py +140 -0
  31. useful_optimizer-0.1.1/opt/imperialist_competitive_algorithm.py +198 -0
  32. useful_optimizer-0.1.1/opt/linear_discriminant_analysis.py +201 -0
  33. useful_optimizer-0.1.1/opt/particle_filter.py +151 -0
  34. useful_optimizer-0.1.1/opt/particle_swarm.py +170 -0
  35. useful_optimizer-0.1.1/opt/parzen_tree_stimator.py +190 -0
  36. useful_optimizer-0.1.1/opt/shuffled_frog_leaping_algorithm.py +151 -0
  37. useful_optimizer-0.1.1/opt/simulated_annealing.py +155 -0
  38. useful_optimizer-0.1.1/opt/sine_cosine_algorithm.py +206 -0
  39. useful_optimizer-0.1.1/opt/squirrel_search.py +113 -0
  40. useful_optimizer-0.1.1/opt/stochastic_diffusion_search.py +154 -0
  41. useful_optimizer-0.1.1/opt/stochastic_fractal_search.py +178 -0
  42. useful_optimizer-0.1.1/opt/successive_linear_programming.py +112 -0
  43. useful_optimizer-0.1.1/opt/tabu_search.py +192 -0
  44. useful_optimizer-0.1.1/opt/variable_depth_search.py +138 -0
  45. useful_optimizer-0.1.1/opt/variable_neighbourhood_search.py +142 -0
  46. useful_optimizer-0.1.1/opt/very_large_scale_neighborhood_search.py +140 -0
  47. useful_optimizer-0.1.1/opt/whale_optimization_algorithm.py +144 -0
  48. useful_optimizer-0.1.1/pyproject.toml +147 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Anselm Hahn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.1
2
+ Name: useful-optimizer
3
+ Version: 0.1.1
4
+ Summary: A dedicated set of optimization algorithms for numeric problems.
5
+ License: MIT
6
+ Author: Anselm Hahn
7
+ Author-email: Anselm.Hahn@gmail.com
8
+ Requires-Python: >=3.10,<3.13
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: numpy (>=1.26.4,<2.0.0)
15
+ Requires-Dist: scikit-learn (>=1.5.1,<2.0.0)
16
+ Requires-Dist: scipy (>=1.12.0,<2.0.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Useful Optimizer
20
+
21
+ Useful Optimizer is a dedicated set of optimization algorithms for numeric problems. It's designed to provide a comprehensive collection of optimization techniques that can be easily used and integrated into any project.
22
+
23
+ ## Version
24
+
25
+ The current version of Useful Optimizer is 0.1.0.
26
+
27
+ ## Features
28
+
29
+ - A wide range of optimization algorithms.
30
+ - Easy to use and integrate.
31
+ - Suitable for various numeric problems.
32
+ - Having fun to play with the algorithms
33
+
34
+ ## Installation
35
+
36
+ To install Useful Optimizer, you can use pip:
37
+
38
+ ```bash
39
+ pip install git+https://github.com/Anselmoo/useful-optimizer
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ Here's a basic example of how to use Useful Optimizer:
45
+
46
+ ```python
47
+ from opt.benchmark import CrossEntropyMethod
48
+ from opt.benchmark.functions import shifted_ackley
49
+
50
+ optimizer = CrossEntropyMethod(
51
+ func=shifted_ackley,
52
+ dim=2,
53
+ lower_bound=-12.768,
54
+ upper_bound=+12.768,
55
+ population_size=100,
56
+ max_iter=1000,
57
+ )
58
+ best_solution, best_fitness = optimizer.search()
59
+ print(f"Best solution: {best_solution}")
60
+ print(f"Best fitness: {best_fitness}")
61
+ ```
62
+
63
+ ## Current Implemented Optimizer
64
+
65
+ The current version of Useful Optimizer includes a wide range of optimization algorithms, each implemented as a separate module. Here's a brief overview of the implemented optimizers:
66
+
67
+ Sure, here's a brief description of each optimizer:
68
+
69
+ - **Adadelta, Adagrad, and Adaptive Moment Estimation**: These are gradient-based optimization algorithms commonly used in machine learning and deep learning.
70
+
71
+ - **Ant Colony Optimization**: This is a nature-inspired algorithm that mimics the behavior of ants to solve optimization problems.
72
+
73
+ - **Artificial Fish Swarm Algorithm**: This algorithm simulates the behavior of fish in nature to perform global optimization.
74
+
75
+ - **Augmented Lagrangian Method**: This is a method to solve constrained optimization problems. It combines the objective function and the constraints into a single function using Lagrange multipliers.
76
+
77
+ - **Bat Algorithm**: This is a metaheuristic optimization algorithm inspired by the echolocation behavior of microbats.
78
+
79
+ - **Bee Algorithm**: This is a population-based search algorithm inspired by the food foraging behavior of honey bee colonies.
80
+
81
+ - **Cat Swarm Optimization**: This algorithm is based on the behavior of cats and distinguishes between two forms of behavior in cats: seeking mode and tracing mode.
82
+
83
+ - **CMA-ES (Covariance Matrix Adaptation Evolution Strategy)**: This is an evolutionary algorithm for difficult non-linear non-convex optimization problems in continuous domain.
84
+
85
+ - **Colliding Bodies Optimization**: This is a physics-inspired optimization method, based on the collision and explosion of bodies.
86
+
87
+ - **Cross Entropy Method**: This is a Monte Carlo method for importance sampling and optimization.
88
+
89
+ - **Cuckoo Search**: This is a nature-inspired metaheuristic optimization algorithm, which is based on the obligate brood parasitism of some cuckoo species.
90
+
91
+ - **Cultural Algorithm**: This is a type of evolutionary algorithm that is based on the concept of culture, or shared information and knowledge.
92
+
93
+ - **Differential Evolution**: This is a population-based metaheuristic algorithm, which uses mechanisms inspired by biological evolution, such as reproduction, mutation, recombination, and selection.
94
+
95
+ - **Eagle Strategy**: This is a metaheuristic optimization algorithm inspired by the hunting behavior of eagles.
96
+
97
+ - **Estimation of Distribution Algorithm**: This is a stochastic optimization algorithm that uses a probabilistic model of candidate solutions.
98
+
99
+ - **Firefly Algorithm**: This is a nature-inspired metaheuristic optimization algorithm, based on the flashing behavior of fireflies.
100
+
101
+ - **Genetic Algorithm**: This is a search heuristic that is inspired by Charles Darwin’s theory of natural evolution.
102
+
103
+ - **Glowworm Swarm Optimization**: This is a nature-inspired optimization algorithm based on the behavior of glowworms.
104
+
105
+ - **Grey Wolf Optimizer**: This is a metaheuristic optimization algorithm inspired by grey wolves.
106
+
107
+ - **Harmony Search**: This is a music-inspired metaheuristic optimization algorithm.
108
+
109
+ - **Hessian Free Optimization**: This is a second-order optimization algorithm that uses information from the Hessian matrix to guide the search.
110
+
111
+ - **Hill Climbing**: This is a mathematical optimization technique which belongs to the family of local search.
112
+
113
+ - **Imperialist Competitive Algorithm**: This is a socio-politically motivated global search strategy, which is based on the imperialistic competition.
114
+
115
+ - **Linear Discriminant Analysis**: This is a method used in statistics, pattern recognition, and machine learning to find a linear combination of features that characterizes or separates two or more classes of objects or events.
116
+
117
+ - **Particle Filter**: This is a statistical filter technique used to estimate the state of a system where the state model and the measurements are both nonlinear.
118
+
119
+ - **Particle Swarm Optimization**: This is a computational method that optimizes a problem by iteratively trying to improve a candidate solution with regard to a given measure of quality, mimicking the social behavior of bird flocking or fish schooling.
120
+
121
+ - **Parzen Tree Estimator**: This is a non-parametric method to estimate the density function of random variables.
122
+
123
+ - **Shuffled Frog Leaping Algorithm**: This is a metaheuristic optimization algorithm inspired by the memetic evolution of a group of frogs when searching for food.
124
+
125
+ - **Simulated Annealing**: This is a probabilistic technique for approximating the global optimum of a given function, mimicking the process of heating a material and then slowly lowering the temperature to decrease defects, thus minimizing the system energy.
126
+
127
+ - **Sine Cosine Algorithm**: This is a new population-based meta-heuristic algorithm, inspired by the mathematical sine and cosine functions.
128
+
129
+ - **Squirrel Search Algorithm**: This is a new nature-inspired metaheuristic optimization algorithm, inspired by the caching behavior of squirrels.
130
+
131
+ - **Stochastic Diffusion Search**: This is a population-based search algorithm, based on the behavior of ants when searching for food.
132
+
133
+ - **Stochastic Fractal Search**: This is a metaheuristic search algorithm inspired by the natural phenomenon of fractal shapes and Brownian motion.
134
+
135
+ - **Successive Linear Programming**: This is an optimization method for nonlinear optimization problems.
136
+
137
+ - **Tabu Search**: This is a metaheuristic search method employing local search methods used for mathematical optimization.
138
+
139
+ - **Variable Depth Search**: This is a search algorithm that explores the search space by variable-depth first search and backtracking.
140
+
141
+ - **Variable Neighbourhood Search**: This is a metaheuristic search method for discrete optimization problems.
142
+
143
+ - **Very Large Scale Neighborhood Search**: This is a search method that explores very large neighborhoods with an efficient algorithm.
144
+
145
+ - **Whale Optimization Algorithm**: This is a new bio-inspired optimization algorithm, which simulates the social behavior of humpback whales.
146
+
147
+ > [!NOTE]
148
+ > Please note that not all of these algorithms are suitable for all types of optimization problems. Some are better suited for continuous optimization problems, some for discrete optimization problems, and others for specific types of problems like quadratic programming or linear discriminant analysis.
149
+
150
+ ## Contributing
151
+
152
+ Contributions to Useful Optimizer are welcome! Please read the contributing guidelines before getting started.
153
+
154
+ ## [License](LICENSE)
155
+
156
+ ---
157
+
158
+ > [!WARNING]
159
+ > This project was generated with GitHub Copilot and may not be completely verified. Please use with caution and feel free to report any issues you encounter. Thank you!
160
+
161
+ > [!WARNING]
162
+ > Some parts still contain the _legacy_ `np.random.rand` call. See also: https://docs.astral.sh/ruff/rules/numpy-legacy-random/
163
+
@@ -0,0 +1,144 @@
1
+ # Useful Optimizer
2
+
3
+ Useful Optimizer is a dedicated set of optimization algorithms for numeric problems. It's designed to provide a comprehensive collection of optimization techniques that can be easily used and integrated into any project.
4
+
5
+ ## Version
6
+
7
+ The current version of Useful Optimizer is 0.1.0.
8
+
9
+ ## Features
10
+
11
+ - A wide range of optimization algorithms.
12
+ - Easy to use and integrate.
13
+ - Suitable for various numeric problems.
14
+ - Having fun to play with the algorithms
15
+
16
+ ## Installation
17
+
18
+ To install Useful Optimizer, you can use pip:
19
+
20
+ ```bash
21
+ pip install git+https://github.com/Anselmoo/useful-optimizer
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ Here's a basic example of how to use Useful Optimizer:
27
+
28
+ ```python
29
+ from opt.benchmark import CrossEntropyMethod
30
+ from opt.benchmark.functions import shifted_ackley
31
+
32
+ optimizer = CrossEntropyMethod(
33
+ func=shifted_ackley,
34
+ dim=2,
35
+ lower_bound=-12.768,
36
+ upper_bound=+12.768,
37
+ population_size=100,
38
+ max_iter=1000,
39
+ )
40
+ best_solution, best_fitness = optimizer.search()
41
+ print(f"Best solution: {best_solution}")
42
+ print(f"Best fitness: {best_fitness}")
43
+ ```
44
+
45
+ ## Current Implemented Optimizer
46
+
47
+ The current version of Useful Optimizer includes a wide range of optimization algorithms, each implemented as a separate module. Here's a brief overview of the implemented optimizers:
48
+
49
+ Sure, here's a brief description of each optimizer:
50
+
51
+ - **Adadelta, Adagrad, and Adaptive Moment Estimation**: These are gradient-based optimization algorithms commonly used in machine learning and deep learning.
52
+
53
+ - **Ant Colony Optimization**: This is a nature-inspired algorithm that mimics the behavior of ants to solve optimization problems.
54
+
55
+ - **Artificial Fish Swarm Algorithm**: This algorithm simulates the behavior of fish in nature to perform global optimization.
56
+
57
+ - **Augmented Lagrangian Method**: This is a method to solve constrained optimization problems. It combines the objective function and the constraints into a single function using Lagrange multipliers.
58
+
59
+ - **Bat Algorithm**: This is a metaheuristic optimization algorithm inspired by the echolocation behavior of microbats.
60
+
61
+ - **Bee Algorithm**: This is a population-based search algorithm inspired by the food foraging behavior of honey bee colonies.
62
+
63
+ - **Cat Swarm Optimization**: This algorithm is based on the behavior of cats and distinguishes between two forms of behavior in cats: seeking mode and tracing mode.
64
+
65
+ - **CMA-ES (Covariance Matrix Adaptation Evolution Strategy)**: This is an evolutionary algorithm for difficult non-linear non-convex optimization problems in continuous domain.
66
+
67
+ - **Colliding Bodies Optimization**: This is a physics-inspired optimization method, based on the collision and explosion of bodies.
68
+
69
+ - **Cross Entropy Method**: This is a Monte Carlo method for importance sampling and optimization.
70
+
71
+ - **Cuckoo Search**: This is a nature-inspired metaheuristic optimization algorithm, which is based on the obligate brood parasitism of some cuckoo species.
72
+
73
+ - **Cultural Algorithm**: This is a type of evolutionary algorithm that is based on the concept of culture, or shared information and knowledge.
74
+
75
+ - **Differential Evolution**: This is a population-based metaheuristic algorithm, which uses mechanisms inspired by biological evolution, such as reproduction, mutation, recombination, and selection.
76
+
77
+ - **Eagle Strategy**: This is a metaheuristic optimization algorithm inspired by the hunting behavior of eagles.
78
+
79
+ - **Estimation of Distribution Algorithm**: This is a stochastic optimization algorithm that uses a probabilistic model of candidate solutions.
80
+
81
+ - **Firefly Algorithm**: This is a nature-inspired metaheuristic optimization algorithm, based on the flashing behavior of fireflies.
82
+
83
+ - **Genetic Algorithm**: This is a search heuristic that is inspired by Charles Darwin’s theory of natural evolution.
84
+
85
+ - **Glowworm Swarm Optimization**: This is a nature-inspired optimization algorithm based on the behavior of glowworms.
86
+
87
+ - **Grey Wolf Optimizer**: This is a metaheuristic optimization algorithm inspired by grey wolves.
88
+
89
+ - **Harmony Search**: This is a music-inspired metaheuristic optimization algorithm.
90
+
91
+ - **Hessian Free Optimization**: This is a second-order optimization algorithm that uses information from the Hessian matrix to guide the search.
92
+
93
+ - **Hill Climbing**: This is a mathematical optimization technique which belongs to the family of local search.
94
+
95
+ - **Imperialist Competitive Algorithm**: This is a socio-politically motivated global search strategy, which is based on the imperialistic competition.
96
+
97
+ - **Linear Discriminant Analysis**: This is a method used in statistics, pattern recognition, and machine learning to find a linear combination of features that characterizes or separates two or more classes of objects or events.
98
+
99
+ - **Particle Filter**: This is a statistical filter technique used to estimate the state of a system where the state model and the measurements are both nonlinear.
100
+
101
+ - **Particle Swarm Optimization**: This is a computational method that optimizes a problem by iteratively trying to improve a candidate solution with regard to a given measure of quality, mimicking the social behavior of bird flocking or fish schooling.
102
+
103
+ - **Parzen Tree Estimator**: This is a non-parametric method to estimate the density function of random variables.
104
+
105
+ - **Shuffled Frog Leaping Algorithm**: This is a metaheuristic optimization algorithm inspired by the memetic evolution of a group of frogs when searching for food.
106
+
107
+ - **Simulated Annealing**: This is a probabilistic technique for approximating the global optimum of a given function, mimicking the process of heating a material and then slowly lowering the temperature to decrease defects, thus minimizing the system energy.
108
+
109
+ - **Sine Cosine Algorithm**: This is a new population-based meta-heuristic algorithm, inspired by the mathematical sine and cosine functions.
110
+
111
+ - **Squirrel Search Algorithm**: This is a new nature-inspired metaheuristic optimization algorithm, inspired by the caching behavior of squirrels.
112
+
113
+ - **Stochastic Diffusion Search**: This is a population-based search algorithm, based on the behavior of ants when searching for food.
114
+
115
+ - **Stochastic Fractal Search**: This is a metaheuristic search algorithm inspired by the natural phenomenon of fractal shapes and Brownian motion.
116
+
117
+ - **Successive Linear Programming**: This is an optimization method for nonlinear optimization problems.
118
+
119
+ - **Tabu Search**: This is a metaheuristic search method employing local search methods used for mathematical optimization.
120
+
121
+ - **Variable Depth Search**: This is a search algorithm that explores the search space by variable-depth first search and backtracking.
122
+
123
+ - **Variable Neighbourhood Search**: This is a metaheuristic search method for discrete optimization problems.
124
+
125
+ - **Very Large Scale Neighborhood Search**: This is a search method that explores very large neighborhoods with an efficient algorithm.
126
+
127
+ - **Whale Optimization Algorithm**: This is a new bio-inspired optimization algorithm, which simulates the social behavior of humpback whales.
128
+
129
+ > [!NOTE]
130
+ > Please note that not all of these algorithms are suitable for all types of optimization problems. Some are better suited for continuous optimization problems, some for discrete optimization problems, and others for specific types of problems like quadratic programming or linear discriminant analysis.
131
+
132
+ ## Contributing
133
+
134
+ Contributions to Useful Optimizer are welcome! Please read the contributing guidelines before getting started.
135
+
136
+ ## [License](LICENSE)
137
+
138
+ ---
139
+
140
+ > [!WARNING]
141
+ > This project was generated with GitHub Copilot and may not be completely verified. Please use with caution and feel free to report any issues you encounter. Thank you!
142
+
143
+ > [!WARNING]
144
+ > Some parts still contain the _legacy_ `np.random.rand` call. See also: https://docs.astral.sh/ruff/rules/numpy-legacy-random/
@@ -0,0 +1,6 @@
1
+ """Useful optimizers, a set of optimization algorithms."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ __version__ = "0.1.1"
@@ -0,0 +1,74 @@
1
+ """This module defines an abstract base class for optimizers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC
6
+ from abc import abstractmethod
7
+ from typing import TYPE_CHECKING
8
+
9
+ import numpy as np
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Callable
14
+
15
+ from numpy import ndarray
16
+
17
+
18
+ class AbstractOptimizer(ABC):
19
+ """An abstract base class for optimizers.
20
+
21
+ Args:
22
+ func (Callable): The objective function to be optimized.
23
+ lower_bound (float): The lower bound of the search space.
24
+ upper_bound (float): The upper bound of the search space.
25
+ dim (int): The dimensionality of the search space.
26
+ max_iter (int, optional): The maximum number of iterations for the optimization process. Defaults to 1000.
27
+
28
+ Attributes:
29
+ func (Callable): The objective function to be optimized.
30
+ lower_bound (float): The lower bound of the search space.
31
+ upper_bound (float): The upper bound of the search space.
32
+ dim (int): The dimensionality of the search space.
33
+ max_iter (int): The maximum number of iterations for the optimization process.
34
+ seed (int): The seed for the random number generator.
35
+ population_size (int): The number of individuals in the population.
36
+
37
+
38
+ Methods:
39
+ search() -> Tuple[TBestSolution, TBestFitness]:
40
+ Perform the optimization search.
41
+
42
+ Returns:
43
+ Tuple containing the best solution found and its corresponding fitness value.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ func: Callable[[ndarray], float],
49
+ lower_bound: float,
50
+ upper_bound: float,
51
+ dim: int,
52
+ max_iter: int = 1000,
53
+ seed: int | None = None,
54
+ population_size: int = 100,
55
+ ) -> None:
56
+ """Initialize the optimizer."""
57
+ self.func = func
58
+ self.lower_bound = lower_bound
59
+ self.upper_bound = upper_bound
60
+ self.dim = dim
61
+ self.max_iter = max_iter
62
+ if seed is None:
63
+ self.seed = np.random.default_rng(42).integers(0, 2**32)
64
+ else:
65
+ self.seed = seed
66
+ self.population_size = population_size
67
+
68
+ @abstractmethod
69
+ def search(self) -> tuple[np.ndarray, float]:
70
+ """Perform the optimization search.
71
+
72
+ Returns:
73
+ Tuple containing the best solution found and its corresponding fitness value.
74
+ """
@@ -0,0 +1,148 @@
1
+ """AdaDelta Optimizer.
2
+
3
+ This module implements the AdaDelta optimizer, which is an extension of AdaGrad that
4
+ seeks to reduce its sensitivity to the learning rate hyperparameter.
5
+
6
+ AdaDelta is a gradient-based optimization algorithm that adapts the learning rate
7
+ for each of the parameters in the model. It is designed to converge faster than
8
+ AdaGrad by using a moving average of the squared gradient values to scale the learning rate.
9
+
10
+ The AdaDelta optimizer is defined by the following update rule:
11
+
12
+ Eg = rho * Eg + (1 - rho) * g^2
13
+ dx = -sqrt(Edx + eps) / sqrt(Eg + eps) * g
14
+ Edx = rho * Edx + (1 - rho) * dx^2
15
+ x = x + dx
16
+
17
+ where:
18
+ - x: current solution
19
+ - g: gradient of the objective function
20
+ - rho: decay rate
21
+ - eps: small constant to avoid dividing by zero
22
+ - Eg: moving average of squared gradient values
23
+ - Edx: moving average of squared updates
24
+
25
+ The algorithm iteratively updates the solution x by computing the gradient of the
26
+ objective function at x, scaling it by the moving average of the squared gradients,
27
+ and dividing it by the square root of the moving average of the squared updates.
28
+
29
+ The algorithm continues for a fixed number of iterations or until a specified
30
+ stopping criterion is met, returning the best solution found.
31
+
32
+ This module provides a simple example of how to use the AdaDelta optimizer to minimize
33
+ the Shifted Ackley's function in two dimensions.
34
+
35
+ Example:
36
+ $ python adadelta.py
37
+
38
+ Attributes:
39
+ rho (float): Decay rate for the moving average of squared gradients
40
+ eps (float): Small constant to avoid dividing by zero
41
+ Eg (np.ndarray): Moving average of squared gradient values
42
+ Edx (np.ndarray): Moving average of squared updates
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ from typing import TYPE_CHECKING
48
+
49
+ import numpy as np
50
+
51
+ from scipy.optimize import approx_fprime
52
+
53
+ from opt.abstract_optimizer import AbstractOptimizer
54
+ from opt.benchmark.functions import shifted_ackley
55
+
56
+
57
+ if TYPE_CHECKING:
58
+ from collections.abc import Callable
59
+
60
+ from numpy import ndarray
61
+
62
+
63
+ class AdaDelta(AbstractOptimizer):
64
+ """AdaDelta optimizer implementation.
65
+
66
+ Args:
67
+ func (Callable[[ndarray], float]): The objective function to be minimized.
68
+ lower_bound (float): The lower bound of the search space.
69
+ upper_bound (float): The upper bound of the search space.
70
+ dim (int): The dimensionality of the search space.
71
+ max_iter (int, optional): The maximum number of iterations. Defaults to 1000.
72
+ seed (Optional[int], optional): The seed value for random number generation. Defaults to None.
73
+ rho (float, optional): The decay rate for the moving average of squared gradients. Defaults to 0.97.
74
+ eps (float, optional): A small constant to avoid division by zero. Defaults to 1e-8.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ func: Callable[[ndarray], float],
80
+ lower_bound: float,
81
+ upper_bound: float,
82
+ dim: int,
83
+ max_iter: int = 1000,
84
+ rho: float = 0.97,
85
+ eps: float = 1e-8,
86
+ seed: int | None = None,
87
+ ) -> None:
88
+ """Initialize the AdaDelta optimizer."""
89
+ super().__init__(
90
+ func=func,
91
+ lower_bound=lower_bound,
92
+ upper_bound=upper_bound,
93
+ dim=dim,
94
+ max_iter=max_iter,
95
+ seed=seed,
96
+ )
97
+ self.rho = rho
98
+ self.eps = eps
99
+ self.Eg = np.zeros(self.dim)
100
+ self.Edx = np.zeros(self.dim)
101
+
102
+ def _update(self, x: np.ndarray) -> np.ndarray:
103
+ """Perform a single update step of the AdaDelta algorithm.
104
+
105
+ Args:
106
+ x (np.ndarray): The current solution.
107
+
108
+ Returns:
109
+ np.ndarray: The updated solution.
110
+ """
111
+ g = approx_fprime(x, self.func, self.eps)
112
+ self.Eg = self.rho * self.Eg + (1 - self.rho) * g**2
113
+ dx = -np.sqrt(self.Edx + self.eps) / np.sqrt(self.Eg + self.eps) * g
114
+ self.Edx = self.rho * self.Edx + (1 - self.rho) * dx**2
115
+ return x + dx
116
+
117
+ def search(self) -> tuple[np.ndarray, float]:
118
+ """Perform the AdaDelta search.
119
+
120
+ Returns:
121
+ Tuple[np.ndarray, float]: A tuple containing the best solution found and its fitness value.
122
+ """
123
+ # Initialize solution
124
+ x = np.random.default_rng(self.seed).uniform(
125
+ self.lower_bound, self.upper_bound, self.dim
126
+ )
127
+ best_solution = x
128
+ best_fitness = np.inf
129
+
130
+ # Main loop
131
+ for _ in range(self.max_iter):
132
+ x = self._update(x)
133
+ x = np.clip(x, self.lower_bound, self.upper_bound)
134
+ fitness = self.func(x)
135
+ if fitness < best_fitness:
136
+ best_fitness = fitness
137
+ best_solution = x
138
+
139
+ return best_solution, best_fitness
140
+
141
+
142
+ if __name__ == "__main__":
143
+ optimizer = AdaDelta(
144
+ func=shifted_ackley, lower_bound=-2.768, upper_bound=+2.768, dim=2
145
+ )
146
+ best_solution, best_fitness = optimizer.search()
147
+ print(f"Best solution found: {best_solution}")
148
+ print(f"Best fitness value: {best_fitness}")
@@ -0,0 +1,111 @@
1
+ """ADAGrad Optimizer.
2
+
3
+ This module implements the Adaptive Gradient Algorithm (ADAGrad) optimizer. ADAGrad is
4
+ a gradient-based optimization algorithm that adapts the learning rate to the parameters,
5
+ performing smaller updates for parameters associated with frequently occurring features,
6
+ and larger updates for parameters associated with infrequent features. It is particularly
7
+ useful for dealing with sparse data.
8
+
9
+ ADAGrad's main strength is that it eliminates the need to manually tune the learning rate.
10
+ Most implementations also include a 'smoothing term' to avoid division by zero when the
11
+ gradient is zero.
12
+
13
+ The ADAGrad optimizer is commonly used in machine learning and deep learning applications.
14
+
15
+ Example:
16
+ optimizer = ADAGrad(func=objective_function, learning_rate=0.01, initial_guess=[0, 0])
17
+ best_solution, best_fitness = optimizer.optimize()
18
+
19
+ Attributes:
20
+ func (Callable): The objective function to optimize.
21
+ learning_rate (float): The learning rate for the optimization.
22
+ initial_guess (List[float]): The starting point for the optimization.
23
+
24
+ Methods:
25
+ optimize(): Perform the ADAGrad optimization.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from typing import TYPE_CHECKING
31
+
32
+ import numpy as np
33
+
34
+ from scipy.optimize import approx_fprime
35
+
36
+ from opt.abstract_optimizer import AbstractOptimizer
37
+ from opt.benchmark.functions import shifted_ackley
38
+
39
+
40
+ if TYPE_CHECKING:
41
+ from collections.abc import Callable
42
+
43
+ from numpy import ndarray
44
+
45
+
46
+ class ADAGrad(AbstractOptimizer):
47
+ """ADAGrad optimizer implementation.
48
+
49
+ Args:
50
+ func (Callable[[ndarray], float]): The objective function to be optimized.
51
+ lower_bound (float): The lower bound of the search space.
52
+ upper_bound (float): The upper bound of the search space.
53
+ dim (int): The dimensionality of the search space.
54
+ max_iter (int, optional): The maximum number of iterations. Defaults to 1000.
55
+ seed (Optional[int], optional): The seed value for random number generation. Defaults to None.
56
+ lr (float, optional): The learning rate. Defaults to 0.01.
57
+ eps (float, optional): A small value added to the denominator for numerical stability. Defaults to 1e-8.
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ func: Callable[[ndarray], float],
63
+ lower_bound: float,
64
+ upper_bound: float,
65
+ dim: int,
66
+ max_iter: int = 1000,
67
+ lr: float = 0.01,
68
+ eps: float = 1e-8,
69
+ seed: int | None = None,
70
+ ) -> None:
71
+ """Initialize the ADAGrad optimizer."""
72
+ super().__init__(
73
+ func=func,
74
+ lower_bound=lower_bound,
75
+ upper_bound=upper_bound,
76
+ dim=dim,
77
+ max_iter=max_iter,
78
+ seed=seed,
79
+ )
80
+ self.lr = lr
81
+ self.eps = eps
82
+
83
+ def search(self) -> tuple[np.ndarray, float]:
84
+ """Perform the ADAGrad search algorithm.
85
+
86
+ Returns:
87
+ Tuple[np.ndarray, float]: A tuple containing the best solution found and its fitness value.
88
+ """
89
+ x = np.random.default_rng(self.seed).uniform(
90
+ self.lower_bound, self.upper_bound, self.dim
91
+ )
92
+ grad_accumulator = np.zeros(self.dim)
93
+
94
+ for _ in range(self.max_iter):
95
+ grad = approx_fprime(x, self.func, np.sqrt(np.finfo(float).eps))
96
+ grad_accumulator += grad**2
97
+ adjusted_grad = grad / (np.sqrt(grad_accumulator) + self.eps)
98
+ x = x - self.lr * adjusted_grad
99
+
100
+ best_solution = x
101
+ best_fitness = self.func(best_solution)
102
+ return best_solution, best_fitness
103
+
104
+
105
+ if __name__ == "__main__":
106
+ optimizer = ADAGrad(
107
+ func=shifted_ackley, lower_bound=-2.768, upper_bound=2.768, dim=2
108
+ )
109
+ best_solution, best_fitness = optimizer.search()
110
+ print(f"Best solution found: {best_solution}")
111
+ print(f"Best fitness value: {best_fitness}")