Python优化算法07——布谷鸟搜索算法

article/2025/10/5 7:56:17

和前面的系列不同,布谷鸟这里没有现成的Python的包,使用我们需要自己写各种源码模块进行组合,达到布谷鸟搜索算法(CS)的功能。

这里的CS算法是面向过程的编程,都是自定义函数,不涉及类与对象。还是很简单的,知道原理的话可以看得懂的。


布谷鸟代码

# cuckoo_search via levy flight for global optimization
import numpy as np
import scipy.special as sc_special
import random
import timetime_start = time.time()  # 记录开始时间
#a=[]
#生成莱维飞行的步长
def levy_flight(n, m, beta):"""This function implements Levy's flight.---------------------------------------------------Input parameters:n: Number of steps m: Number of dimensionsbeta: Power law index (note: 1 < beta < 2)Output:'n' levy steps in 'm' dimension"""sigma_u = (sc_special.gamma(1+beta)*np.sin(np.pi*beta/2)/(sc_special.gamma((1+beta)/2)*beta*(2**((beta-1)/2))))**(1/beta)sigma_v = 1u =  np.random.normal(0, sigma_u, (n, m))v = np.random.normal(0, sigma_v, (n, m))steps = u/((np.abs(v))**(1/beta))return steps#计算每个鸟巢的适应值(即函数值)
def calc_fitness(fit_func, nests):"""calculate each nest's fitness---------------------------------------------------Input parameters:fit_func: User defined fitness evaluative functionnests:  Nests' locationsOutput:Every nest's fitness"""n, m = nests.shapefitness = np.empty(n)for each_nest in range(n):fitness[each_nest] = fit_func(nests[each_nest])return fitness#产生鸟巢的位置
def generate_nests(n, m, lower_boundary, upper_boundary):"""Generate the nests' locations---------------------------------------------------Input parameters:n: Number of nestsm: Number of dimensionslower_boundary: Lower bounary (example: lower_boundary = (-2, -2, -2))upper_boundary: Upper boundary (example: upper_boundary = (2, 2, 2))Output:generated nests' locations"""lower_boundary = np.array(lower_boundary)upper_boundary = np.array(upper_boundary)nests = np.empty((n, m))for each_nest in range(n):nests[each_nest] = lower_boundary + np.array([np.random.rand() for _ in range(m)]) * (upper_boundary - lower_boundary)return nests#更新鸟巢的位置
def update_nests(fit_func, lower_boundary, upper_boundary, nests, best_nest, fitness, step_coefficient):"""This function is to get new nests' locations and use new better one to replace the old nest---------------------------------------------------Input parameters:fit_func: User defined fitness evaluative functionlower_boundary: Lower bounary (example: lower_boundary = (-2, -2, -2))upper_boundary: Upper boundary (example: upper_boundary = (2, 2, 2))nests: Old nests' locations best_nest: Nest with best fitnessfitness: Every nest's fitnessstep_coefficient:  Step size scaling factor related to the problem's scale (default: 0.1)Output:Updated nests' locations"""lower_boundary = np.array(lower_boundary)upper_boundary = np.array(upper_boundary)n, m = nests.shape# generate steps using levy flightsteps = levy_flight(n, m, 1.5)new_nests = nests.copy()for each_nest in range(n):# coefficient 0.01 is to avoid levy flights becoming too aggresive# and (nest[each_nest] - best_nest) could let the best nest be remainedstep_size = step_coefficient * steps[each_nest] * (nests[each_nest] - best_nest)step_direction = np.random.rand(m)new_nests[each_nest] += step_size * step_direction# apply boundary condtionsnew_nests[each_nest][new_nests[each_nest] < lower_boundary] = lower_boundary[new_nests[each_nest] < lower_boundary]new_nests[each_nest][new_nests[each_nest] > upper_boundary] = upper_boundary[new_nests[each_nest] > upper_boundary]new_fitness = calc_fitness(fit_func, new_nests)nests[new_fitness > fitness] = new_nests[new_fitness > fitness]return nests#按照一定概率抛弃鸟蛋,换巢(局部搜索)
def abandon_nests(nests, lower_boundary, upper_boundary, pa):"""Some cuckoos' eggs are found by hosts, and are abandoned.So cuckoos need to find new nests.---------------------------------------------------Input parameters:nests: Current nests' locationslower_boundary: Lower bounary (example: lower_boundary = (-2, -2, -2))upper_boundary: Upper boundary (example: upper_boundary = (2, 2, 2))pa: Possibility that hosts find cuckoos' eggsOutput:Updated nests' locations"""lower_boundary = np.array(lower_boundary)upper_boundary = np.array(upper_boundary)n, m = nests.shapefor each_nest in range(n):if (np.random.rand() < pa):step_size = np.random.rand() * (nests[np.random.randint(0, n)] - nests[np.random.randint(0, n)])nests[each_nest] += step_size# apply boundary condtionsnests[each_nest][nests[each_nest] < lower_boundary] = lower_boundary[nests[each_nest] < lower_boundary]nests[each_nest][nests[each_nest] > upper_boundary] = upper_boundary[nests[each_nest] > upper_boundary]return nests#算法迭代
def cuckoo_search(n, m, fit_func, lower_boundary, upper_boundary, iter_num = 1000,pa = 0.25, beta = 1.5, step_size = 0.01):"""Cuckoo search function---------------------------------------------------Input parameters:n: Number of nestsm: Number of dimensionsfit_func: User defined fitness evaluative functionlower_boundary: Lower bounary (example: lower_boundary = (-2, -2, -2))upper_boundary: Upper boundary (example: upper_boundary = (2, 2, 2))iter_num: Number of iterations (default: 100) pa: Possibility that hosts find cuckoos' eggs (default: 0.25)beta: Power law index (note: 1 < beta < 2) (default: 1.5)step_size:  Step size scaling factor related to the problem's scale (default: 0.1)Output:The best solution and its value"""# get initial nests' locations nests = generate_nests(n, m, lower_boundary, upper_boundary)fitness = calc_fitness(fit_func, nests)# get the best nest and record itbest_nest_index = np.argmin(fitness)best_fitness = fitness[best_nest_index]best_nest = nests[best_nest_index].copy()for _ in range(iter_num):nests = update_nests(fit_func, lower_boundary, upper_boundary, nests, best_nest, fitness, step_size)nests = abandon_nests(nests, lower_boundary, upper_boundary, pa)fitness = calc_fitness(fit_func, nests)min_nest_index = np.argmin(fitness)min_fitness = fitness[min_nest_index]min_nest = nests[min_nest_index]a.append(min_fitness)if (min_fitness < best_fitness):best_nest = min_nest.copy()best_fitness = min_fitnessreturn (best_nest, best_fitness)

