基于遗传算法的实例代码
时间: 2024-10-27 20:14:11 浏览: 25
matlab遗传算法实例.zip_matlab 遗传算法_遗传算法
5星 · 资源好评率100%
基于遗传算法的实例代码通常用于解决优化问题,如函数最小化、路线规划等。这里是一个简单的Python遗传算法求解一维函数优化的示例:
```python
import random
from math import sin
# 定义目标函数(这里是单峰函数Zimmermann函数)
def fitness_function(x):
return (x - 6) ** 2 + sin(12 * x) + 10
# 遗传算法参数
pop_size = 50 # 种群大小
gen_num = 100 # 迭代次数
mutation_rate = 0.1 # 变异概率
crossover_rate = 0.9 # 交叉概率
# 初始化种群
def create_population(pop_size):
return [random.uniform(-10, 10) for _ in range(pop_size)]
# 适应度评估
def evaluate_population(population):
return [fitness_function(individual) for individual in population]
# 选择操作
def selection(population, fitness):
return [population[i] for i in sorted(range(len(fitness)), key=lambda k: fitness[k], reverse=True)[:int(pop_size / 2)])
# 交叉操作
def crossover(parents):
if random.random() < crossover_rate:
cut_point = random.randint(1, len(parents[0]) - 1)
child1 = parents[0][:cut_point] + parents[1][cut_point:]
child2 = parents[1][:cut_point] + parents[0][cut_point:]
return [child1, child2]
else:
return parents
# 变异操作
def mutation(population):
for individual in population:
if random.random() < mutation_rate:
individual[random.randint(0, len(individual)-1)] += random.uniform(-0.1, 0.1)
return population
# 主体循环
def genetic_algorithm():
population = create_population(pop_size)
for _ in range(gen_num):
fitness_values = evaluate_population(population)
selected_population = selection(population, fitness_values)
children = crossover(selected_population)
mutated_children = mutation(children)
population = mutated_children
best_individual = min(population, key=fitness_function)
return best_individual, fitness_function(best_individual)
best_solution, best_fitness = genetic_algorithm()
print(f"最优解: {best_solution}, 最优值: {best_fitness}")
阅读全文