遗传算法求香蕉函数的极大值
时间: 2024-01-15 17:05:09 浏览: 124
遗传算法求函数极大值(matlab实现).docx
遗传算法是一种优化算法,可以用于求解函数的极大值或极小值。香蕉函数(Rosenbrock函数)是一个经典的非凸函数,常用于测试最优化算法的性能。
下面是使用遗传算法求解香蕉函数极大值的一个示例:
```python
import random
# 定义香蕉函数
def banana_function(x1, x2):
return (1 - x1)**2 + 100 * (x2 - x1**2)**2
# 定义遗传算法函数
def genetic_algorithm(Size, G, Codel, umax, umin, pc, pm):
# 初始化种群
population = []
for _ in range(Size):
individual = [random.uniform(umin, umax) for _ in range(Codel)]
population.append(individual)
# 迭代进化
for _ in range(G):
# 计算适应度
fitness = [banana_function(individual[0], individual[1]) for individual in population]
# 选择
selected_population = []
for _ in range(Size):
# 轮盘赌选择
total_fitness = sum(fitness)
pick = random.uniform(0, total_fitness)
current_fitness = 0
for i in range(Size):
current_fitness += fitness[i]
if current_fitness > pick:
selected_population.append(population[i])
break
# 交叉
offspring_population = []
for i in range(0, Size, 2):
parent1 = selected_population[i]
parent2 = selected_population[i+1]
if random.random() < pc:
# 单点交叉
crossover_point = random.randint(1, Codel-1)
offspring1 = parent1[:crossover_point] + parent2[crossover_point:]
offspring2 = parent2[:crossover_point] + parent1[crossover_point:]
else:
offspring1 = parent1
offspring2 = parent2
offspring_population.append(offspring1)
offspring_population.append(offspring2)
# 变异
for i in range(Size):
individual = offspring_population[i]
for j in range(Codel):
if random.random() < pm:
individual[j] = random.uniform(umin, umax)
# 更新种群
population = offspring_population
# 找到最优解
best_individual = population[0]
best_fitness = banana_function(best_individual[0], best_individual[1])
for individual in population:
fitness = banana_function(individual[0], individual[1])
if fitness > best_fitness:
best_individual = individual
best_fitness = fitness
return best_fitness, best_individual[0], best_individual[1]
# 调用遗传算法函数求解香蕉函数的极大值
BestSfi, BestS, x1, x2 = genetic_algorithm(Size=100, G=100, Codel=2, umax=5, umin=-5, pc=0.8, pm=0.01)
print("最大值:", BestSfi)
print("最优解:", BestS, x1, x2)
```
这段代码使用遗传算法对香蕉函数进行了优化,输出了找到的最大值和对应的最优解。
阅读全文