上述代码都是拆分为一个个小函数。最后的cuckoo_search是总体的搜索迭代的函数。

对布谷鸟算法的搜索能力,我们采用 Goldstein-Price函数进行测试。Goldstein-Price函数是二元八次多项式,是一个常见的用来进行算法测试的函数,可以用算法找它的局部最小值。该函数理论在x=0,y=-1处取得最小值3,该函数的公式如下:

进行定义和计算

if __name__=='__main__':def fit_func(nest):x= nest        #return 3*(1-x)**2*np.e**(-x**2-(y+1)**2) - 10*(x/5-x**3-y**5)*np.e**(-x**2-y**2) - (np.e**(-(x+1)**2-y**2))/3return  (1+pow((1+x[0]+x[1]),2)*(19-14*x[0]+3*x[0]*x[0]-14*x[1]+6*x[0]*x[1]+3*x[1]*x[1]))*(30+pow((2*x[0]-3*x[1]),2)*(18-32*x[0]+12*x[0]*x[0]+48*x[1]-36*x[0]*x[1]+27*x[1]*x[1]))best_nest, best_fitness = cuckoo_search(100, 2, fit_func, [-3, -3], [3, 3],iter_num = 1000, step_size = 0.1)time_end = time.time()  # 记录结束时间time_sum = time_end - time_start  # 计算的时间差为程序的执行时间,单位为秒/sprint(time_sum)print('最小值为:%.5f, 在(%.5f, %.5f)处取到!'%(best_fitness, best_nest[0], best_nest[1]))

 可以看到迭代1000次用时4s,还是很快的。和理论的最小值3很接近,x1和x2的值和真实值也还比较接近。

