遗传算法(Genetic Algorithm, GA)是一种模拟自然选择和遗传学原理的搜索启发式算法。它们通常用于解决优化和搜索问题,基于“适者生存”的自然选择概念,通过选择、交叉(杂交)、变异操作在一系列迭代中逐步优化解决方案。
遗传算法的主要组成部分:
- 种群(Population):解决方案的集合。
- 适应度函数(Fitness Function):衡量个体适应环境的好坏。
- 选择(Selection):选择适应度好的个体繁殖。
- 交叉(Crossover):交换某些个体的部分基因,产生新的个体。
- 变异(Mutation):随机改变个体的某些基因,增加种群的多样性。
Python 实现:简单遗传算法
案例分析:最大化一个简单的数学函数
我们将使用遗传算法来最大化函数 𝑓(𝑥)=𝑥^2,其中 𝑥x 在某个范围内,例如 [0, 31]。
Python 实现:
import random
# 适应度函数
def fitness(x):
return x ** 2
# 选择
def select(population, scores, k=3):
# 轮盘赌选择
selection_ix = random.randint(0, len(population)-1)
for ix in random.sample(range(len(population)), k):
if scores[ix] > scores[selection_ix]:
selection_ix = ix
return population[selection_ix]
# 交叉
def crossover(p1, p2, r_cross):
# 单点交叉
c1, c2 = p1.copy(), p2.copy()
if random.random() < r_cross:
pt = random.randint(1, len(p1)-2)
c1 = p1[:pt] + p2[pt:]
c2 = p2[:pt] + p1[pt:]
return [c1, c2]
# 变异
def mutation(bitstring, r_mut):
for i in range(len(bitstring)):
if random.random() < r_mut:
bitstring[i] = 1 - bitstring[i]
# 遗传算法
def genetic_algorithm(objective, n_bits, n_iter, n_pop, r_cross, r_mut):
# 初始种群
population = [[random.randint(0, 1) for _ in range(n_bits)] for _ in range(n_pop)]
best, best_eval = 0, objective(int("".join(str(x) for x in population[0]), 2))
for gen in range(n_iter):
# 评估所有候选
scores = [objective(int("".join(str(x) for x in candidate), 2)) for candidate in population]
for i in range(n_pop):
if scores[i] > best_eval:
best, best_eval = population[i], scores[i]
print(">%d, new best f(%s) = %f" % (gen, "".join(str(x) for x in population[i]), scores[i]))
# 选择下一代
selected = [select(population, scores) for _ in range(n_pop)]
# 创建下一代
children = list()
for i in range(0, n_pop, 2):
p1, p2 = selected[i], selected[i+1]