带约束条件的遗传算法代码
时间: 2023-06-15 15:07:35 浏览: 44
以下是一个简单的带约束条件的遗传算法代码示例:
```python
import random
# 定义目标函数
def objective_function(x):
return x[0]**2 + x[1]**2
# 定义约束条件函数
def constraint_function(x):
return x[0] + x[1] - 2
# 定义遗传算法函数
def genetic_algorithm(objective_function, constraint_function, bounds, n_population=50, n_generations=100, p_crossover=0.9, p_mutation=0.1):
population = []
for i in range(n_population):
individual = []
for j in range(len(bounds)):
individual.append(random.uniform(bounds[j][0], bounds[j][1]))
population.append(individual)
for i in range(n_generations):
# 计算适应度和约束条件
fitness_values = []
constraint_values = []
for j in range(n_population):
fitness = objective_function(population[j])
fitness_values.append(fitness)
constraint = constraint_function(population[j])
constraint_values.append(constraint)
# 找到符合约束条件的个体
feasible_population = []
feasible_fitness_values = []
for j in range(n_population):
if constraint_values[j] <= 0:
feasible_population.append(population[j])
feasible_fitness_values.append(fitness_values[j])
# 打印当前最优解
best_index = feasible_fitness_values.index(min(feasible_fitness_values))
print("Generation {}: Best objective value = {:.4f}".format(i+1, feasible_fitness_values[best_index]))
# 选择
parents = random.choices(feasible_population, weights=feasible_fitness_values, k=n_population)
# 交叉
for j in range(0, n_population, 2):
if random.random() < p_crossover:
crossover_point = random.randint(1, len(bounds)-1)
parents[j][crossover_point:], parents[j+1][crossover_point:] = parents[j+1][crossover_point:], parents[j][crossover_point:]
# 变异
for j in range(n_population):
if random.random() < p_mutation:
mutation_point = random.randint(0, len(bounds)-1)
parents[j][mutation_point] = random.uniform(bounds[mutation_point][0], bounds[mutation_point][1])
# 更新种群
population = parents
# 返回最优解
best_index = feasible_fitness_values.index(min(feasible_fitness_values))
return feasible_population[best_index]
```
该代码中,`objective_function` 是目标函数,`constraint_function` 是约束条件函数,`bounds` 是变量的取值范围,`n_population` 是种群大小,`n_generations` 是迭代次数,`p_crossover` 是交叉概率,`p_mutation` 是变异概率。
在遗传算法的每一代中,首先计算所有个体的适应度和约束条件,然后找到符合约束条件的个体,打印当前最优解。接着,根据适应度进行选择操作,然后根据交叉概率进行交叉操作,最后根据变异概率进行变异操作,更新种群。最后返回符合约束条件的最优解。