想复用这段代码到别的问题只需要改最后的这个fit_func()就行,返回你要评价的指标,布谷鸟会自动找最小值,并且告诉你参数为多少时取到。


http://chatgpt.dhexx.cn/article/ZPrZxCmO.shtml

相关文章

一个例子入坑布谷鸟算法(附完整py代码)

布谷鸟是比较新的启发式最优化算法,但其与传统的遗传算法,退火算法等相比,被证明收敛速度更快,计算效率更高! 文章目录 本文诞生的缘由布谷鸟算法思想简介更新位置的方式莱维飞行局部随机行走 抛出个栗子一些参数的建议完整的python实现运行结果参考文献 本文诞生的缘由 由于布…

基于布谷鸟搜索算法的函数寻优算法

文章目录 一、理论基础1、算法原理2、算法流程图 二、Matlab代码三、参考文献 一、理论基础 1、算法原理 布谷鸟采用一种特殊的寄生宿主巢穴的方式孕育繁殖,它将孵育的蛋置入寄生宿主的巢穴&#xff0c;让寄生宿主孵化布谷鸟蛋。由于布谷鸟幼雏能发出比寄生宿主幼雏更闪亮的叫…

布谷鸟算法(Cuckoo Search,CS)MATLAB案例详细解析

目录 一、布谷鸟算法理论二、CS算法应用于函数优化1.流程图3.代码解析3.1 主函数 Csmain.m3.2 Levy飞行 func_levy.m3.3 与上一代比较&#xff0c;返回较优的鸟巢 func_bestNestPop.m3.4 根据发现概率&#xff0c;舍弃一个鸟巢并建立一个新鸟巢 func_newBuildNest.m3.5 目标函数…

智能优化算法——布谷鸟搜索算法原理(附代码)

目录 基本概念 算法具体流程 算法流程图 测试函数 优化结果 visual studio2017C代码 基本概念 布谷鸟搜索算法&#xff08;Cuckoo Search&#xff0c;缩写 CS&#xff09;是由剑桥大学杨新社教授和S.戴布于2009年提出的一种新兴启发算法。根据昆虫学家的长期观察研究发现&#…

布谷鸟算法

布谷鸟算法是将布谷鸟育雏行为与Levy飞行算法相结合的一种算法。 在布谷鸟算法中&#xff0c;有两个算法或者说两个位置更新是关键&#xff1a; 第一个是布谷鸟寻找最优解时的算法&#xff1a; 一个是布谷鸟寻找鸟窝下蛋的寻找路径是采用早已就有的萊维飞行3&#xff0c;如上…

布谷鸟算法浅谈与简单应用

简介 布谷鸟算法是由剑桥大学Xin-She Yang教授和S.Deb于2009年提出的一种新兴的启发算法&#xff0c;是一种通过模拟自然界当中布谷鸟&#xff08;也就是杜鹃&#xff0c;故该算法也称为杜鹃算法&#xff09;在繁育后代的行为而提出的一种搜索算法。 本文章将以在工程实践当中…

布谷鸟搜索算法学习

0、引言 布谷鸟搜索算法&#xff08;Cuckoo Search, CS&#xff09;是2009年Xin-She Yang 与Suash Deb在《Cuckoo Search via Levy Flights》一文中提出的一种优化算法。布谷鸟算法是一种集合了布谷鸟巢寄生性和莱维飞行&#xff08;Levy Flights&#xff09;模式的群体智能搜索…

布谷鸟搜索算法

布谷鸟搜索&#xff08;Cuckoo Search&#xff0c;缩写 CS&#xff09;&#xff0c;也叫杜鹃搜索&#xff0c;是由剑桥大学杨新社&#xff08;音译自&#xff1a;Xin-She Yang&#xff09;教授和S.戴布&#xff08;S.Deb&#xff09;于2009年提出的一种新兴启发算法。 1.定义 …

优化算法|布谷鸟算法原理及实现

