You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于遗传算法优化神经网络:如何批量评估候选参数?

支持批量种群评估的遗传算法实现方案

针对你的需求(利用TensorFlow批量预测提升优化效率),以下几个开源库原生支持批量评估整个候选种群,完全适配你的向量化目标函数:

1. PyGAD(推荐,简洁高效)

PyGAD是专门针对深度学习场景优化的遗传算法库,原生支持批量评估种群,代码量少且贴合你的神经网络替代模型场景。

步骤:

  • 先写出向量化的目标函数:
import numpy as np

def batch_func_to_opt(X, TRANS_MIN_BV=TRANS_MIN_BV, SUBS_VAL=100, model=model):
    # X: 形状为(n_samples, n_features)的参数矩阵
    y = model.predict(X)  # TensorFlow直接批量处理输入
    y = y[:, :, 0].swapaxes(0, 1)  # 调整维度匹配BV和Rsp的输出
    # 应用约束:BV低于阈值时返回SUBS_VAL,否则返回Rsp
    mask = y[0] > TRANS_MIN_BV
    return np.where(mask, y[1], SUBS_VAL)
  • 配置PyGAD并运行:
import pygad

# 定义批量适应度函数(PyGAD支持直接使用种群矩阵)
def fitness_func(ga_instance, solution, solution_idx):
    # 直接获取整个种群的参数矩阵
    X = ga_instance.population
    fitness_vals = batch_func_to_opt(X)
    # PyGAD默认最大化适应度,因此取负数转为最小化Rsp的目标
    return -fitness_vals

# 参数边界:假设你的trans_bounds是(4,2)的数组,转为每个维度的上下限
bounds = trans_bounds.T.tolist()
gene_space = [{"low": low, "high": high} for low, high in bounds]

# 初始化遗传算法实例
ga_instance = pygad.GA(
    num_generations=500,  # 迭代次数
    num_parents_mating=20,  # 参与交配的父代数量
    fitness_func=fitness_func,
    sol_per_pop=100,  # 种群大小
    num_genes=4,  # 参数维度
    gene_space=gene_space,
    parent_selection_type="sss",
    crossover_type="single_point",
    mutation_type="random",
    mutation_percent_genes=10,
    seed=1
)

# 启动优化
ga_instance.run()

# 获取最优结果
best_params, best_fitness, _ = ga_instance.best_solution()
print("最优参数:", best_params)
print("最优Rsp值:", -best_fitness)  # 还原为原始Rsp值

2. DEAP(灵活定制性强)

DEAP是一个高度灵活的进化算法框架,支持自定义所有进化环节,可直接实现种群级的批量评估。

步骤:

  • 复用上述的batch_func_to_opt函数,然后配置DEAP:
import random
import numpy as np
from deap import base, creator, tools, algorithms

# 定义优化目标:最小化Rsp,因此权重设为-1.0
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMin)

toolbox = base.Toolbox()
n_dims = 4  # 参数维度
bounds = trans_bounds.T.tolist()

# 初始化个体:每个参数在对应边界内随机采样
def init_individual():
    return creator.Individual([random.uniform(low, high) for low, high in bounds])

toolbox.register("individual", init_individual)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

# 注册批量评估函数
def evaluate_batch(population):
    # 将种群转为numpy矩阵
    X = np.array(population)
    fitness_vals = batch_func_to_opt(X)
    # DEAP要求返回每个个体的适应度元组
    return [(val,) for val in fitness_vals]

toolbox.register("evaluate", evaluate_batch)

# 配置遗传操作
toolbox.register("mate", tools.cxBlend, alpha=0.5)  # 混合交叉
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=0.1, indpb=0.2)  # 高斯变异
toolbox.register("select", tools.selTournament, tournsize=3)  # 锦标赛选择

# 运行优化
def main():
    pop = toolbox.population(n=100)  # 种群大小
    hof = tools.HallOfFame(1)  # 保存最优个体
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", np.mean)
    stats.register("min", np.min)
    
    pop, log = algorithms.eaSimple(
        pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=500,
        stats=stats, halloffame=hof, verbose=True
    )
    
    print("最优个体:", hof[0])
    print("最优Rsp值:", hof[0].fitness.values[0])
    return pop, log, hof

if __name__ == "__main__":
    pop, log, hof = main()

3. Optuna(超参数优化+遗传算法采样)

Optuna主要用于超参数优化,但通过NSGAIISampler可以实现遗传算法优化,同时支持批量评估或并行计算,适合需要更多调参工具链的场景。

批量评估示例:

import optuna

# 批量目标函数
def batch_objective(trials):
    # 生成批量参数矩阵
    X = np.array([
        [trial.suggest_float(f"x{i}", bounds[i][0], bounds[i][1]) for i in range(4)]
        for trial in trials
    ])
    fitness_vals = batch_func_to_opt(X)
    # 为每个trial设置结果
    for trial, val in zip(trials, fitness_vals):
        trial.report(val, step=0)
        trial.set_user_attr("fitness", val)

# 使用NSGA-II遗传算法采样器
study = optuna.create_study(
    direction="minimize",
    sampler=optuna.samplers.NSGAIISampler(seed=1)
)

# 批量运行优化(Optuna 3.0+支持)
study.optimize_batch(
    batch_objective,
    n_trials=5000,  # 总评估次数
    batch_size=100  # 每次批量评估的样本数
)

print("最优参数:", study.best_params)
print("最优Rsp值:", study.best_value)

补充说明

  • scipy的differential_evolution仅支持单样本评估,其workers参数是并行处理单个样本,无法利用TensorFlow的批量预测优势,因此不推荐继续使用。
  • 上述方案中,PyGAD最适合你的场景,代码简洁且直接适配批量神经网络预测;DEAP适合需要高度定制进化逻辑的场景。

内容的提问来源于stack exchange,提问作者Ondrej_D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 03:48:09