-
-
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 all 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,125 @@ | ||
import numpy as np | ||
|
||
|
||
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, | ||
func, | ||
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
|
||
bounds, | ||
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
|
||
population_size=100, | ||
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
|
||
generations=500, | ||
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
|
||
crossover_prob=0.9, | ||
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
|
||
mutation_prob=0.01, | ||
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
|
||
): | ||
self.func = func | ||
self.bounds = np.array(bounds) | ||
self.population_size = population_size | ||
self.generations = generations | ||
self.crossover_prob = crossover_prob | ||
self.mutation_prob = mutation_prob | ||
self.num_variables = len(bounds) | ||
|
||
# Initialize the random number generator | ||
self.rng = np.random.default_rng() | ||
|
||
def initialize_population(self): | ||
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
|
||
""" | ||
Initialize a population of random solutions within the bounds. | ||
""" | ||
return self.rng.uniform( | ||
low=self.bounds[:, 0], | ||
high=self.bounds[:, 1], | ||
size=(self.population_size, self.num_variables), | ||
) | ||
|
||
def fitness(self, individual): | ||
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
|
||
""" | ||
Evaluate the fitness of an individual. | ||
In minimization problems, we aim to minimize the function value. | ||
""" | ||
return self.func(*individual) | ||
|
||
def select_parents(self, population, fitness_scores): | ||
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
|
||
""" | ||
Select parents using tournament selection. | ||
""" | ||
selected_indices = self.rng.choice( | ||
range(self.population_size), size=2, replace=False | ||
) | ||
return population[selected_indices[np.argmin(fitness_scores[selected_indices])]] | ||
|
||
def crossover(self, parent1, parent2): | ||
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
|
||
""" | ||
Perform one-point crossover to create offspring. | ||
Skip crossover for single-variable functions. | ||
""" | ||
if self.num_variables == 1: | ||
return parent1, parent2 # No crossover needed for single-variable functions | ||
|
||
if self.rng.random() < self.crossover_prob: | ||
point = self.rng.integers(1, self.num_variables) | ||
child1 = np.concatenate((parent1[:point], parent2[point:])) | ||
child2 = np.concatenate((parent2[:point], parent1[point:])) | ||
return child1, child2 | ||
return parent1, parent2 | ||
|
||
def mutate(self, individual): | ||
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
|
||
""" | ||
Apply mutation to an individual with a given mutation probability. | ||
""" | ||
if self.rng.random() < self.mutation_prob: | ||
index = self.rng.integers(0, self.num_variables) | ||
individual[index] = self.rng.uniform( | ||
self.bounds[index, 0], self.bounds[index, 1] | ||
) | ||
return individual | ||
|
||
def evolve(self): | ||
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
|
||
""" | ||
Run the genetic algorithm for a number of generations. | ||
""" | ||
population = self.initialize_population() | ||
best_solution = None | ||
best_fitness = float("inf") | ||
|
||
for gen in range(self.generations): | ||
fitness_scores = np.array( | ||
[self.fitness(individual) for individual in population] | ||
) | ||
|
||
new_population = [] | ||
for _ in range(self.population_size // 2): | ||
parent1 = self.select_parents(population, fitness_scores) | ||
parent2 = self.select_parents(population, fitness_scores) | ||
child1, child2 = self.crossover(parent1, parent2) | ||
child1 = self.mutate(child1) | ||
child2 = self.mutate(child2) | ||
new_population.extend([child1, child2]) | ||
|
||
population = np.array(new_population) | ||
|
||
# Track the best solution | ||
min_fitness_index = np.argmin(fitness_scores) | ||
if fitness_scores[min_fitness_index] < best_fitness: | ||
best_fitness = fitness_scores[min_fitness_index] | ||
best_solution = population[min_fitness_index] | ||
|
||
print(f"Generation {gen + 1}, Best Fitness: {best_fitness}") | ||
|
||
return best_solution, best_fitness | ||
|
||
|
||
if __name__ == "__main__": | ||
# Define the function to optimize | ||
def func(x, y): | ||
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
|
||
return x**2 + y**2 # Example: Minimizing x^2 + y^2 | ||
|
||
# Define the bounds for each variable | ||
bounds = [(-10, 10), (-10, 10)] | ||
|
||
# Initialize and run the optimizer | ||
optimizer = GeneticAlgorithmOptimizer(func=func, bounds=bounds) | ||
best_solution, best_fitness = optimizer.evolve() | ||
|
||
print("Best Solution:", best_solution) | ||
print("Best Fitness:", best_fitness) |
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.