遗传算法代码介绍
遗传算法是一种模拟自然进化过程的优化算法,主要用于求解复杂的优化问题。其基本思想是通过模拟自然界生物进化过程,不断地迭代搜索最优解。
遗传算法的主要步骤包括:
-
初始化种群:随机生成一定数量的个体作为初始种群。
-
评估适应度:对每个个体进行评估,计算其适应度值,用于后续的选择操作。
-
选择操作:根据适应度值选择优秀的个体,保留下一代。
-
交叉操作:对选出的个体进行交叉操作,生成新的个体。
-
变异操作:对新生成的个体进行变异操作,引入新的遗传信息。
-
更新种群:将新生成的个体加入到种群中,替代原来的个体。
-
判断终止条件:当达到预设的迭代次数或者找到满足要求的解时,停止迭代。
下面是一个简单的遗传算法代码实现:
import random
# 定义问题
def fitness_function(x):
return x ** 2
# 初始化种群
def init_population(pop_size, chromo_size):
population = []
for i in range(pop_size):
chromo = []
for j in range(chromo_size):
chromo.append(random.randint(0, 1))
population.append(chromo)
return population
# 计算适应度值
def calc_fitness(population):
fitness_values = []
for chromo in population:
x = int(''.join(map(str, chromo)), 2)
fitness_values.append(fitness_function(x))
return fitness_values
# 选择操作
def selection(population, fitness_values):
parents = []
for i in range(len(population)):
idx1 = random.randint(0, len(population)-1)
idx2 = random.randint(0, len(population)-1)
if fitness_values[idx1] < fitness_values[idx2]:
parents.append(population[idx1])
else:
parents.append(population[idx2])
return parents
# 交叉操作
def crossover(parents, pc):
children = []
for i in range(0, len(parents), 2):
p1 = parents[i]
p2 = parents[i+1]
if random.random() < pc:
c1 = p1[:len(p1)//2] + p2[len(p2)//2:]
c2 = p2[:len(p2)//2] + p1[len(p1)//2:]
children.append(c1)
children.append(c2)
else:
children.append(p1)
children.append(p2)
return children
# 变异操作
def mutation(children, pm):
for i in range(len(children)):
for j in range(len(children[i])):
if random.random() < pm:
children[i][j] = 1 - children[i][j]
return children
# 更新种群
def update_population(population, children):
population = population[:len(population)//2] + children[:len(population)//2]
return population
# 遗传算法主函数
def genetic_algorithm(pop_size, chromo_size, pc, pm, max_iter):
population = init_population(pop_size, chromo_size)
for i in range(max_iter):
fitness_values = calc_fitness(population)
parents = selection(population, fitness_values)
children = crossover(parents, pc)
children = mutation(children, pm)
population = update_population(population, children)
best_chromo = population[0]
best_fitness = fitness_function(int(''.join(map(str, best_chromo)), 2))
for chromo in population:
x = int(''.join(map(str, chromo)), 2)
fitness = fitness_function(x)
if fitness < best_fitness:
best_chromo = chromo
best_fitness = fitness
return best_chromo, best_fitness
# 测试
if __name__ == '__main__':
best_chromo, best_fitness = genetic_algorithm(pop_size=100, chromo_size=10, pc=0.8, pm=0.01, max_iter=1000)
x = int(''.join(map(str, best_chromo)), 2)
print('x =', x)
print('f(x) =', best_fitness)
该代码实现了一个简单的遗传算法,用于求解一个函数的最小值。其中,init_population函数用于初始化种群,calc_fitness函数用于计算适应度值,selection函数用于选择操作,crossover函数用于交叉操作,mutation函数用于变异操作,update_population函数用于更新种群。最后,genetic_algorithm函数用于执行遗传算法的主循环。在测试中,程序会输出求解得到的最小值及其对应的自变量值。
原文地址: https://www.cveoy.top/t/topic/bk96 著作权归作者所有。请勿转载和采集!