布谷鸟算法 一、布谷鸟算法背景知识二、布谷鸟算法思想简介三、布谷鸟算法流程四、布谷鸟算法的Python实现五、布谷鸟算法matlab实现 一、布谷鸟算法背景知识 2009年&#xff0c;Xin-She Yang 与Suash Deb在《Cuckoo Search via Levy Flights》一文中提出了布谷鸟算法(简称CS)…

CS_2022_01

2022-1-3 08:33:52 用OBS录完之后的视频是mkv格式的&#xff0c;PR不支持mkv格式的视频&#xff0c;于是需要转码&#xff0c;一开始用FFmpeg&#xff0c;有点不方便&#xff0c;但是也能用。后来一看OBS原本自带转码工具。 发现过程&#xff1a; 打开OBS&#xff0c;点击左下角…

CSP-S 2020

[CSP-S2020] 动物园 题目描述 动物园里饲养了很多动物&#xff0c;饲养员小 A 会根据饲养动物的情况&#xff0c;按照《饲养指南》购买不同种类的饲料&#xff0c;并将购买清单发给采购员小 B。 具体而言&#xff0c;动物世界里存在 2 k 2^k 2k 种不同的动物&#xff0c;它…

cs231n(1)

图像分类 目标&#xff1a;已有固定的分类标签集合&#xff0c;然后对于输入的图像&#xff0c;从分类标签集合中找出一个分类标签&#xff0c;最后把分类标签分配给该输入图像。 图像分类流程 输入&#xff1a;输入是包含N个图像的集合&#xff0c;每个图像的标签是K种分类标…

CS61A 02

Control Expressions evaluate to values Statements perform actions print(print(1), print(2))1 2 None None Boolean Expressions T and F False values: False, None, 0, ‘’ True values: everything else Operators and, or, not True and 5 2 and 88 False …

CS224N 2019 Assignment 2

Written: Understanding word2vec Let’s have a quick refresher on the word2vec algorithm. The key insight behind word2vec is that ‘a word is known by the company it keeps’. Concretely, suppose we have a ‘center’ word c c c and a contextual window surr…

【CS231N】

损失函数和后向传播 铰链损失函数&#xff1a;SVM常用&#xff0c;打击和正确结果相似度高的错误答案 正则化&#xff1a;获得更简单的模型&#xff0c;获得更平均的模型&#xff0c;避免过拟合&#xff08;绿色线&#xff09; Softmax&#xff1a;先指数计算&#xff08;去除负…

Stanford CS230深度学习(一)

斯坦福CS230可以作为深度学习的入门课&#xff0c;最近我也在跟着看视频、完成编程作业。首先列出使用的资源链接&#xff0c;然后给出第一课的理解和编程作业的代码。 所有资料如下&#xff1a; 一、课程连接&#xff1a; b站课堂讲授版&#xff1a;Stanford CS230(吴恩达 …

csp-202206

202206 题目一&#xff1a;归一化处理【100分】题目二&#xff1a;寻宝&#xff01;大冒险&#xff01;【100分】题目三&#xff1a;角色授权【100分】题目四&#xff1a;光线追踪【15分】 题目一&#xff1a;归一化处理【100分】 水题&#xff0c;直接上 AC代码&#xff1a; …

cs229-1

本文全部参考自https://blog.csdn.net/stdcoutzyx?typeblog&#xff0c;仅作学习使用 文章目录 监督学习supervised learning线性回归局部加权回归LWR,Locally/Loess Weighted Regression最小二乘法的概率解释逻辑斯蒂回归logistic regression感知器算法牛顿方法NewTons Metho…

CS231n_learn

CS231n CS 程序&#xff1a;https://cs.stanford.edu/people/karpathy/convnetjs/demo/cifar10.html CS 课件http://cs231n.stanford.edu/slides/2017/&#xff1a; CS 课程首页&#xff1a;http://cs231n.stanford.edu/ CS 附带教程网页版&#xff1a;https://cs.stanford…

csp-202203

202203 题目一&#xff1a;未初始化警告【100分】题目二&#xff1a;出行计划【100分】题目三&#xff1a;计算资源调度器 【100分】 题目一&#xff1a;未初始化警告【100分】 简单数组操作题 #include<iostream> using namespace std; int n,k; bool ready[10000000]…