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接收Gmail新邮件并发送到gtalk的方法
Mar 10 Python
Django Admin实现上传图片校验功能
Mar 06 Python
Python+matplotlib实现计算两个信号的交叉谱密度实例
Jan 08 Python
python3+PyQt5+Qt Designer实现堆叠窗口部件
Apr 20 Python
利用python-pypcap抓取带VLAN标签的数据包方法
Jul 23 Python
python如何统计代码运行的时长
Jul 24 Python
python用WxPython库实现无边框窗体和透明窗体实现方法详解
Feb 21 Python
django实现HttpResponse返回json数据为中文
Mar 27 Python
python使用OpenCV模块实现图像的融合示例代码
Apr 10 Python
Django项目uwsgi+Nginx保姆级部署教程实现
Apr 19 Python
python logging通过json文件配置的步骤
Apr 27 Python
Python爬虫实战之爬取京东商品数据并实实现数据可视化
Jun 07 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
php Notice: Undefined index 错误提示解决方法
2010/08/29 PHP
PHP错误提示的关闭方法详解
2013/06/23 PHP
ThinkPHP3.1.3版本新特性概述
2014/06/19 PHP
PHP使用memcache缓存技术提高响应速度的方法
2014/12/26 PHP
py文件转exe时包含paramiko模块出错解决方法
2016/08/12 PHP
选择TreeView控件的树状数据节点的JS方法(jquery)
2010/02/06 Javascript
ExtJS 设置级联菜单的默认值
2010/06/13 Javascript
jQuery1.6 使用方法一
2011/11/23 Javascript
找出字符串中出现次数最多的字母和出现次数精简版
2012/11/07 Javascript
js整数字符串转换为金额类型数据(示例代码)
2013/12/26 Javascript
FF IE浏览器修改标签透明度的方法
2014/01/27 Javascript
利用jQuery和CSS将背景图片拉伸
2015/10/16 Javascript
jQuery EasyUI 布局之动态添加tabs标签页
2015/11/18 Javascript
JavaScript浏览器对象之一Window对象详解
2016/06/03 Javascript
JavaScript数据结构链表知识详解
2016/11/21 Javascript
详解nodejs微信公众号开发——6.自定义菜单
2017/04/13 NodeJs
详解AngularJS2 Http服务
2017/06/26 Javascript
Vue 中的compile操作方法
2018/02/26 Javascript
详解在React里使用&quot;Vuex&quot;
2018/04/02 Javascript
微信小程序调用后台service教程详解
2020/11/06 Javascript
js前端传json后台接收‘‘被转为quot的问题解决
2020/11/12 Javascript
Python 函数基础知识汇总
2018/03/09 Python
使用pandas中的DataFrame数据绘制柱状图的方法
2018/04/10 Python
Python实现合并两个列表的方法分析
2018/05/28 Python
python集合是否可变总结
2019/06/20 Python
python多线程共享变量的使用和效率方法
2019/07/16 Python
Python如何测试stdout输出
2020/08/10 Python
python实现暗通道去雾算法的示例
2020/09/27 Python
伦敦平价潮流珠宝首饰品牌:Astrid & Miyu
2016/10/10 全球购物
瑜伽服装品牌:露露柠檬(lululemon athletica)
2017/06/04 全球购物
保加利亚服装和鞋类购物网站:Bibloo.bg
2020/11/08 全球购物
中专生自我鉴定
2013/12/17 职场文书
运动会广播稿80字
2014/01/23 职场文书
中药学自荐信
2014/06/15 职场文书
车辆年审委托书范本
2014/09/18 职场文书
MySql数据库 查询时间序列间隔
2022/05/11 MySQL