遗传算法python代码应用实例
时间: 2024-10-15 14:04:59 浏览: 39
遗传算法在Python中的应用通常用于优化问题,比如函数极值搜索。下面是一个简化版的遗传算法用于求解单峰函数的极值的Python代码示例[^1]:
```python
import numpy as np
from random import uniform
# 初始化参数
def initialize_population(pop_size, problem_dim):
return [np.random.rand(problem_dim) for _ in range(pop_size)]
# 函数适应度评估
def fitness_function(solution):
# 假设我们正在寻找一个函数f(x)的最小值
# 对于单峰函数,越接近峰值,适应度越好
return -solution**2
# 选择操作
def selection(population, fitness):
elite_count = len(population) // 10 # 精英保留比例
sorted_indices = np.argsort(fitness)[:elite_count] # 选取适应度最高的个体
selected = population[sorted_indices]
remaining = population[~np.isin(np.arange(len(population)), sorted_indices)]
return np.concatenate([selected, remaining])
# 交叉操作
def crossover(parents, crossover_rate):
child_size = parents.shape[0]
cross_points = np.random.choice(child_size, 2, replace=False)
parent1, parent2 = parents[cross_points]
offspring = np.zeros_like(parents)
offspring[(cross_points[0]:child_size), :] = parent1[(cross_points[1]:):]
offspring[(cross_points[1]:), :] = parent2[:cross_points[0]]
return offspring
# 变异操作
def mutation(children, mutation_rate, problem_dim):
mutated_children = children.copy()
for i in range(len(mutated_children)):
if uniform(0, 1) < mutation_rate:
mutated_children[i] += uniform(-1, 1) * (mutated_children[i].max() - mutated_children[i].min())
return mutated_children
# 主循环
def genetic_algorithm(pop_size, generations, problem_dim, crossover_rate, mutation_rate):
population = initialize_population(pop_size, problem_dim)
for _ in range(generations):
fitness = np.array([fitness_function(sol) for sol in population])
population = selection(population, fitness)
population = crossover(population, crossover_rate)
population = mutation(population, mutation_rate, problem_dim)
best_solution = population[np.argmin(fitness_function(population))]
return best_solution, fitness_function(best_solution)
# 示例调用
best_solution, fitness = genetic_algorithm(100, 100, 1, 0.8, 0.01)
print(f"Best solution found: {best_solution}, with fitness: {fitness}")
```
阅读全文