用Python写一段遗传算法
时间: 2024-02-16 13:52:28 浏览: 67
好的,下面是一个简单的遗传算法的Python代码示例:
```python
import random
# 遗传算法的参数设置
POPULATION_SIZE = 10 # 种群数量
CROSSOVER_PROBABILITY = 0.8 # 交叉概率
MUTATION_PROBABILITY = 0.2 # 变异概率
GENERATIONS = 10 # 迭代次数
# 假设我们要优化的函数为 f(x) = x^2
def objective_function(x):
return x**2
# 初始化种群,每个个体随机生成一个 x 值
def initialize_population():
population = []
for i in range(POPULATION_SIZE):
x = random.uniform(-10, 10)
population.append({'x': x, 'fitness': None})
return population
# 计算个体的适应度
def calculate_fitness(individual):
x = individual['x']
fitness = objective_function(x)
individual['fitness'] = fitness
return fitness
# 选择操作,使用轮盘赌选择算法
def selection(population):
total_fitness = sum([individual['fitness'] for individual in population])
selected_individuals = []
for i in range(POPULATION_SIZE):
pick = random.uniform(0, total_fitness)
current = 0
for individual in population:
current += individual['fitness']
if current > pick:
selected_individuals.append(individual)
break
return selected_individuals
# 交叉操作,使用单点交叉算法
def crossover(parent1, parent2):
if random.random() < CROSSOVER_PROBABILITY:
crossover_point = random.randint(0, 1)
child1 = {'x': None, 'fitness': None}
child2 = {'x': None, 'fitness': None}
child1['x'] = parent1['x'][0:crossover_point] + parent2['x'][crossover_point:]
child2['x'] = parent2['x'][0:crossover_point] + parent1['x'][crossover_point:]
return child1, child2
else:
return parent1, parent2
# 变异操作,使用随机变异算法
def mutation(child):
if random.random() < MUTATION_PROBABILITY:
mutation_point = random.randint(0, len(child['x'])-1)
child['x'][mutation_point] = random.uniform(-10, 10)
return child
# 遗传算法主程序
def genetic_algorithm():
# 初始化种群
population = initialize_population()
# 迭代
for i in range(GENERATIONS):
# 计算个体适应度
for individual in population:
calculate_fitness(individual)
# 选择
selected_individuals = selection(population)
# 交叉
children = []
for i in range(0, POPULATION_SIZE, 2):
child1, child2 = crossover(selected_individuals[i], selected_individuals[i+1])
children.append(mutation(child1))
children.append(mutation(child2))
# 替换原始种群
population = children
# 返回最优解
best_individual = max(population, key=lambda x: x['fitness'])
return best_individual['x']
```
上述代码实现了一个简单的遗传算法,用于求解 $f(x)=x^2$ 函数在 $[-10, 10]$ 区间内的最大值。在遗传算法的迭代过程中,每个个体表示为一个字典,包含一个 x 值和一个适应度值。在初始化种群时,随机生成每个个体的 x 值;在计算适应度时,根据目标函数计算个体的适应度;在选择操作中,使用轮盘赌选择算法选择个体;在交叉操作中,使用单点交叉算法对个体进行交叉;在变异操作中,使用随机变异算法对个体进行变异。最终返回种群中适应度最高的个体的 x 值作为最优解。
阅读全文