-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Create function_optimization.py #11611
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 41 commits
Commits
Show all changes
43 commits
Select commit
Hold shift + click to select a range
1c8c133
Create function_optimization.py
night-spring a91b8d8
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 8176e0e
Update function_optimization.py
night-spring da593c4
Merge branch 'master' of https://github.com/night-spring/Python
night-spring 3864de9
Update function_optimization.py
night-spring 1ad1867
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] f7bc96e
Update function_optimization.py
night-spring 70f4771
Merge branch 'master' of https://github.com/night-spring/Python
night-spring 5d82115
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b740c01
Update function_optimization.py
night-spring d28af66
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 78c8dd7
Update function_optimization.py
night-spring 854b155
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] fa726e6
Update function_optimization.py
night-spring 08ab755
Merge branch 'master' of https://github.com/night-spring/Python
night-spring ad01c9c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] b761f25
Update function_optimization.py
night-spring f4a4831
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] eb27d35
Update function_optimization.py
night-spring 19d5420
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] e51da64
.
night-spring 0feb04c
Update genetic_algorithm_optimization.py
night-spring 162792e
Update genetic_algorithm_optimization.py
night-spring b093145
Update genetic_algorithm_optimization.py
night-spring 7f8befa
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 0697e97
Update genetic_algorithm_optimization.py
night-spring cd4f6f3
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 282b6c6
Update genetic_algorithm_optimization.py
night-spring 85fc983
Update genetic_algorithm_optimization.py
night-spring 11876c9
Update genetic_algorithm_optimization.py
night-spring cabb35a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 961e1a4
Merge branch 'TheAlgorithms:master' into master
night-spring 6dd4159
Merge branch 'TheAlgorithms:master' into master
night-spring ccbf8a5
Update genetic_algorithm_optimization.py
night-spring 8661150
Update genetic_algorithm_optimization.py
night-spring 3a654c5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 1873f2f
Update genetic_algorithm_optimization.py
night-spring 40e4e3c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 5ff30a6
Update genetic_algorithm_optimization.py
night-spring 0b06dae
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 796d80b
Update genetic_algorithm_optimization.py
night-spring 57feaea
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 096a033
Update genetic_algorithm_optimization.py
night-spring File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
from collections.abc import Callable # Sorted import | ||
import numpy as np # Sorted import | ||
|
||
class GeneticAlgorithmOptimizer: | ||
def __init__( | ||
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self, | ||
objective_function: Callable[..., float], | ||
variable_bounds: list[tuple[float, float]], | ||
population_size: int = 100, | ||
max_generations: int = 500, | ||
crossover_probability: float = 0.9, | ||
mutation_probability: float = 0.01, | ||
) -> None: | ||
self.objective_function = objective_function | ||
self.variable_bounds = np.array(variable_bounds) | ||
self.population_size = population_size | ||
self.max_generations = max_generations | ||
self.crossover_probability = crossover_probability | ||
self.mutation_probability = mutation_probability | ||
self.num_variables = len(variable_bounds) | ||
self.rng = np.random.default_rng() # Initialize random generator | ||
|
||
def generate_initial_population(self) -> np.ndarray: | ||
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Generate a population of random solutions within the given variable bounds. | ||
""" | ||
return self.rng.uniform( | ||
low=self.variable_bounds[:, 0], | ||
high=self.variable_bounds[:, 1], | ||
size=(self.population_size, self.num_variables), | ||
) | ||
|
||
def evaluate_fitness(self, individual: list[float]) -> float: | ||
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Evaluate the fitness of an individual by computing the value of the objective function. | ||
""" | ||
return self.objective_function(*individual) | ||
|
||
def select_parent( | ||
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self, population: np.ndarray, fitness_values: np.ndarray | ||
) -> np.ndarray: | ||
""" | ||
Select a parent using tournament selection based on fitness values. | ||
""" | ||
selected_indices = self.rng.choice( | ||
range(self.population_size), size=2, replace=False | ||
) | ||
return population[selected_indices[np.argmin(fitness_values[selected_indices])]] | ||
|
||
def perform_crossover( | ||
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self, parent1: np.ndarray, parent2: np.ndarray | ||
) -> tuple[np.ndarray, np.ndarray]: | ||
""" | ||
Perform one-point crossover between two parents to create offspring. | ||
""" | ||
if self.num_variables == 1: | ||
return parent1, parent2 | ||
|
||
if self.rng.random() < self.crossover_probability: | ||
crossover_point = self.rng.integers(1, self.num_variables) | ||
child1 = np.concatenate((parent1[:crossover_point], parent2[crossover_point:])) | ||
child2 = np.concatenate((parent2[:crossover_point], parent1[crossover_point:])) | ||
return child1, child2 | ||
return parent1, parent2 | ||
|
||
def apply_mutation(self, individual: np.ndarray) -> np.ndarray: | ||
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Apply mutation to an individual based on the mutation probability. | ||
""" | ||
if self.rng.random() < self.mutation_probability: | ||
mutation_index = self.rng.integers(0, self.num_variables) | ||
individual[mutation_index] = self.rng.uniform( | ||
self.variable_bounds[mutation_index, 0], | ||
self.variable_bounds[mutation_index, 1] | ||
) | ||
return individual | ||
|
||
def optimize(self) -> tuple[np.ndarray, float]: | ||
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Execute the genetic algorithm over a number of generations to find the optimal solution. | ||
""" | ||
population = self.generate_initial_population() | ||
best_solution = None | ||
best_fitness_value = float("inf") | ||
|
||
for generation in range(self.max_generations): | ||
fitness_values = np.array( | ||
[self.evaluate_fitness(individual) for individual in population] | ||
) | ||
|
||
new_population = [] | ||
for _ in range(self.population_size // 2): | ||
parent1 = self.select_parent(population, fitness_values) | ||
parent2 = self.select_parent(population, fitness_values) | ||
child1, child2 = self.perform_crossover(parent1, parent2) | ||
child1 = self.apply_mutation(child1) | ||
child2 = self.apply_mutation(child2) | ||
new_population.extend([child1, child2]) | ||
|
||
population = np.array(new_population) | ||
|
||
# Track the best solution | ||
min_fitness_index = np.argmin(fitness_values) | ||
if fitness_values[min_fitness_index] < best_fitness_value: | ||
best_fitness_value = fitness_values[min_fitness_index] | ||
best_solution = population[min_fitness_index] | ||
|
||
print(f"Generation {generation + 1}, Best Fitness Value: {best_fitness_value}") | ||
|
||
return best_solution, best_fitness_value | ||
|
||
if __name__ == "__main__": | ||
def objective_function(x: float, y: float) -> float: | ||
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
night-spring marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Example objective function to minimize x^2 + y^2 | ||
""" | ||
return x**2 + y**2 | ||
|
||
variable_bounds: list[tuple[float, float]] = [(-10, 10), (-10, 10)] | ||
|
||
optimizer = GeneticAlgorithmOptimizer( | ||
objective_function=objective_function, | ||
variable_bounds=variable_bounds | ||
) | ||
best_solution, best_fitness_value = optimizer.optimize() | ||
|
||
print("Best Solution:", best_solution) | ||
print("Best Fitness Value:", best_fitness_value) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.