Random search
- class RandomSearch(domain: Domain, fitness_function: Callable[[Solution], float], population_size=10, max_iterations: int = 20, distributed=False, log_dir: str = 'logs/RS')
Bases:
MetaheuristicRandomSearch is a class for performing a random search optimization algorithm.
It generates and evaluates random solutions in a search space to find an optimal solution. The algorithm maintains a population of solutions and in each iteration, it mutates all solutions except the best one from the previous iteration.
- Parameters:
domain (Domain) – The search domain that defines the solution space
fitness_function (Callable[[Solution], float]) – The fitness function used to evaluate solutions
population_size (int, optional) – The size of the population to maintain, defaults to 1
max_iterations (int, optional) – The maximum number of iterations to run, defaults to 20
distributed (bool, optional) – Whether to use distributed computation, defaults to False
log_dir (str, optional) – Directory for logging, defaults to “logs/RS”
- Variables:
max_iterations (int) – Maximum number of iterations to run
Code example
from metagen.framework import Domain from metagen.metaheuristics import RandomSearch domain = Domain() domain.defineInteger(0, 1) fitness_function = ... search = RandomSearch(domain, fitness_function, population_size=50, max_iterations=100) optimal_solution = search.run()
Initialize the RandomSearch algorithm.
- Parameters:
domain (Domain) – The search domain that defines the solution space
fitness_function (Callable[[Solution], float]) – The fitness function used to evaluate solutions
population_size (int, optional) – The size of the population to maintain, defaults to 1
max_iterations (int, optional) – The maximum number of iterations to run, defaults to 20
distributed (bool, optional) – Whether to use distributed computation, defaults to False
log_dir (str, optional) – Directory for logging, defaults to “logs/RS”
- initialize(num_solutions=10) Tuple[List[Solution], Solution]
Initialize a population of random solutions.
- iterate(solutions: List[Solution]) Tuple[List[Solution], Solution]
Execute one iteration of the random search algorithm.
In each iteration, the best solution from the previous iteration is preserved, while all other solutions are mutated and evaluated.
- stopping_criterion() bool
Check if the algorithm should stop.
The algorithm stops when the current iteration reaches the maximum number of iterations.
- Returns:
True if the maximum number of iterations is reached, False otherwise
- Return type:
bool