最终效果与测试函数

1迭代过程

2效果曲线

3测试函数



artiBeeColony.py

面向对象的实现方式,简单明了。如有转载请注明出处。
直接运行,有bug的评论区私聊

#encoding:utf-8
#author:FuJun WANG
from functools import reduce
import math
import random
import copy
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签
plt.rcParams['axes.unicode_minus'] = Falsefrom mpl_toolkits.mplot3d import Axes3D
import numpy as np
##默认所有的函数都是求最小值问题
class testPro:def __init__(self):self.Pro1=Nonedef GriewankFunction(self,x):itemOne=0itmeTwo=0for i,value in enumerate(x):itemOne+=(value**2)/4000itmeTwo*=(math.cos(value/math.sqrt(i+1)))return 1+itemOne-itmeTwodef GeneralizeRastrigin(self,x):s=0for value in x:s+=(value**2-10*math.cos(2*math.pi*value)+10)return -sdef AckleyFunction(self,x):s1=0s2=0for value in x:s1+=value**2s2+=math.cos(2*math.pi*value)s1=s1/len(x)s2=s2/len(x)return -20*math.exp(-0.2*math.sqrt(s1))-math.exp(s2)+20+math.edef showGriewankFunction(self,n,bounds):##可视化函数""":param n: 可视化几阶次的函数,一般取2或3(因为最高我们只能可视化三维):param bounds: 函数的边界:return:"""if n==2:fig=plt.figure()value=[self.GriewankFunction(x) for x in np.arange(bounds[0],bounds[1],(bounds[1]-bounds[0])/1000)]plt.plot(range(len(value)),value)plt.title("GriewankFunction")plt.xlabel("x")plt.ylabel("value")elif n==3:fig=plt.figure()ax=plt.axes(projection='3d')xx=np.arange(bounds[0],bounds[1],(bounds[1]-bounds[0])/2000)yy=np.arange(bounds[0],bounds[1],(bounds[1]-bounds[0])/2000)X,Y=np.meshgrid(xx,yy)Z=1+(X**2+Y**2)/4000-(np.cos(X/1)*np.cos(Y/np.sqrt(2)))minZ=np.min(Z)indexMin=np.argmin(Z)ax.plot_surface(X,Y,Z,cmap='rainbow')plt.title("GriewankFunction,minValue%s" % round(minZ,2))plt.show()def showGeneralizeRastrigin(self,n,bounds):if n==2:passif n==3:fig = plt.figure()ax = plt.axes(projection='3d')xx = np.arange(bounds[0], bounds[1], (bounds[1] - bounds[0]) / 2000)yy = np.arange(bounds[0], bounds[1], (bounds[1] - bounds[0]) / 2000)X, Y = np.meshgrid(xx, yy)Z = -(X**2-10*np.cos(2*math.pi*X)+10)+(Y**2-10*np.cos(2*np.pi*Y)+10)minZ = np.min(Z)ax.plot_surface(X, Y, Z, cmap='rainbow')plt.title("GeneralizeRastrigin,minValue%s" % round(minZ,2))plt.show()def showAckleyFunction(self,n,bounds):if n==2:passif n==3:fig = plt.figure()ax = plt.axes(projection='3d')xx = np.arange(bounds[0], bounds[1], (bounds[1] - bounds[0]) / 2000)yy = np.arange(bounds[0], bounds[1], (bounds[1] - bounds[0]) / 2000)X, Y = np.meshgrid(xx, yy)Z =-20*np.exp(-0.2*np.sqrt((X**2+Y**2)/2))-np.exp((np.cos(2*np.pi*X)+np.cos(2*np.pi*Y))/2)+20+math.eminZ = np.min(Z)ax.plot_surface(X, Y, Z, cmap='rainbow')plt.title("AckleyFunction,minValue%s" % round(minZ,2))plt.show()class fitnessFunc:def fitneForMin(self,value,average):# math.exp(-(value / (average)))if value>=0:return 1/(1+value)else:return 1+math.fabs(value)def fitneForMax(self,value,average):return math.exp(value/average)
class Nectar:##蜜源def __init__(self,pos):# self.pro=pro##蜜源对应的评价函数self.LIMIT=8self.pos=pos##蜜源位置self.beAbandoned=0##被丢弃的次数self.beChoosed=1#被选择的self.followers=[]self.func=testPro().GriewankFunctionself.fitFunc=fitnessFunc().fitneForMindef getValue(self):##该位置在所给评价标准为pro的情况下的值,即蜜源大小return self.func(self.pos)def getBeAbandoned(self):return self.beAbandoneddef addAbandoned(self):self.beAbandoned+=1def addBechoosed(self):self.beChoosed+=1def getPos(self):return self.posdef setPos(self,pos):self.pos=posdef getFollowers(self):return self.followersdef setFollowers(self,newFoll):self.followers=newFolldef addFolloers(self,f):##该蜜源增加的采蜜者self.followers.append(f)def getLimit(self):return self.LIMIT
class Bee:def __init__(self,id,type):self.id=idself.type=type##type=1表示是雇佣蜂2表示是追随蜂3表示的是侦察蜂def setType(self):self.type=typedef getType(self):return self.typedef getId(self):return self.idclass ABC:def __init__(self,pro,B,E,L,S,I,bound):self.pro=pro#问题self.B=B#蜂群的大小self.E=E#雇佣蜂的数目self.L=L#追随蜂的数目self.S=S#侦察峰的数目self.I=I#最大的迭代次数self.st=[]#保存蜜源self.bound=boundself.onLookList=[]##追随蜂列表self.scoutsList=[]#侦察蜂列表self.bestValue=None#最优值self.bestPos=None#最优值位置self.fitnessFun=fitnessFunc().fitneForMinself.resultRecord=[]##存放中间最优值self.resultForPicture=[]self.pictureIndex=[0,10,20,30,50,70,90,int(100+0*(self.I-100)/5),int(100+1*(self.I-100)/5),int(100+2*(self.I-100)/5),int(100+3*(self.I-100)/5),int(100+4*(self.I-100)/5)]#在第几次循环中拍快照##用二阶的grienWankFunc进行测试def getFeasibleSol(slef, bounds):  ##随机产生点return bounds[0] + random.random() * (bounds[1] - bounds[0])def initial(self):#初始化蜜源for i in range(self.B):if i <self.E:##前E个是雇佣蜂,雇佣蜂的数量与# thisBee=Bee(i,1)##初始化一只小蜜蜂randomPos=[self.getFeasibleSol(self.bound),self.getFeasibleSol(self.bound)]thisNectar=Nectar(randomPos)##初始化蜜源的位置thisNectar.addFolloers(i)##将这只雇佣蜂添加到这个蜂源上self.st.append(thisNectar)else:##这些是追随峰# thisBee=Bee(i,2)self.onLookList.append(i)for i in range(self.S):##侦察蜂# thisBee=Bee(i,3)self.scoutsList.append(i)bestIndex,self.bestValue=list(min(enumerate([item.getValue() for item in self.st])))self.bestPos=self.st[bestIndex].getPos()#目前最优的函数值,以及最优值对应的点def getRandomPos(self,pos1,pos2):randomStep=random.random()return [pos1[0]+randomStep*(pos2[0]-pos1[0]),pos1[1]+randomStep*(pos2[1]-pos1[1])]def roulette(self,pList):arrow=random.random()s=0for index,value in enumerate(pList):s+=valueif s>=arrow:return indexdef employedPro(self):newStList = []  # 新的蜂源集合for nc in self.st:if len(nc.getFollowers())==0:pass  # 如果这个蜜源没有一个开采这者了,就废弃else:flyAway = []notFly = []for bee in nc.getFollowers():if random.random()<0.3:self.onLookList.append(bee)continue#成为跟随峰if random.random()<0.6 and random.random()>0.3:#成为侦察蜂self.scoutsList.append(bee)continueelse:# 探索一个新的位置,先随机的从现有的st中随机的选择一个元素ranNc = random.choice(self.st)newPos = self.getRandomPos(nc.getPos(),ranNc.getPos())newNc = Nectar(newPos)##贪婪求法,if newNc.getValue() < nc.getValue():  # 如果新探索的位置好,就放弃现在的位置newNc.addFolloers(bee)newStList.append(newNc)flyAway.append(bee)  ##这只小蜜蜂飞走了nc.addAbandoned()  ##被丢弃的个数加1if newNc.getValue()<self.bestValue:#是否能信最优值self.bestValue=newNc.getValue()self.bestPos=newNc.getPos()print("目前最优", self.bestValue, "|", self.bestPos)else:nc.addBechoosed()  # 坚持现在的,当前位置被宠幸加1notFly.append(bee)##所有蜜蜂遍历结束看当前还剩几个蜜蜂if len(flyAway) == len(nc.getFollowers()):  # 当前蜜源的蜜蜂飞走完了,该位置被废弃passelif (nc.getBeAbandoned()>=nc.getLimit()):##如果当前位置被丢弃过多,放弃该蜜源,此地的小蜜蜂成为其他峰for bee in nc.getFollowers():if random.random()<0.5:##等概率的成为追随峰或者侦察峰self.onLookList.append(bee)else:self.scoutsList.append(bee)else:nc.setFollowers(notFly)newStList.append(nc)self.st = copy.deepcopy(newStList)def onLookerPro(self):valueList = []for nc in self.st:valueList.append(nc.getValue())aveValue = sum(valueList) / len(valueList)fitnessList = [self.fitnessFun(item, aveValue) for item in valueList]  ##适应度sumFit = sum(fitnessList)pList = [item / sumFit for item in fitnessList]  ##被选概率notBeEmployed=[]for bee in self.onLookList:if random.random()<0.3:#百分之30的概率不成为雇佣蜂notBeEmployed.append(bee)else:follow=self.roulette(pList)self.st[follow].addFolloers(bee)self.onLookList=copy.deepcopy(notBeEmployed)#现在依然是雇佣峰的def scoutsPro(self):newScoutList = []for bee in self.scoutsList:newSt=Nectar([self.getFeasibleSol(self.bound), self.getFeasibleSol(self.bound)])for i in range(30):##侦察峰的探索次数temPos = [self.getFeasibleSol(self.bound), self.getFeasibleSol(self.bound)]temSt = Nectar(temPos)if temSt.getValue()>newSt.getValue():newSt=temStif newSt.getValue() < self.bestValue:self.st.append(newSt)self.bestValue = newSt.getValue()self.bestPos = newSt.getPos()print("目前最优", self.bestValue, "|", self.bestPos)else:#rif random.random() < 0.3:self.onLookList.append(bee)else:newScoutList.append(bee)self.scoutsList = copy.deepcopy(newScoutList)def solve(self):self.initial()  # 初始化完成##雇佣蜂行动找下一个峰源for i in range(self.I):self.employedPro()##跟随峰行动self.onLookerPro()##侦察峰出动self.scoutsPro()self.resultRecord.append(self.bestValue)if i in self.pictureIndex :##抓取蜜源快照self.resultForPicture.append(self.st)def showResult(self):##画优化过程曲线fig=plt.figure()plt.plot(range(len(self.resultRecord)),self.resultRecord)plt.title("优化过程曲线")##画快照fig1=plt.figure()for i in range(len(self.pictureIndex)):ax=fig1.add_subplot(3,4,i+1)x,y=[],[]for st in self.resultForPicture[i]:x.append(st.getPos()[0])y.append(st.getPos()[1])ax.scatter(x,y)plt.xlabel("第%s次迭代"%(self.pictureIndex[i]))plt.tight_layout()plt.show()if __name__ == '__main__':#初始化蜂群的大小,追随者数目,雇佣者的数目,侦察者的数目I=200##最好大于100好画图B=120onLookers=int(0.5*B)employedBee = int(0.5 * B)scouts=80myPros=testPro()grienWankFunc=myPros.GriewankFunctionbounds=[-10,10]myBCA=ABC(grienWankFunc,B,onLookers,employedBee,scouts,I,bounds)myBCA.solve()print(myBCA.bestValue)print(myBCA.bestPos)myBCA.showResult()myPros.showGriewankFunction(3,bounds)myPros.showGeneralizeRastrigin(3,bounds)myPros.showAckleyFunction(3,bounds)

