一、概念
遗传算法(Genetic Algorithm)是一种受生物进化理论启发的优化算法。它模拟自然界中的进化过程,通过对问题空间中的个体进行交叉、变异和选择等操作,逐步搜索问题的最优解或近似最优解。
遗传算法的基本思想是通过模拟基因遗传、交叉和突变等操作,对候选解进行迭代改进。它基于种群的概念,每个个体表示问题空间中的一个可能解。每个个体都有一个适应度值,用来评估其在解空间中的优劣。
总之,遗传算法广泛应用于解决优化问题,例如在机器学习中的特征选择、参数调优等问题,以及在工程、经济和计划等领域的调度、路径规划和布局优化等问题。
值得注意的是,遗传算法并非适用于所有问题,对于问题的特性和约束条件需要进行合理的建模和设计才能有效地应用遗传算法,具体问题具体分析。
二、实现步骤
遗传算法的主要步骤如下:
(1)初始化种群:根据问题的要求,随机生成一组个体作为初始种群。
(2)评估适应度:计算每个个体的适应度值,评估其在问题空间中的质量。
(3)选择操作:采用适应度选择策略,以一定的概率选择高适应度个体,并保留到下一代。
(4)交叉操作:选择两个个体作为父亲和母亲,并通过交叉操作产生新的后代个体。
(5)变异操作:对新的后代个体进行变异操作,以增加种群的多样性。
(6)更新种群:将父代个体和后代个体合并,形成新一代的种群。
(7)重复步骤2至步骤6,直到满足终止条件(如达到最大迭代次数或找到满意的解)
总结一下以上步骤:
(1)优化结果与初始条件无关,因为是随机的,在随机范围就好。
(2)一个常见的错误:元素数量不足以满足染色体的编码长度。其实就是,基因的长度的一半要大于等于参数数量。
(3)对于变异操作,要控制好突变概率和迭代次数。
三、小案例
问题:求下述二元函数的最大值:
其中∈ { 1 , 2 , 3 , 4 , 5 , 6 , 7 } , ∈ { 1 , 2 , 3 , 4 , 5 , 6 , 7 }
根据遗传算法步骤,Python代码实现如下:
import random
# 定义问题的参数
x1_values = [1, 2, 3, 4, 5, 6, 7]
x2_values = [1, 2, 3, 4, 5, 6, 7]
chromosome_length = 10 # 基因长度
population_size = 50 # 种群大小
mutation_rate = 0.01 # 突变概率
num_generations = 100 # 迭代次数
# 初始化种群
def initialize_population():
population = []
for _ in range(population_size):
x1_index = random.randint(0, len(x1_values) - 1)
x2_index = random.randint(0, len(x2_values) - 1)
# print("x:",x1_index,x2_index)
chromosome = format(x1_index, '0' + str(chromosome_length // 2) + 'b') + format(x2_index, '0' + str(chromosome_length // 2) + 'b')
population.append(chromosome)
return population
# 将二进制编码转换为对应的实数值
def decode_chromosome(chromosome):
# print('key:',chromosome[:chromosome_length // 2],chromosome[chromosome_length // 2:])
x1_index = int(chromosome[:chromosome_length // 2], 2)
x2_index = int(chromosome[chromosome_length // 2:], 2)
# print('final:', x1_index,x2_index)
if x1_index<len(x1_values) and x2_index<len(x2_values):
x1 = x1_values[x1_index]
x2 = x2_values[x2_index]
return x1, x2
else:
return 0, 0
# 计算适应度函数(即目标函数)
def fitness_function(x1, x2):
return x1**2 + x2**2
# 计算种群的适应度
def calculate_fitness(population):
fitness_values = []
for chromosome in population:
# print('set:',chromosome)
x1, x2 = decode_chromosome(chromosome)
fitness = fitness_function(x1, x2)
fitness_values.append(fitness)
return fitness_values
# 选择操作(使用轮盘赌选择法)
def selection(population, fitness_values):
total_fitness = sum(fitness_values)
probabilities = [fitness / total_fitness for fitness in fitness_values]
selected_population = random.choices(population, probabilities, k=population_size)
return selected_population
# 交叉操作(单点交叉)
def crossover(parent1, parent2):
crossover_point = random.randint(1, chromosome_length - 1)
child1 = parent1[:crossover_point] + parent2[crossover_point:]
child2 = parent2[:crossover_point] + parent1[crossover_point:]
return child1, child2
# 突变操作
def mutation(chromosome):
mutated_chromosome = list(chromosome)
for i in range(chromosome_length):
if random.random() < mutation_rate:
mutated_chromosome[i] = '0' if chromosome[i] == '1' else '1'
return ''.join(mutated_chromosome)
# 遗传算法主函数
def genetic_algorithm():
population = initialize_population()
# print('why:',population)
for generation in range(num_generations):
fitness_values = calculate_fitness(population)
best_fitness = max(fitness_values)
best_chromosome = population[fitness_values.index(best_fitness)]
selected_population = selection(population, fitness_values)
new_population = []
while len(new_population) < population_size:
parent1 = random.choice(selected_population)
parent2 = random.choice(selected_population)
if parent1 != parent2:
child1, child2 = crossover(parent1, parent2)
child1 = mutation(child1)
child2 = mutation(child2)
new_population.extend([child1, child2])
population = new_population
print("Generation:", generation + 1)
print("Best fitness:", best_fitness)
print("Best chromosome:", best_chromosome)
print("---------------------------")
print("Final result:")
print("Best fitness:", best_fitness)
print("Best chromosome:", best_chromosome)
# 执行遗传算法
genetic_algorithm()