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中lambda与def用法对比实例分析
Apr 30 Python
Python函数式编程指南(一):函数式编程概述
Jun 24 Python
对python 矩阵转置transpose的实例讲解
Apr 17 Python
python 实现数字字符串左侧补零的方法
Dec 04 Python
在Python中使用Neo4j的方法
Mar 14 Python
windows下python虚拟环境virtualenv安装和使用详解
Jul 16 Python
Python超越函数积分运算以及绘图实现代码
Nov 20 Python
win10安装tensorflow-gpu1.8.0详细完整步骤
Jan 20 Python
python 的topk算法实例
Apr 02 Python
Pytorch可视化的几种实现方法
Jun 10 Python
Python+Matplotlib+LaTeX玩转数学公式
Feb 24 Python
python函数的两种嵌套方法使用
Apr 02 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
yii框架通过控制台命令创建定时任务示例
2014/04/30 PHP
php实现简易聊天室应用代码
2015/09/23 PHP
php+ajax实现无刷新数据分页的办法
2015/11/02 PHP
Laravel 5.3 学习笔记之 错误&amp;日志
2016/08/28 PHP
PHP读取文件的常见几种方法
2016/11/03 PHP
onkeyup,onkeydown和onkeypress的区别介绍
2013/10/21 Javascript
JavaScript中输出标签的方法
2014/08/27 Javascript
JS针对浏览器窗口关闭事件的监听方法集锦
2016/06/24 Javascript
JavaScript你不知道的一些数组方法
2017/08/18 Javascript
基于Vue的移动端图片裁剪组件功能
2017/11/28 Javascript
在小程序中集成redux/immutable/thunk第三方库的方法
2018/08/12 Javascript
[01:02:47]EG vs Secret 2019国际邀请赛淘汰赛 胜者组 BO3 第一场 8.21.mp4
2020/07/19 DOTA
[52:39]完美世界DOTA2联赛PWL S3 CPG vs Forest 第一场 12.16
2020/12/17 DOTA
python实现识别相似图片小结
2016/02/22 Python
深入理解Python爬虫代理池服务
2018/02/28 Python
numpy np.newaxis 的实用分享
2019/11/30 Python
Python 实现进度条的六种方式
2021/01/06 Python
纯CSS3实现绘制各种图形实现代码详细整理
2012/12/26 HTML / CSS
澳洲国民品牌乡村路折扣店:Country Road & Trenery Outlet
2018/04/19 全球购物
eHarmony英国:全球领先的认真恋爱约会平台之一
2020/11/16 全球购物
当一个对象被当作参数传递到一个方法后,此方法可改变这个对象的属性,并可返回变化后的结果,那么这里到底是值传递还是引用传递?
2014/09/09 面试题
C/C++有关内存的思考题
2015/12/04 面试题
导游的职业规划书范文
2013/12/27 职场文书
幼儿园家长会邀请函
2014/01/15 职场文书
高二历史教学反思
2014/01/25 职场文书
优秀少先队辅导员先进事迹材料
2014/05/18 职场文书
校运会口号
2014/06/18 职场文书
亚运会口号
2014/06/20 职场文书
商铺门前三包责任书
2014/07/25 职场文书
我的中国梦演讲稿600字
2014/08/19 职场文书
党员个人党性分析材料
2014/12/18 职场文书
办公室年度工作总结2015
2015/05/21 职场文书
2016年春节慰问信息大全
2015/11/30 职场文书
《活见鬼》教学反思
2016/02/24 职场文书
Python Pygame实战之塔防游戏的实现
2022/03/17 Python
Java 多线程协作作业之信号同步
2022/05/11 Java/Android