遗传算法的介绍
遗传算法(Genetic Algorithm,GA)是一种模拟自然选择和遗传机制的随机搜索和优化算法。它通过模拟生物进化过程中的遗传、变异和选择等操作,来寻找问题的最优解或近似最优解。以下是一个使用Python实现遗传算法求解函数最大值的简单示例:
示例问题
假设我们要在区间 [0, 31]
内找到函数 y = x * x
的最大值。
代码实现
import random
# 计算适应度
def fitness(x):
return x * x
# 初始化种群
def initialize_population(population_size, chromosome_length):
population = []
for _ in range(population_size):
chromosome = [random.randint(0, 1) for _ in range(chromosome_length)]
population.append(chromosome)
return population
# 解码染色体
def decode_chromosome(chromosome):
return int(''.join(map(str, chromosome)), 2)
# 选择操作
def selection(population, fitness_scores):
total_fitness = sum(fitness_scores)
selection_probabilities = [score / total_fitness for score in fitness_scores]
new_population = []
for _ in range(len(population