ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

scikit-opt 群智能算法库实战指南:GA/PSO/SA/ACA/IA/AFSA/DE 与 UDF 扩展机制全解析

scikit-opt 群智能算法库实战指南:GA/PSO/SA/ACA/IA/AFSA/DE 与 UDF 扩展机制全解析 scikit-opt 群智能算法库实战指南GA/PSO/SA/ACA/IA/AFSA/DE 与 UDF 扩展机制全解析【免费下载链接】scikit-optGenetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony Optimization Algorithm,Immune Algorithm, Artificial Fish Swarm Algorithm, Differential Evolution and TSP(Traveling salesman)项目地址: https://gitcode.com/GitHub_Trending/sci/scikit-optscikit-opt 是一个纯 Python 实现的群智能优化算法库囊括遗传算法GA、粒子群优化PSO、模拟退火SA、蚁群算法ACA、免疫算法IA、人工鱼群算法AFSA与差分进化DE并针对 TSP 旅行商问题提供多个专用求解器。本文以 docs/en/README.md 为主线结合仓库源码与 examples 目录中的可运行示例系统讲解从安装、UDF 自定义算子、断点续跑、四种加速模式到七大类算法的完整实战流程读完即可在科研与工程场景中直接套用。安装与项目结构scikit-opt 支持 Python 3.5可通过 pip 一键安装pip install scikit-opt如需使用当前开发版源码则克隆后以本地安装方式引入git clone gitgithub.com:guofei9987/scikit-opt.git cd scikit-opt pip install .仓库的核心实现集中在sko/目录每个算法一个独立模块GA.py、PSO.py、SA.py、DE.py、ACA.py、IA.py、AFSA.py公共基类SkoBase位于 base.py算子库交叉、变异、排名、选择位于 operators/全部示例代码在 examples/ 目录下可运行。安装后即可按from sko.GA import GA的方式导入使用。四大核心特性Feature 1UDF 用户自定义算子机制UDFUser Defined Function允许用户替换 GA 内部的核心算子是 scikit-opt 最具扩展性的设计。完整示例见 examples/demo_ga_udf.py。第一步定义自己的算子例如一种锦标赛选择算子def selection_tournament(algorithm, tourn_size): FitV algorithm.FitV sel_index [] for i in range(algorithm.size_pop): aspirants_index np.random.choice(range(algorithm.size_pop), sizetourn_size) sel_index.append(max(aspirants_index, keylambda i: FitV[i])) algorithm.Chrom algorithm.Chrom[sel_index, :] # next generation return algorithm.Chrom第二步照常构建 GA 对象import numpy as np from sko.GA import GA, GA_TSP demo_func lambda x: x[0] ** 2 (x[1] - 0.05) ** 2 (x[2] - 0.5) ** 2 ga GA(funcdemo_func, n_dim3, size_pop100, max_iter500, prob_mut0.001, lb[-1, -10, -5], ub[2, 10, 2], precision[1e-7, 1e-7, 1])第三步通过register注册自定义算子ga.register(operator_nameselection, operatorselection_tournament, tourn_size3)register的底层实现在 base.py它把传入的算子函数包装成绑定到算法实例上的方法并允许通过*args/**kwargs传递额外参数如tourn_size3返回self以支持链式调用。也可以直接注册 scikit-opt 内置算子只需一行链式写法from sko.operators import ranking, selection, crossover, mutation ga.register(operator_nameranking, operatorranking.ranking). \ register(operator_namecrossover, operatorcrossover.crossover_2point). \ register(operator_namemutation, operatormutation.mutation)之后正常调用run()即可best_x, best_y ga.run() print(best_x:, best_x, \n, best_y:, best_y)目前 UDF 机制支持 GA 的四个环节crossover交叉、mutation变异、selection选择、ranking排名。仓库在 operators/ 下内置了十余种算子例如crossover_2point/crossover_2point_bit/crossover_pmx、mutation/mutation_reverse/mutation_swap、selection_tournament_faster等均可作为自定义算子的参考实现。进阶玩法直接继承 GA 类覆写算子方法适合需要固化自定义算法的用户class MyGA(GA): def selection(self, tourn_size3): FitV self.FitV sel_index [] for i in range(self.size_pop): aspirants_index np.random.choice(range(self.size_pop), sizetourn_size) sel_index.append(max(aspirants_index, keylambda i: FitV[i])) self.Chrom self.Chrom[sel_index, :] # next generation return self.Chrom ranking ranking.ranking demo_func lambda x: x[0] ** 2 (x[1] - 0.05) ** 2 (x[2] - 0.5) ** 2 my_ga MyGA(funcdemo_func, n_dim3, size_pop100, max_iter500, lb[-1, -10, -5], ub[2, 10, 2], precision[1e-7, 1e-7, 1]) best_x, best_y my_ga.run() print(best_x:, best_x, \n, best_y:, best_y)从源码角度看GA类的默认算子绑定在 GA.pyranking ranking.ranking、selection selection.selection_tournament_faster、crossover crossover.crossover_2point_bit、mutation mutation.mutation继承覆写或register注册均可无缝替换。Feature 2断点续跑Continue to Run版本 0.3.6 起新增的特性算法对象可以分段运行后续迭代会基于前面的状态继续无需重新初始化。from sko.GA import GA func lambda x: x[0] ** 2 ga GA(funcfunc, n_dim1) ga.run(10) # 先跑 10 代 ga.run(20) # 再基于前面 10 代的结果继续跑 20 代run(max_iterNone)的实现在 GA.py它通过self.max_iter max_iter or self.max_iter动态更新迭代次数种群Chrom作为实例属性被保留因此分段调用天然衔接。同样的模式也适用于PSO.run()见 PSO.py适合长任务分阶段调试与观察收敛过程。Feature 3四种加速模式Accelerate针对目标函数计算代价高的场景scikit-opt 提供四种加速手段vectorization向量化、multithreading多线程、multiprocessing多进程、cached缓存。完整基准示例见 examples/example_function_modes.py。通过set_run_mode切换模式实现在 tools.pyfrom sko.tools import set_run_mode def obj_func(p): x1, x2 p x np.square(x1) np.square(x2) return 0.5 (np.square(np.sin(x)) - 0.5) / np.square(1 0.001 * x) set_run_mode(obj_func, multithreading) # 或 multiprocessing / cached ga GA(funcobj_func, n_dim2, size_pop10, max_iter5, lb[-1, -1], ub[1, 1], precision1e-7) best_x, best_y ga.run()各模式使用要点如下模式适用场景说明common默认模式逐样本 for 循环调用目标函数vectorization目标函数本身可向量化目标函数需改为接收二维数组x1, x2 p[:, 0], p[:, 1]见示例中obj_func2的写法multithreadingIO 密集型任务底层用multiprocessing.dummy.Pool线程池n_processes0表示使用全部 CPUmultiprocessingCPU 密集型任务底层用multiprocessing.PoolWindows 下会自动降级为多线程cached目标函数对相同输入反复求值用functools.lru_cache缓存结果避免重复计算模式分发与转换逻辑在 tools.py 的func_transformer中完成注意parallel是multithreading的别名。示例脚本同时给出了 io 密集与 cpu 密集两类任务下各模式的耗时对比方法可直接运行python examples/example_function_modes.py复现。Feature 4GPU 计算实验性GPU 加速正在开发中官方计划在 1.0.0 版本趋于稳定。目前 GA 已提供基于 PyTorch 的实验性支持示例见 examples/demo_ga_gpu.pyimport torch from sko.GA import GA device torch.device(cuda:0 if torch.cuda.is_available() else cpu) ga GA(funcschaffer, n_dim2, size_pop50, max_iter800, lb[-1, -1], ub[1, 1], precision1e-7) ga.to(devicedevice) # 将种群 Chrom 迁移到 GPU best_x, best_y ga.run()GA.to(device)的实现见 GA.py将染色体转为torch.tensor后用 GPU 版算子替换变异与交叉operators_gpu.mutation_gpu、crossover_gpu.crossover_2point_bit。需要注意的是目标函数本身仍以 NumPy 计算算子在做chrom2x时会先转回 CPU且未安装 PyTorch 时该方法会打印提示并原样返回。Quick Start七类算法快速上手1. 差分进化Differential EvolutionStep1定义问题。以下示例在x1²x2²x3²目标下引入等式与不等式约束 min f(x1, x2, x3) x1^2 x2^2 x3^2 s.t. x1*x2 1 x1*x2 5 x2 x3 1 0 x1, x2, x3 5 def obj_func(p): x1, x2, x3 p return x1 ** 2 x2 ** 2 x3 ** 2 constraint_eq [ lambda x: 1 - x[1] - x[2] ] constraint_ueq [ lambda x: 1 - x[0] * x[1], lambda x: x[0] * x[1] - 5 ]Step2执行 DE完整代码见 examples/demo_de.pyfrom sko.DE import DE de DE(funcobj_func, n_dim3, size_pop50, max_iter800, lb[0, 0, 0], ub[5, 5, 5], constraint_eqconstraint_eq, constraint_ueqconstraint_ueq) best_x, best_y de.run() print(best_x:, best_x, \n, best_y:, best_y)从源码看DE 的实现在 DE.py变异算子生成V[i]X[r1]F*(X[r2]-X[r3])F默认 0.5越界时用随机值重采样交叉算子按概率prob_mut默认 0.3混合V与X选择算子采用贪心策略保留更优个体。2. 遗传算法Genetic AlgorithmStep1定义目标函数示例选用具有大量局部极小值的 Schaffer 函数全局最小值在(0,0)值为 0import numpy as np def schaffer(p): This function has plenty of local minimum, with strong shocks global minimum at (0,0) with value 0 https://en.wikipedia.org/wiki/Test_functions_for_optimization x1, x2 p part1 np.square(x1) - np.square(x2) part2 np.square(x1) np.square(x2) return 0.5 (np.square(np.sin(part1)) - 0.5) / np.square(1 0.001 * part2)Step2执行 GA 并查看收敛历史完整代码见 examples/demo_ga.pyfrom sko.GA import GA ga GA(funcschaffer, n_dim2, size_pop50, max_iter800, prob_mut0.001, lb[-1, -1], ub[1, 1], precision1e-7) best_x, best_y ga.run() print(best_x:, best_x, \n, best_y:, best_y)import pandas as pd import matplotlib.pyplot as plt Y_history pd.DataFrame(ga.all_history_Y) fig, ax plt.subplots(2, 1) ax[0].plot(Y_history.index, Y_history.values, ., colorred) Y_history.min(axis1).cummin().plot(kindline) plt.show()GA 参数说明见 GA.py 的类文档func为目标函数输入解向量输出标量越小越好n_dim为变量维度size_pop为种群大小源码断言必须为偶数max_iter为最大迭代代数默认 200prob_mut为变异概率01默认 0.001lb/ub为每个变量的下/上界precision为每个变量的编码精度可为标量或数组另有constraint_eq/constraint_ueq等式与不等式约束、early_stop提前终止、n_processes并行进程数。GA 采用格雷码对染色体编码每个变量占用的基因位数由Lind ceil(log2((ub-lb)/precision 1))计算并针对整数精度场景做了边界扩展处理。2.2 遗传算法求解 TSP 问题GA_TSP通过重载crossover部分匹配交叉 PMX与mutation反转变异算子来求解旅行商问题见 GA.py。Step1准备点坐标与距离矩阵完整代码见 examples/demo_ga_tsp.pyimport numpy as np from scipy import spatial import matplotlib.pyplot as plt num_points 50 points_coordinate np.random.rand(num_points, 2) # generate coordinate of points distance_matrix spatial.distance.cdist(points_coordinate, points_coordinate, metriceuclidean) def cal_total_distance(routine): The objective function. input routine, return total distance. cal_total_distance(np.arange(num_points)) num_points, routine.shape return sum([distance_matrix[routine[i % num_points], routine[(i 1) % num_points]] for i in range(num_points)])Step2执行 GA_TSPfrom sko.GA import GA_TSP ga_tsp GA_TSP(funccal_total_distance, n_dimnum_points, size_pop50, max_iter500, prob_mut1) best_points, best_distance ga_tsp.run()Step3绘图展示路径与收敛曲线fig, ax plt.subplots(1, 2) best_points_ np.concatenate([best_points, [best_points[0]]]) best_points_coordinate points_coordinate[best_points_, :] ax[0].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], o-r) ax[1].plot(ga_tsp.generation_best_Y) plt.show()3. 粒子群优化PSOStep1定义目标函数完整代码见 examples/demo_pso.pydef demo_func(x): x1, x2, x3 x return x1 ** 2 (x2 - 0.05) ** 2 x3 ** 2Step2执行 PSOfrom sko.PSO import PSO pso PSO(funcdemo_func, n_dim3, pop40, max_iter150, lb[0, -1, 0.5], ub[1, 1, 1], w0.8, c10.5, c20.5) pso.run() print(best_x is , pso.gbest_x, best_y is, pso.gbest_y)Step3绘制最优值历史曲线import matplotlib.pyplot as plt plt.plot(pso.gbest_y_hist) plt.show()PSO 的核心参数见 PSO.pyw为惯性权重默认 0.8c1、c2分别为个体认知与社会学习系数均默认 0.5速度与位置更新遵循标准公式V w*V c1*r1*(pbest-X) c2*r2*(gbest-X)位置越界时被裁剪回lb/ub见 PSO.py。算法结束后通过属性gbest_x、gbest_y直接读取全局最优。3.2 带非线性约束的 PSO如需加入形如(x[0] - 1) ** 2 (x[1] - 0) ** 2 - 0.5 ** 2 0的非线性不等式约束只需传入constraint_ueqconstraint_ueq ( lambda x: (x[0] - 1) ** 2 (x[1] - 0) ** 2 - 0.5 ** 2 , ) pso PSO(funcdemo_func, n_dim2, pop40, max_itermax_iter, lb[-2, -2], ub[2, 2] , constraint_ueqconstraint_ueq)constraint_ueq以元组传入可以添加多个非线性约束每个约束函数要求返回不超过 0 时视为可行解。约束检查在个体最优更新时执行见 PSO.py 的check_constraint与update_pbest。PSO 的三维动态动画示例见 examples/demo_pso_ani.py。4. 模拟退火SA4.1 多元函数优化Step1定义目标函数完整代码见 examples/demo_sa.pydemo_func lambda x: x[0] ** 2 (x[1] - 0.05) ** 2 x[2] ** 2Step2执行 SAfrom sko.SA import SA sa SA(funcdemo_func, x0[1, 1, 1], T_max1, T_min1e-9, L300, max_stay_counter150) best_x, best_y sa.run() print(best_x:, best_x, best_y, best_y)Step3绘制最优值累计下降曲线import matplotlib.pyplot as plt import pandas as pd plt.plot(pd.DataFrame(sa.best_y_history).cummin(axis0)) plt.show()SA 的参数见 SA.pyx0为初始解T_max/T_min为初始与终止温度需满足T_max T_min 0L为每个温度下的迭代链长max_stay_counter为连续无改进的降温轮数上限超过即提前停止冷却机制。4.2 SA 求解 TSPStep2执行SA_TSP完整代码见 examples/demo_sa_tsp.pyfrom sko.SA import SA_TSP sa_tsp SA_TSP(funccal_total_distance, x0range(num_points), T_max100, T_min1, L10 * num_points) best_points, best_distance sa_tsp.run() print(best_points, best_distance, cal_total_distance(best_points))Step3绘图展示距离收敛曲线与最终路径from matplotlib.ticker import FormatStrFormatter fig, ax plt.subplots(1, 2) best_points_ np.concatenate([best_points, [best_points[0]]]) best_points_coordinate points_coordinate[best_points_, :] ax[0].plot(sa_tsp.best_y_history) ax[0].set_xlabel(Iteration) ax[0].set_ylabel(Distance) ax[1].plot(best_points_coordinate[:, 0], best_points_coordinate[:, 1], markero, markerfacecolorb, colorc, linestyle-) ax[1].xaxis.set_major_formatter(FormatStrFormatter(%.3f)) ax[1].yaxis.set_major_formatter(FormatStrFormatter(%.3f)) ax[1].set_xlabel(Longitude) ax[1].set_ylabel(Latitude) plt.show()SA_TSP的新解生成采用 swap / reverse / transpose 三种路径扰动策略随机切换见 SA.py。此外scikit-opt 内置Fast、Boltzmann、Cauchy三种模拟退火变体SA默认即SAFast见 SA.py分别对应不同的邻域生成与降温策略指数降温、对数降温、倒数降温参数如hop、learn_rate、quench可在构造时通过kwargs传入详细用法见 docs/en/more_sa.md。5. 蚁群算法ACA求解 TSPACA 需要显式传入距离矩阵完整代码见 examples/demo_aca_tsp.pyfrom sko.ACA import ACA_TSP aca ACA_TSP(funccal_total_distance, n_dimnum_points, size_pop50, max_iter200, distance_matrixdistance_matrix) best_x, best_y aca.run()6. 免疫算法IA求解 TSPIA 用于 TSP 的示例完整代码见 examples/demo_ia.py参数T与alpha控制免疫浓度调节与变异强度from sko.IA import IA_TSP ia_tsp IA_TSP(funccal_total_distance, n_dimnum_points, size_pop500, max_iter800, prob_mut0.2, T0.7, alpha0.95) best_points, best_distance ia_tsp.run() print(best routine:, best_points, best_distance:, best_distance)7. 人工鱼群算法AFSAAFSA 通过鱼群的觅食、聚群、追尾行为寻优完整代码见 examples/demo_afsa.pydef func(x): x1, x2 x return 1 / x1 ** 2 x1 ** 2 1 / x2 ** 2 x2 ** 2 from sko.AFSA import AFSA afsa AFSA(func, n_dim2, size_pop50, max_iter300, max_try_num100, step0.5, visual0.3, q0.98, delta0.5) best_x, best_y afsa.run() print(best_x, best_y)其中max_try_num为每次觅食最大尝试次数step为鱼移动步长visual为鱼视野半径q为视野衰减因子delta为拥挤度因子。扩展阅读与后续路线参数详解更多算法参数的取值建议与对比见 docs/en/args.mdGA 进阶GA 更多技巧与变体见 docs/en/more_ga.mdPSO 进阶见 docs/en/more_pso.mdSA 进阶三种退火变体对比见 docs/en/more_sa.md加速实践四种加速模式的完整对照实验见 examples/example_function_modes.py曲线拟合基于群智能算法做曲线拟合的实战示例见 docs/en/curve_fitting.md学术应用仓库记录的多篇基于 scikit-opt 的学术论文应用如 IEEE TIFS 的恶意软件频谱可视化、Energy Reports 的强化学习最优潮流生成器等可在根目录 README.md 的 Projects using scikit-opt 一节中查阅覆盖网络安全、电力系统、材料合成、推荐系统等多个领域可作为算法选型与论文引用的参考。【免费下载链接】scikit-optGenetic Algorithm, Particle Swarm Optimization, Simulated Annealing, Ant Colony Optimization Algorithm,Immune Algorithm, Artificial Fish Swarm Algorithm, Differential Evolution and TSP(Traveling salesman)项目地址: https://gitcode.com/GitHub_Trending/sci/scikit-opt创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表