Python 2 :
2. Algorithme génétique pour l'optimisation d'une fonction
Énoncé :
Implémenter un algorithme génétique pour trouver les valeurs de xxx et yyy maximisant la
fonction f(x,y)=x2+y2f(x, y) = x^2 + y^2f(x,y)=x2+y2 dans une plage donnée.
Solution :
python
Copier
import numpy as np
# Fonction à optimiser
def fitness(x, y):
return x**2 + y**2
# Initialisation de la population
def create_population(pop_size, x_bounds, y_bounds):
population = []
for _ in range(pop_size):
x = np.random.uniform(*x_bounds)
y = np.random.uniform(*y_bounds)
population.append((x, y))
return population
# Sélection par tournoi
def select(population):
tournament = np.random.choice(population, size=5)
best = max(tournament, key=lambda ind: fitness(ind[0], ind[1]))
return best
# Croisement (crossover)
def crossover(parent1, parent2):
child1 = (parent1[0], parent2[1])
child2 = (parent2[0], parent1[1])
return child1, child2
# Mutation
def mutate(individual, mutation_rate, x_bounds, y_bounds):
if np.random.rand() < mutation_rate:
x = np.random.uniform(*x_bounds)
y = np.random.uniform(*y_bounds)
return (x, y)
return individual
# Algorithme génétique
def genetic_algorithm(pop_size, x_bounds, y_bounds, generations,
mutation_rate):
population = create_population(pop_size, x_bounds, y_bounds)
for gen in range(generations):
new_population = []
for _ in range(pop_size // 2):
parent1 = select(population)
parent2 = select(population)
child1, child2 = crossover(parent1, parent2)
new_population.append(mutate(child1, mutation_rate, x_bounds,
y_bounds))
new_population.append(mutate(child2, mutation_rate, x_bounds,
y_bounds))
population = new_population
best_individual = max(population, key=lambda ind: fitness(ind[0],
ind[1]))
return best_individual
# Paramètres de l'algorithme
pop_size = 100
x_bounds = (-10, 10)
y_bounds = (-10, 10)
generations = 1000
mutation_rate = 0.1
best = genetic_algorithm(pop_size, x_bounds, y_bounds, generations,
mutation_rate)
print(f"Meilleure solution trouvée : x = {best[0]}, y = {best[1]}, f(x, y)
= {fitness(best[0], best[1])}")
Explication :
L'algorithme génétique est utilisé pour maximiser une fonction.
Il comprend la création d'une population aléatoire, la sélection par tournoi, le
croisement (crossover) et la mutation.
L'objectif est de trouver la combinaison de xxx et yyy qui maximise f(x,y)f(x, y)f(x,y).