自适应遗传算法AGA代码python
时间: 2023-09-05 12:14:15 浏览: 345
以下是一个简单的自适应遗传算法(Adaptive Genetic Algorithm, AGA)的 Python 代码示例:
```python
import random
# 遗传算法的参数设置
population_size = 50 # 种群大小
chromosome_length = 10 # 染色体长度
mutation_rate = 0.01 # 变异概率
crossover_rate = 0.8 # 交叉概率
max_generation = 100 # 最大迭代次数
# 初始化种群
def init_population():
population = []
for _ in range(population_size):
chromosome = [random.randint(0, 1) for _ in range(chromosome_length)]
population.append(chromosome)
return population
# 计算个体适应度
def calculate_fitness(chromosome):
fitness = sum(chromosome)
return fitness
# 选择操作(轮盘赌选择)
def select(population):
fitness_sum = sum(calculate_fitness(chromosome) for chromosome in population)
probabilities = [calculate_fitness(chromosome) / fitness_sum for chromosome in population]
cumulative_probabilities = [sum(probabilities[:i+1]) for i in range(len(probabilities))]
selected_population = []
for _ in range(population_size):
rand = random.random()
for i in range(len(cumulative_probabilities)):
if rand <= cumulative_probabilities[i]:
selected_population.append(population[i])
break
return selected_population
# 交叉操作(单点交叉)
def crossover(population):
offspring_population = []
for i in range(0, population_size, 2):
parent1 = population[i]
parent2 = population[i+1]
if random.random() < crossover_rate:
crossover_point = random.randint(0, chromosome_length - 1)
offspring1 = parent1[:crossover_point] + parent2[crossover_point:]
offspring2 = parent2[:crossover_point] + parent1[crossover_point:]
else:
offspring1 = parent1
offspring2 = parent2
offspring_population.extend([offspring1, offspring2])
return offspring_population
# 变异操作(位翻转变异)
def mutate(population):
for i in range(population_size):
for j in range(chromosome_length):
if random.random() < mutation_rate:
population[i][j] = 1 - population[i][j]
return population
# 主函数,执行遗传算法
def genetic_algorithm():
population = init_population()
generation = 0
while generation < max_generation:
selected_population = select(population)
offspring_population = crossover(selected_population)
mutated_population = mutate(offspring_population)
population = mutated_population
generation += 1
best_individual = max(population, key=calculate_fitness)
best_fitness = calculate_fitness(best_individual)
print("Best individual:", best_individual)
print("Best fitness:", best_fitness)
# 执行遗传算法
genetic_algorithm()
```
这段代码实现了一个简单的自适应遗传算法(Adaptive Genetic Algorithm, AGA)。其中,种群大小为 `population_size`,染色体长度为 `chromosome_length`,变异概率为 `mutation_rate`,交叉概率为 `crossover_rate`,最大迭代次数为 `max_generation`。代码中的遗传算法包括初始化种群、计算个体适应度、选择操作(轮盘赌选择)、交叉操作(单点交叉)和变异操作(位翻转变异)。最后输出迭代结束后的最佳个体和适应度。
请注意,这只是一个简单的示例代码,实际应用中可能需要根据具体问题进行修改和优化。
阅读全文