python实现人工蜂群算法


Posted in Python onSeptember 18, 2020

ABSIndividual.py

import numpy as np
import ObjFunction


class ABSIndividual:

  '''
  individual of artificial bee swarm algorithm
  '''

  def __init__(self, vardim, bound):
    '''
    vardim: dimension of variables
    bound: boundaries of variables
    '''
    self.vardim = vardim
    self.bound = bound
    self.fitness = 0.
    self.trials = 0

  def generate(self):
    '''
    generate a random chromsome for artificial bee swarm algorithm
    '''
    len = self.vardim
    rnd = np.random.random(size=len)
    self.chrom = np.zeros(len)
    for i in xrange(0, len):
      self.chrom[i] = self.bound[0, i] + \
        (self.bound[1, i] - self.bound[0, i]) * rnd[i]

  def calculateFitness(self):
    '''
    calculate the fitness of the chromsome
    '''
    self.fitness = ObjFunction.GrieFunc(
      self.vardim, self.chrom, self.bound)

ABS.py

import numpy as np
from ABSIndividual import ABSIndividual
import random
import copy
import matplotlib.pyplot as plt


class ArtificialBeeSwarm:

  '''
  the class for artificial bee swarm algorithm
  '''

  def __init__(self, sizepop, vardim, bound, MAXGEN, params):
    '''
    sizepop: population sizepop
    vardim: dimension of variables
    bound: boundaries of variables
    MAXGEN: termination condition
    params: algorithm required parameters, it is a list which is consisting of[trailLimit, C]
    '''
    self.sizepop = sizepop
    self.vardim = vardim
    self.bound = bound
    self.foodSource = self.sizepop / 2
    self.MAXGEN = MAXGEN
    self.params = params
    self.population = []
    self.fitness = np.zeros((self.sizepop, 1))
    self.trace = np.zeros((self.MAXGEN, 2))

  def initialize(self):
    '''
    initialize the population of abs
    '''
    for i in xrange(0, self.foodSource):
      ind = ABSIndividual(self.vardim, self.bound)
      ind.generate()
      self.population.append(ind)

  def evaluation(self):
    '''
    evaluation the fitness of the population
    '''
    for i in xrange(0, self.foodSource):
      self.population[i].calculateFitness()
      self.fitness[i] = self.population[i].fitness

  def employedBeePhase(self):
    '''
    employed bee phase
    '''
    for i in xrange(0, self.foodSource):
      k = np.random.random_integers(0, self.vardim - 1)
      j = np.random.random_integers(0, self.foodSource - 1)
      while j == i:
        j = np.random.random_integers(0, self.foodSource - 1)
      vi = copy.deepcopy(self.population[i])
      # vi.chrom = vi.chrom + np.random.uniform(-1, 1, self.vardim) * (
      #   vi.chrom - self.population[j].chrom) + np.random.uniform(0.0, self.params[1], self.vardim) * (self.best.chrom - vi.chrom)
      # for k in xrange(0, self.vardim):
      #   if vi.chrom[k] < self.bound[0, k]:
      #     vi.chrom[k] = self.bound[0, k]
      #   if vi.chrom[k] > self.bound[1, k]:
      #     vi.chrom[k] = self.bound[1, k]
      vi.chrom[
        k] += np.random.uniform(low=-1, high=1.0, size=1) * (vi.chrom[k] - self.population[j].chrom[k])
      if vi.chrom[k] < self.bound[0, k]:
        vi.chrom[k] = self.bound[0, k]
      if vi.chrom[k] > self.bound[1, k]:
        vi.chrom[k] = self.bound[1, k]
      vi.calculateFitness()
      if vi.fitness > self.fitness[fi]:
        self.population[fi] = vi
        self.fitness[fi] = vi.fitness
        if vi.fitness > self.best.fitness:
          self.best = vi
      vi.calculateFitness()
      if vi.fitness > self.fitness[i]:
        self.population[i] = vi
        self.fitness[i] = vi.fitness
        if vi.fitness > self.best.fitness:
          self.best = vi
      else:
        self.population[i].trials += 1

  def onlookerBeePhase(self):
    '''
    onlooker bee phase
    '''
    accuFitness = np.zeros((self.foodSource, 1))
    maxFitness = np.max(self.fitness)

    for i in xrange(0, self.foodSource):
      accuFitness[i] = 0.9 * self.fitness[i] / maxFitness + 0.1

    for i in xrange(0, self.foodSource):
      for fi in xrange(0, self.foodSource):
        r = random.random()
        if r < accuFitness[i]:
          k = np.random.random_integers(0, self.vardim - 1)
          j = np.random.random_integers(0, self.foodSource - 1)
          while j == fi:
            j = np.random.random_integers(0, self.foodSource - 1)
          vi = copy.deepcopy(self.population[fi])
          # vi.chrom = vi.chrom + np.random.uniform(-1, 1, self.vardim) * (
          #   vi.chrom - self.population[j].chrom) + np.random.uniform(0.0, self.params[1], self.vardim) * (self.best.chrom - vi.chrom)
          # for k in xrange(0, self.vardim):
          #   if vi.chrom[k] < self.bound[0, k]:
          #     vi.chrom[k] = self.bound[0, k]
          #   if vi.chrom[k] > self.bound[1, k]:
          #     vi.chrom[k] = self.bound[1, k]
          vi.chrom[
            k] += np.random.uniform(low=-1, high=1.0, size=1) * (vi.chrom[k] - self.population[j].chrom[k])
          if vi.chrom[k] < self.bound[0, k]:
            vi.chrom[k] = self.bound[0, k]
          if vi.chrom[k] > self.bound[1, k]:
            vi.chrom[k] = self.bound[1, k]
          vi.calculateFitness()
          if vi.fitness > self.fitness[fi]:
            self.population[fi] = vi
            self.fitness[fi] = vi.fitness
            if vi.fitness > self.best.fitness:
              self.best = vi
          else:
            self.population[fi].trials += 1
          break

  def scoutBeePhase(self):
    '''
    scout bee phase
    '''
    for i in xrange(0, self.foodSource):
      if self.population[i].trials > self.params[0]:
        self.population[i].generate()
        self.population[i].trials = 0
        self.population[i].calculateFitness()
        self.fitness[i] = self.population[i].fitness

  def solve(self):
    '''
    the evolution process of the abs algorithm
    '''
    self.t = 0
    self.initialize()
    self.evaluation()
    best = np.max(self.fitness)
    bestIndex = np.argmax(self.fitness)
    self.best = copy.deepcopy(self.population[bestIndex])
    self.avefitness = np.mean(self.fitness)
    self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
    self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
    print("Generation %d: optimal function value is: %f; average function value is %f" % (
      self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
    while self.t < self.MAXGEN - 1:
      self.t += 1
      self.employedBeePhase()
      self.onlookerBeePhase()
      self.scoutBeePhase()
      best = np.max(self.fitness)
      bestIndex = np.argmax(self.fitness)
      if best > self.best.fitness:
        self.best = copy.deepcopy(self.population[bestIndex])
      self.avefitness = np.mean(self.fitness)
      self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
      self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
      print("Generation %d: optimal function value is: %f; average function value is %f" % (
        self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
    print("Optimal function value is: %f; " % self.trace[self.t, 0])
    print "Optimal solution is:"
    print self.best.chrom
    self.printResult()

  def printResult(self):
    '''
    plot the result of abs algorithm
    '''
    x = np.arange(0, self.MAXGEN)
    y1 = self.trace[:, 0]
    y2 = self.trace[:, 1]
    plt.plot(x, y1, 'r', label='optimal value')
    plt.plot(x, y2, 'g', label='average value')
    plt.xlabel("Iteration")
    plt.ylabel("function value")
    plt.title("Artificial Bee Swarm algorithm for function optimization")
    plt.legend()
    plt.show()

运行程序:

if __name__ == "__main__":
 
   bound = np.tile([[-600], [600]], 25)
   abs = ABS(60, 25, bound, 1000, [100, 0.5])
   abs.solve()

ObjFunction见简单遗传算法-python实现。

以上就是python实现人工蜂群算法的详细内容,更多关于python 人工蜂群算法的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python+Django+apache的配置方法详解
Jun 01 Python
Python内存管理方式和垃圾回收算法解析
Nov 11 Python
Python实现自动上京东抢手机
Feb 06 Python
对pandas中iloc,loc取数据差别及按条件取值的方法详解
Nov 06 Python
Python判断telnet通不通的实例
Jan 26 Python
Python实现监控Nginx配置文件的不同并发送邮件报警功能示例
Feb 26 Python
Python字符串格式化输出代码实例
Nov 22 Python
使用Python进行防病毒免杀解析
Dec 13 Python
python-docx文件定位读取过程(尝试替换)
Feb 13 Python
Python面向对象实现方法总结
Aug 12 Python
属性与 @property 方法让你的python更高效
Sep 21 Python
baselines示例程序train_cartpole.py的ImportError
May 20 Python
Python猫眼电影最近上映的电影票房信息
Sep 18 #Python
python实现简单遗传算法
Sep 18 #Python
详解python 支持向量机(SVM)算法
Sep 18 #Python
python利用线程实现多任务
Sep 18 #Python
Pycharm的Available Packages为空的解决方法
Sep 18 #Python
Pycharm Available Package无法显示/安装包的问题Error Loading Package List解决
Sep 18 #Python
pycharm 代码自动补全的实现方法(图文)
Sep 18 #Python
You might like
ThinkPHP自动验证失败的解决方法
2011/06/09 PHP
PHP常用的三种设计模式汇总
2016/08/28 PHP
PHP实现微信申请退款功能
2018/10/01 PHP
表单提交时自动复制内容到剪贴板的js代码
2007/03/16 Javascript
javascrpt绑定事件之匿名函数无法解除绑定问题
2012/12/06 Javascript
javascript 利用Image对象实现的埋点(某处的点击数)统计
2012/12/28 Javascript
超简单JS二级、多级联动的简单实例
2014/02/18 Javascript
jquery自定义滚动条插件示例分享
2014/02/21 Javascript
express的中间件basicAuth详解
2014/12/04 Javascript
javascript 应用小技巧方法汇总
2015/07/05 Javascript
关注jquery技巧提高jquery技能(前端开发必学)
2015/11/02 Javascript
基于javascript制作微信聊天面板
2020/08/09 Javascript
jQuery 3.0十大新特性最终版发布
2016/07/14 Javascript
使用ionic播放轮询广告的实现方法(必看)
2017/04/24 Javascript
jquery之基本选择器practice(实例讲解)
2017/09/30 jQuery
nodejs中art-template模板语法的引入及冲突解决方案
2017/11/07 NodeJs
AngularJS实现的生成随机数与猜数字大小功能示例
2017/12/25 Javascript
基于openlayers4实现点的扩散效果
2020/08/17 Javascript
vue.js父子组件通信动态绑定的实例
2018/09/28 Javascript
JS使用队列对数组排列,基数排序算法示例
2019/03/02 Javascript
微信小程序组件传值图示过程详解
2019/07/31 Javascript
vue中根据时间戳判断对应的时间(今天 昨天 前天)
2019/12/20 Javascript
vue实现路由不变的情况下,刷新页面操作示例
2020/02/02 Javascript
[06:44]2018DOTA2亚洲邀请赛4.5 SOLO赛 MidOne vs Sumail
2018/04/06 DOTA
[01:35]2018完美盛典章节片——共竞
2018/12/17 DOTA
[52:06]FNATIC vs NIP 2019国际邀请赛小组赛 BO2 第二场 8.16
2019/08/19 DOTA
python通过cookie模拟已登录状态的初步研究
2016/11/09 Python
python日志记录模块实例及改进
2017/02/12 Python
如何利用Boost.Python实现Python C/C++混合编程详解
2018/11/08 Python
pycharm下配置pyqt5的教程(anaconda虚拟环境下+tensorflow)
2020/03/25 Python
CSS3 绘制BMW logo实的现代码
2013/04/25 HTML / CSS
HTML5 解决苹果手机不能自动播放音乐问题
2017/12/27 HTML / CSS
校园餐饮创业计划书
2014/01/10 职场文书
留学经费担保书
2014/05/12 职场文书
2014四风问题对照检查材料范文
2014/09/15 职场文书
Python入门学习之类的相关知识总结
2021/05/25 Python