Python5.2打卡(day12)

超参数调整专题2

  1. 三种启发式算法的示例代码:遗传算法、粒子群算法、退火算法
  2. 学习优化算法的思路(避免浪费无效时间)

作业:今天以自由探索的思路为主,尝试检索资料、视频、文档,用尽可能简短但是清晰的语言看是否能说清楚这三种算法每种算法的实现逻辑,帮助更深入的理解。

以下是对三种启发式算法的核心逻辑解析及代码示例,以 “寻找函数最小值” 为统一场景(目标函数 f(x) = x²),帮助快速理解其差异。


一、算法核心逻辑对比

算法 核心思想 关键操作 适用场景
遗传算法 模拟生物进化,通过种群迭代筛选最优解 选择、交叉、变异 离散/连续、多峰优化
粒子群算法 模拟鸟群协作,粒子共享信息寻找最优 速度更新、跟踪个体/群体最优 连续空间、快速收敛
退火算法 模拟金属冷却,概率性接受劣解防局部最优 温度下降、Metropolis准则 单一解、复杂地形优化

二、算法实现详解 & 代码

1. 遗传算法 (GA)

逻辑:通过交叉变异生成新解,保留适应度高的个体。

import random

def genetic_algorithm(pop_size=50, generations=100):
    # 初始化种群 (这里简化为一维实数编码)
    population = [random.uniform(-10, 10) for _ in range(pop_size)]
    
    for _ in range(generations):
        # 计算适应度 (目标是最小化 f(x)=x²)
        fitness = [1/(x**2 + 1e-6) for x in population]  # 防止除以0
        
        # 选择 (轮盘赌选择父代)
        parents = random.choices(population, weights=fitness, k=pop_size)
        
        # 交叉 (单点交叉,这里简化为父代平均值)
        offspring = [(parents[i] + parents[i+1])/2 for i in range(0, pop_size, 2)]
        
        # 变异 (随机扰动)
        population = [x + random.uniform(-0.5, 0.5) for x in offspring]
    
    # 返回最优解
    return min(population, key=lambda x: x**2)

print(genetic_algorithm())  # 输出接近 0
2. 粒子群算法 (PSO)

逻辑:粒子通过跟踪个体历史最优和群体最优更新速度和位置。

import random

class Particle:
    def __init__(self):
        self.position = random.uniform(-10, 10)
        self.velocity = 0
        self.best_pos = self.position

def pso(num_particles=30, iterations=100):
    particles = [Particle() for _ in range(num_particles)]
    global_best = min(particles, key=lambda p: p.position**2).position
    
    for _ in range(iterations):
        for p in particles:
            # 更新速度和位置
            inertia = 0.5 * p.velocity
            cognitive = 1.5 * random.random() * (p.best_pos - p.position)
            social = 1.5 * random.random() * (global_best - p.position)
            p.velocity = inertia + cognitive + social
            p.position += p.velocity
            
            # 更新个体最优和全局最优
            if p.position**2 < p.best_pos**2:
                p.best_pos = p.position
                if p.position**2 < global_best**2:
                    global_best = p.position
    return global_best

print(pso())  # 输出接近 0
3. 模拟退火算法 (SA)

逻辑:以概率接受劣解,逐步降低“温度”减少随机性。

import random
import math

def simulated_annealing(initial_temp=1000, cooling_rate=0.95):
    current = random.uniform(-10, 10)
    current_energy = current**2
    best = current
    
    temp = initial_temp
    while temp > 1e-5:
        # 生成新解
        new = current + random.uniform(-1, 1)
        new_energy = new**2
        
        # Metropolis准则决定是否接受
        if new_energy < current_energy or random.random() < math.exp((current_energy - new_energy)/temp):
            current, current_energy = new, new_energy
            if current_energy < best**2:
                best = current
        
        # 降温
        temp *= cooling_rate
    
    return best

print(simulated_annealing())  # 输出接近 0

三、学习优化算法的思路

  1. 先理解核心比喻:将算法与自然现象(进化、鸟群、退火)对应,快速抓住核心思想。

  2. 手动推演小例子:在纸上模拟2-3次迭代,观察解如何变化。

  3. 调参实战:修改代码中的参数(如种群大小、温度衰减率),观察对结果的影响。

  4. 换问题验证:将目标函数改为其他形式(如 sin(x)+cos(2x)),测试算法鲁棒性。


四、关键优化点总结

  • 遗传算法:交叉/变异的设计直接影响搜索能力。

  • 粒子群算法:惯性权重和加速系数决定收敛速度。

  • 退火算法:降温速率过快易陷入局部最优,过慢则计算量大。

@浙大疏锦行 

你可能感兴趣的:(python训练营打卡,python)