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

article/2025/10/5 8:46:54

布谷鸟算法

  • 一、布谷鸟算法背景知识
  • 二、布谷鸟算法思想简介
  • 三、布谷鸟算法流程
  • 四、布谷鸟算法的Python实现
  • 五、布谷鸟算法matlab实现

一、布谷鸟算法背景知识

2009年,Xin-She Yang 与Suash Deb在《Cuckoo Search via Levy Flights》一文中提出了布谷鸟算法(简称CS)。假设每只布谷鸟一次只产一枚卵 ,并且宿主鸟发现外来鸟蛋后,就舍弃该鸟窝,另寻他地建造新的鸟窝 ,那么可以认为 :鸟窝=卵蛋=解,卵蛋是否能够成功被宿主鸟孵化并茁长成长是衡量解好坏的唯一标准 。布谷鸟寻找鸟窝下蛋的过程就是在D维空间中寻找解的过程 ,而鸟窝的好坏象征着解的好坏。

二、布谷鸟算法思想简介

在这里插入图片描述
如图所示,布谷鸟下蛋之后会把蛋扔到其他鸟的鸟窝,为了不被宿主鸟发现,它会扔掉宿主鸟一个蛋,并且把蛋装扮成与宿主鸟的蛋外观相似,被宿主鸟发现之后会被移走,没有被宿主鸟发现则会被宿主鸟养育长大,一段时间后,布谷鸟下蛋了,小布谷鸟出生,会移走宿主鸟的一只蛋,继续按照上面的方式进行。
它的大致过程整理下:
在这里插入图片描述
更新位置方式

更新位置的方式会关系到最后算法的收敛速度,在上述的算法步骤中,我们在第3步和第4步都需要更新点的位置。通过随机行走(random walk)的方式更新点的位置,随机生成一个方向和长度,叠加到原有点上就成了新的点,但是需要指出的是,这个随机生成的方向和长度都是有讲究的,有研究发现通过莱维飞行(Levy Flight)的方式能比较有效地去寻找全局最优解而不至于陷入局部最优解中,并且它和布谷鸟算法配合达到了相当不错的效果,接下来就是解答什么是莱维飞行了。
莱维飞行
在这里插入图片描述
在这里插入图片描述

莱维飞行是由较长时间的短步长和较短时间的长步长组成。
点大多数时间只有小距离移动,偶尔会有大距离移动的情况。这和自然界中大多数动物觅食方式类似。
找到一块区域后细致的查找猎物,如果没找到,就换一片区域。
那么如何实现这种移动方式呢?

假设我们是捕猎者出去捕猎,刚开始会随机选个方向,接着确定要走多远。
Levy分布要求大概率落在值比较小的位置,小概率落在值比较大的位置,刚好满足这种均匀分布。
局部随机行走:
计算公式为:
在这里插入图片描述
在这里插入图片描述
它只适用于局部,容易陷入局部最优解,优点是比较稳定。相对于莱维飞行,它最大程度利用已有点的位置信息,新产生的点便是这些已有点的“折中”。

三、布谷鸟算法流程

伪代码:
在这里插入图片描述

四、布谷鸟算法的Python实现

布谷鸟算法提出者之一的Xin-She Yang教授试了多组参数,发现种群规模在15到40,布谷鸟蛋被发现的概率 pa 取0.25时,对于大多数优化问题已足够,并且结果和分析也表明收敛速度在一定程度上对所使用的参数不敏感。这意味着对于任何问题都不需要进行仔细地调整。至于迭代次数,我在实验中发现100次的迭代次数已能很好地找到最优解,但迭代次数往往取决你问题的规模.

