python实现遗传算法对标准测试函数(以Rastrigin函数为例)进行求解,效果还不错:
import numpy as np
import matplotlib.pyplot as plt
# 标准测试函数(以Rastrigin函数为例)
def rastrigin(x):
return 10 * len(x) + sum([(xi**2 - 10 * np.cos(2 * np.pi * xi)) for xi in x])
class GeneticAlgorithm:
def __init__(self, func, bounds, pop_size=200, elite_size=10,
mutation_rate=0.01, generations=100):
self.func = func
self.bounds = bounds
self.dim = len(bounds)
self.pop_size = pop_size
self.elite_size = elite_size
self.mutation_rate = mutation_rate
self.generations = generations
def initialize_population(self):
return np.random.uniform(
low=[b[0] for b in self.bounds],
high=[b[1] for b in self.bounds],
size=(self.pop_size, self.dim)
)
def fitness(self, population):
return 1 / (1 + np.array([self.func(ind) for ind in population]))
def select(self, population, fitness):
elite_idx = np.argsort(fitness)[-self.elite_size:]
parents = population[elite_idx]
return parents
def crossover(self, parents):
offspring = np.zeros((self.pop_size - self.elite_size, self.dim))
for i in range(offspring.shape[0]):
parent1, parent2 = parents[np.random.choice(len(parents), 2, replace=False)]
alpha = np.random.random(self.dim)
offspring[i] = alpha * parent1 + (1 - alpha) * parent2
return offspring
def mutate(self, offspring):
for i in range(offspring.shape[0]):
if np.random.random() < self.mutation_rate:
j = np.random.randint(self.dim)
offspring[i,j] = np.random.uniform(self.bounds[j][0], self.bounds[j][1])
return offspring
def run(self):
pop = self.initialize_population()
best_fitness = []
for gen in range(self.generations):
fit = self.fitness(pop)
best_fitness.append(np.max(fit))
parents = self.select(pop, fit)
offspring = self.crossover(parents)
offspring = self.mutate(offspring)
pop = np.vstack([parents, offspring])
if gen % 10 == 0:
best_idx = np.argmax(fit)
print(f"Gen {gen}: Best fitness = {1/fit[best_idx]-1:.4f}")
best_idx = np.argmax(self.fitness(pop))
best_solution = pop[best_idx]
best_value = self.func(best_solution)
return best_solution, best_value, best_fitness
# 参数设置
bounds = [(-5.12, 5.12)] * 2 # 二维Rastrigin函数搜索空间
ga = GeneticAlgorithm(rastrigin, bounds, generations=100)
# 运行算法
solution, value, fitness_history = ga.run()
# 输出结果
print(f"\n最优解: {solution}")
print(f"最优值: {value:.4f}")
# 绘制收敛曲线
plt.figure(figsize=(10,6))
plt.plot(1/np.array(fitness_history)-1, 'r-', linewidth=2)
plt.xlabel('Generation')
plt.ylabel('Best Fitness')
plt.title('Genetic Algorithm Convergence')
plt.grid(True)
plt.show()
效果: