针对全局优化问题(如多峰函数优化),如何结合遗传算法与Python实现高效的全局搜索?请给出代码框架并分析其性能。
import random
import numpy as np
# 定义目标函数,这里以多峰函数为例
def objective_function(x):
return np.sin(x) + np.sin(10 * x / 3)
# 遗传算法参数设置
POPULATION_SIZE = 100 # 种群大小
GENERATIONS = 50 # 迭代次数
MUTATION_RATE = 0.1 # 变异概率
ELITISM_RATE = 0.1 # 精英保留比例
# 初始化种群
def initialize_population(size, bounds):
return [random.uniform(bounds[0], bounds[1]) for _ in range(size)]
# 适应度函数(假设目标是最小化)
def fitness(individual):
return -objective_function(individual)
# 选择操作(轮盘赌)
def selection(population, fitnesses):
total_fitness = sum(fitnesses)
probabilities = [f / total_fitness for f in fitnesses]
selected = random.choices(population, weights=probabilities, k=POPULATION_SIZE)
return selected
# 交叉操作(单点交叉)
def crossover(parent1, parent2):
alpha = random.random()
child = alpha * parent1 + (1 - alpha) * parent2
return child
# 变异操作(高斯变异)
def mutation(individual, bounds, mutation_rate):
if random.random() < mutation_rate:
return random.uniform(bounds[0], bounds[1])
return individual
# 遗传算法主函数
def genetic_algorithm(bounds):
population = initialize_population(POPULATION_SIZE, bounds)
best_individual = None
best_fitness = -float('inf')
for generation in range(GENERATIONS):
# 计算适应度
fitnesses = [fitness(ind) for ind in population]
# 更新最优个体
current_best_fitness = max(fitnesses)
if current_best_fitness > best_fitness:
best_fitness = current_best_fitness
best_individual = population[np.argmax(fitnesses)]
# 选择
selected = selection(population, fitnesses)
# 精英保留
elite_size = int(POPULATION_SIZE * ELITISM_RATE)
elite_indices = np.argsort(fitnesses)[-elite_size:]
elite = [population[i] for i in elite_indices]
# 交叉和变异
new_population = []
for i in range(POPULATION_SIZE - elite_size):
parent1, parent2 = random.choices(selected, k=2)
child = crossover(parent1, parent2)
child = mutation(child, bounds, MUTATION_RATE)
new_population.append(child)
# 合并精英和新种群
population = elite + new_population
return best_individual, -best_fitness
# 定义搜索范围
bounds = (0, 10)
best_solution, best_value = genetic_algorithm(bounds)
print(f'最优解: {best_solution}, 最优值: {best_value}')
性能分析
- 多样性保持:遗传算法通过交叉和变异操作保持种群的多样性,避免陷入局部最优解。
- 全局搜索能力:通过种群的整体搜索,可以覆盖解空间的多个区域,提高找到全局最优解的概率。
- 计算开销:每次迭代需要计算种群中所有个体的适应度,可能会增加计算时间,但并行化可以优化这一点。
- 参数影响:种群大小、变异率和精英保留比例等参数直接影响算法的性能。较大的种群和变异率有助于探索新区域,但会增加计算成本。
示例分析
假设目标函数是多峰函数 np.sin(x) + np.sin(10 * x / 3),遗传算法能够在搜索范围 (0, 10) 内找到多个峰值点。通过足够多的迭代次数和适当的参数设置,算法可以收敛到全局最优解附近。实验结果表明,遗传算法在多峰优化问题中表现优于传统局部搜索方法。