import numpy as np
import scipy.special as sc_specialversion = '1.0.0'def cuckoo_search(n, m, fit_func, lower_boundary, upper_boundary, iter_num = 100,pa = 0.25, beta = 1.5, step_size = 0.1):"""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.argmax(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)max_nest_index = np.argmax(fitness)max_fitness = fitness[max_nest_index]max_nest = nests[max_nest_index]if (max_fitness > best_fitness):best_nest = max_nest.copy()best_fitness = max_fitnessreturn (best_nest, best_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 nestsdef 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 nestsdef 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 nestsdef 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 stepsdef 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 fitnessif __name__=='__main__':def fit_func(nest):x, y = 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))/3best_nest, best_fitness = cuckoo_search(25, 2, fit_func, [-3, -3], [3, 3], step_size = 0.4)print('最大值为:%.5f, 在(%.5f, %.5f)处取到!'%(best_fitness, best_nest[0], best_nest[1]))

python运行结果显示:
在这里插入图片描述
代码链接:
Python源码:
https://github.com/SJ2050SJ/Optimization_Algorithms

五、布谷鸟算法matlab实现

matlab运行结果显示:
在这里插入图片描述

代码链接:

matlab源码:
链接1:https://download.csdn.net/download/welcome_yu/14023295
链接2:https://download.csdn.net/download/g425680992/10517545

链接3:https://betterbench.blog.csdn.net/article/details/107285451?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.control

参考:
Xin-She Yang. 《Nature Inspired Optimization Algorithm.2nd》

布谷鸟算法学习1https://blog.csdn.net/sj2050/article/details/98496868?utm_medium=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase&depth_1-utm_source=distribute.pc_relevant_download.none-task-blog-baidujs-2.nonecase

布谷鸟算法学习2 https://betterbench.blog.csdn.net/article/details/107285451?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-2.control

布谷鸟算法学习3 https://blog.csdn.net/zyqblog/article/details/80905019


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

相关文章

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]…

【CS231n系列】

Stanford-cs231n课程学习笔记&#xff08;一&#xff09; Stanford课程原版是英文&#xff0c;奈何本人英语菜的一批。原版网站放在下面&#xff0c;xdm可以多多学习。BUT&#xff01; B站up<同济子豪兄>yyds好吧&#xff01;&#xff01;&#xff01; Stanford231n 文章…

斯坦福CS230官方指南:CNN、RNN及使用技巧速查(打印收藏)

向AI转型的程序员都关注了这个号&#x1f447;&#x1f447;&#x1f447; 机器学习AI算法工程 公众号&#xff1a; datayx 作为全球计算机四大名校之一&#xff0c;斯坦福大学的CS230《深度学习》课程一直受到全球计算机学子和从业人员的热烈欢迎。 CS230授课人为全球著名计算…

CS230学习笔记(一)

CS230学习笔记(一) 1.前言 ok&#xff0c;前思后想&#xff0c;左思右想&#xff0c;我还是觉得自己得督促一下自己&#xff0c;所以&#xff0c;我觉得开始更新cs230的笔记&#xff0c;当然&#xff0c;我前面的六篇pytorch学习笔记我是不会放着不管的&#xff0c;后面肯定会…

目标检测(CS230)

内容来自CS230课程。 目录 目标定位&#xff08;Object localization&#xff09; 特征点检测&#xff08;Landmark detection&#xff09; 基于滑动窗口的目标检测算法 滑动窗口的卷积实现 &#xff08;Convolutional implementation of sliding windows&#xff09; 网络中的…

PHP配置环境变量

1.找到“高级系统设置”&#xff08;二选一的方法找到环境变量&#xff09; ① 我的电脑-属性-高级-环境变量 ②win8,10 直接在搜索框搜 “查看高级系统设置”-环境变量 2.找到变量"Path" ①加上 “E:\phpStudy\PHPTutorial\php\php-7.0.12-nts” &#xff08;php.e…

PHPstudy 设置PHP为环境变量

1.首先启动phpstudy点击‘切换版本’查看当前使用环境的php版本 2.在右键点击桌面的phpstudy图标进入文件夹位置 2.点击PHPTutorial->PHP 3.点击你的开发版本的php文件&#xff0c;我们会看到php.exe文件&#xff0c;复制当前文件位置路径 4.右键点击计算机或者我的电脑选择…

windows环境下设置多个PHP版本的环境变量

windows环境下设置多个PHP版本的环境变量 所在位置修改系统变量修改用户变量重启电脑 所在位置 我的电脑->属性->高级系统设置->高级->环境变量 根据图示&#xff0c;找到相应的变量 修改系统变量 环境变量->系统变量->Path 系统变量&#xff1a;把两个…

windows10的PHP环境变量

win10 环境变量配置 如何在命令行运行php文件 1.配置环境变量 2.进入php所在路径 然后输入 php 文件路径/文件名 即可 参考文献&#xff1a; https://blog.csdn.net/QQ2542920524/article/details/78692116

Windows环境下,PHPStudy设置环境变量

win7系统设置环境变量 1、选中计算机&#xff0c;点击 鼠标右键&#xff0c;选择属性 2、选择高级系统设置&#xff0c;打开&#xff0c;打开后选择高级&#xff0c;然后就能看到环境变量 3、打开环境变量&#xff0c;查找Path &#xff0c;选中path&#xff0c;再点击编辑即可…