算法篇——人工蜂群算法python实现相关推荐

  1. 智能优化算法:人工蜂群算法-附代码

    智能优化算法:人工蜂群算法 文章目录 智能优化算法:人工蜂群算法 1.算法原理 1.1 蜂群的初始化 1.2 雇佣蜂阶段 1.3 跟随蜂阶段 1.4 探索蜂阶段 2.算法流程 3.算法结果 4.参考文 ...

  2. 群智能算法之人工蜂群算法(ABC算法)

    人工蜂群算法(ABC算法)(Artificial Bee Colony) 该算法标准原型代码下载地址:https://abc.erciyes.edu.tr/index.htm ,包括C.Java.Ma ...

  3. 人工蜂群算法python_人工蜂群算法简介与程序分析

    目前人工蜂群算法主要分为基于婚配行为与基于釆蜜行为两大类,本文研究的是基于釆蜜行为的人工蜂群算法. 蜜蜂采蜜 自然界中的蜜蜂总能在任何环境下以极高的效率找到优质蜜源,且能适应环境的改变.蜜蜂群的采蜜系 ...

  4. 【ABC算法】人工蜂群算法原理及代码

    一.人工蜂群算法的介绍     人工蜂群算法(Artificial Bee Colony, ABC)是由Karaboga于2005年提出的一种新颖的基于群智能的全局优化算法,其直观背景来源于蜂群的采蜜 ...

  5. 人工蜂群算法python_人工蜂群算法-python实现

    1 importnumpy as np2 from ABSIndividual importABSIndividual3 importrandom4 importcopy5 importmatplot ...

  6. 基于改进人工蜂群算法的K均值聚类算法(附MATLAB版源代码)

    其实一直以来也没有准备在园子里发这样的文章,相对来说,算法改进放在园子里还是会稍稍显得格格不入.但是最近邮箱收到的几封邮件让我觉得有必要通过我的博客把过去做过的东西分享出去更给更多需要的人.从论文刊登 ...

  7. 人工蜂群算法_如果你的团队能够像人工蜂群一样战斗

    无人机航迹规划那些事儿-人工蜂群算法 无人机航迹规划问题有机器人路径规划问题延伸而来.三维环境下无人机航迹规划问题相较于二维环境规划较为复杂.航迹规划通常按一下流程:先对航迹规划空间进行数学建模,预先 ...

  8. 人工蜂群算法求解TSP问题

    人工蜂群算法求解TSP问题 [标签] ABC TSP Matlab data:2018-10-19 author:怡宝2号 [总起]利用人工蜂群算法(Artificial Bee Colony Alg ...

  9. 论文阅读三:基于改进人工蜂群算法的SDN负载均衡策略研究

    名词解释: Artificial Bee Colony Algorithm, ABC:人工蜂群算法 Load balancing algorithm based on improved artific ...

最新文章

  1. 元件库导入_Axure RP9【元件库的学习】
  2. 【黑客帝国数字雨屏保】基于Win32的黑客帝国数字雨屏幕保护程序(附VS工程代码文件和可执行文件)
  3. 机器人教育发展_得于人工智能发展,机器人教育低龄化越来越普及
  4. 计算机网络 socket,[计算机网络]简单聊聊套接字 Socket
  5. css怎么让div旋转不改变形状,旋转任意角度 如何让div旋转一定的角度
  6. 手工建立mysql的服务_怎样自已手工打开mysql服务
  7. 第五天--表单与页面
  8. verilog基础语法
  9. 【SuperResolution】Spatial resolution的含义
  10. 机顶盒App安装在sd卡的目录
  11. 2016书单总结--看透SpringMvc源代码分析与实践-概述
  12. 5-3 区块链与供应链金融
  13. 关于谷歌眼镜的几点常见问题
  14. typescript 八叉树的简单实现
  15. 最常用的邮箱的SMTP
  16. MATLAB 的BPSK信号调制
  17. 几个非洲鼓的基本节奏
  18. VLC电脑串流视频到手机播放
  19. 博客园上海俱乐部活动报道
  20. 恺撒密码加解密程序(Python)

热门文章

  1. zabbix告警页面sql语句
  2. 在基于瑞芯微rk3568的android12上添加移远4G通信模块EC200A
  3. 样例类,样例对象,伴生类,伴生对象
  4. php 身份证号码获取星座和生肖
  5. 顺序表和单链表基本操作的实现
  6. 小赵、小钱、小孙一起打羽毛球,每局两人比赛,另一人休息。三人约定每一局的输方下一局休息。
  7. span标签中实现换行
  8. MPLS工作机制及MPLS 虚拟专用网络技术
  9. 3大简历难题,你是否也曾遭遇?
  10. 使用class-dump-z