Python实战开发及案例分析(16)—— 遗传算法

        遗传算法(Genetic Algorithm, GA)是一种模拟自然选择和遗传学原理的搜索启发式算法。它们通常用于解决优化和搜索问题,基于“适者生存”的自然选择概念,通过选择、交叉(杂交)、变异操作在一系列迭代中逐步优化解决方案。

遗传算法的主要组成部分:

  1. 种群(Population):解决方案的集合。
  2. 适应度函数(Fitness Function):衡量个体适应环境的好坏。
  3. 选择(Selection):选择适应度好的个体繁殖。
  4. 交叉(Crossover):交换某些个体的部分基因,产生新的个体。
  5. 变异(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]
      
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贾贾乾杯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值