ABSIndividual.py

  1. import numpy as np
  2. import ObjFunction
  3.  
  4. class ABSIndividual:
  5.  
  6. '''
  7. individual of artificial bee swarm algorithm
  8. '''
  9.  
  10. def __init__(self, vardim, bound):
  11. '''
  12. vardim: dimension of variables
  13. bound: boundaries of variables
  14. '''
  15. self.vardim = vardim
  16. self.bound = bound
  17. self.fitness = 0.
  18. self.trials = 0
  19.  
  20. def generate(self):
  21. '''
  22. generate a random chromsome for artificial bee swarm algorithm
  23. '''
  24. len = self.vardim
  25. rnd = np.random.random(size=len)
  26. self.chrom = np.zeros(len)
  27. for i in xrange(0, len):
  28. self.chrom[i] = self.bound[0, i] + \
  29. (self.bound[1, i] - self.bound[0, i]) * rnd[i]
  30.  
  31. def calculateFitness(self):
  32. '''
  33. calculate the fitness of the chromsome
  34. '''
  35. self.fitness = ObjFunction.GrieFunc(
  36. self.vardim, self.chrom, self.bound)

ABS.py

  1. import numpy as np
  2. from ABSIndividual import ABSIndividual
  3. import random
  4. import copy
  5. import matplotlib.pyplot as plt
  6.  
  7. class ArtificialBeeSwarm:
  8.  
  9. '''
  10. the class for artificial bee swarm algorithm
  11. '''
  12.  
  13. def __init__(self, sizepop, vardim, bound, MAXGEN, params):
  14. '''
  15. sizepop: population sizepop
  16. vardim: dimension of variables
  17. bound: boundaries of variables
  18. MAXGEN: termination condition
  19. params: algorithm required parameters, it is a list which is consisting of[trailLimit, C]
  20. '''
  21. self.sizepop = sizepop
  22. self.vardim = vardim
  23. self.bound = bound
  24. self.foodSource = self.sizepop / 2
  25. self.MAXGEN = MAXGEN
  26. self.params = params
  27. self.population = []
  28. self.fitness = np.zeros((self.sizepop, 1))
  29. self.trace = np.zeros((self.MAXGEN, 2))
  30.  
  31. def initialize(self):
  32. '''
  33. initialize the population of abs
  34. '''
  35. for i in xrange(0, self.foodSource):
  36. ind = ABSIndividual(self.vardim, self.bound)
  37. ind.generate()
  38. self.population.append(ind)
  39.  
  40. def evaluation(self):
  41. '''
  42. evaluation the fitness of the population
  43. '''
  44. for i in xrange(0, self.foodSource):
  45. self.population[i].calculateFitness()
  46. self.fitness[i] = self.population[i].fitness
  47.  
  48. def employedBeePhase(self):
  49. '''
  50. employed bee phase
  51. '''
  52. for i in xrange(0, self.foodSource):
  53. k = np.random.random_integers(0, self.vardim - 1)
  54. j = np.random.random_integers(0, self.foodSource - 1)
  55. while j == i:
  56. j = np.random.random_integers(0, self.foodSource - 1)
  57. vi = copy.deepcopy(self.population[i])
  58. # vi.chrom = vi.chrom + np.random.uniform(-1, 1, self.vardim) * (
  59. # vi.chrom - self.population[j].chrom) + np.random.uniform(0.0, self.params[1], self.vardim) * (self.best.chrom - vi.chrom)
  60. # for k in xrange(0, self.vardim):
  61. # if vi.chrom[k] < self.bound[0, k]:
  62. # vi.chrom[k] = self.bound[0, k]
  63. # if vi.chrom[k] > self.bound[1, k]:
  64. # vi.chrom[k] = self.bound[1, k]
  65. vi.chrom[
  66. k] += np.random.uniform(low=-1, high=1.0, size=1) * (vi.chrom[k] - self.population[j].chrom[k])
  67. if vi.chrom[k] < self.bound[0, k]:
  68. vi.chrom[k] = self.bound[0, k]
  69. if vi.chrom[k] > self.bound[1, k]:
  70. vi.chrom[k] = self.bound[1, k]
  71. vi.calculateFitness()
  72. if vi.fitness > self.fitness[fi]:
  73. self.population[fi] = vi
  74. self.fitness[fi] = vi.fitness
  75. if vi.fitness > self.best.fitness:
  76. self.best = vi
  77. vi.calculateFitness()
  78. if vi.fitness > self.fitness[i]:
  79. self.population[i] = vi
  80. self.fitness[i] = vi.fitness
  81. if vi.fitness > self.best.fitness:
  82. self.best = vi
  83. else:
  84. self.population[i].trials += 1
  85.  
  86. def onlookerBeePhase(self):
  87. '''
  88. onlooker bee phase
  89. '''
  90. accuFitness = np.zeros((self.foodSource, 1))
  91. maxFitness = np.max(self.fitness)
  92.  
  93. for i in xrange(0, self.foodSource):
  94. accuFitness[i] = 0.9 * self.fitness[i] / maxFitness + 0.1
  95.  
  96. for i in xrange(0, self.foodSource):
  97. for fi in xrange(0, self.foodSource):
  98. r = random.random()
  99. if r < accuFitness[i]:
  100. k = np.random.random_integers(0, self.vardim - 1)
  101. j = np.random.random_integers(0, self.foodSource - 1)
  102. while j == fi:
  103. j = np.random.random_integers(0, self.foodSource - 1)
  104. vi = copy.deepcopy(self.population[fi])
  105. # vi.chrom = vi.chrom + np.random.uniform(-1, 1, self.vardim) * (
  106. # vi.chrom - self.population[j].chrom) + np.random.uniform(0.0, self.params[1], self.vardim) * (self.best.chrom - vi.chrom)
  107. # for k in xrange(0, self.vardim):
  108. # if vi.chrom[k] < self.bound[0, k]:
  109. # vi.chrom[k] = self.bound[0, k]
  110. # if vi.chrom[k] > self.bound[1, k]:
  111. # vi.chrom[k] = self.bound[1, k]
  112. vi.chrom[
  113. k] += np.random.uniform(low=-1, high=1.0, size=1) * (vi.chrom[k] - self.population[j].chrom[k])
  114. if vi.chrom[k] < self.bound[0, k]:
  115. vi.chrom[k] = self.bound[0, k]
  116. if vi.chrom[k] > self.bound[1, k]:
  117. vi.chrom[k] = self.bound[1, k]
  118. vi.calculateFitness()
  119. if vi.fitness > self.fitness[fi]:
  120. self.population[fi] = vi
  121. self.fitness[fi] = vi.fitness
  122. if vi.fitness > self.best.fitness:
  123. self.best = vi
  124. else:
  125. self.population[fi].trials += 1
  126. break
  127.  
  128. def scoutBeePhase(self):
  129. '''
  130. scout bee phase
  131. '''
  132. for i in xrange(0, self.foodSource):
  133. if self.population[i].trials > self.params[0]:
  134. self.population[i].generate()
  135. self.population[i].trials = 0
  136. self.population[i].calculateFitness()
  137. self.fitness[i] = self.population[i].fitness
  138.  
  139. def solve(self):
  140. '''
  141. the evolution process of the abs algorithm
  142. '''
  143. self.t = 0
  144. self.initialize()
  145. self.evaluation()
  146. best = np.max(self.fitness)
  147. bestIndex = np.argmax(self.fitness)
  148. self.best = copy.deepcopy(self.population[bestIndex])
  149. self.avefitness = np.mean(self.fitness)
  150. self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
  151. self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
  152. print("Generation %d: optimal function value is: %f; average function value is %f" % (
  153. self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
  154. while self.t < self.MAXGEN - 1:
  155. self.t += 1
  156. self.employedBeePhase()
  157. self.onlookerBeePhase()
  158. self.scoutBeePhase()
  159. best = np.max(self.fitness)
  160. bestIndex = np.argmax(self.fitness)
  161. if best > self.best.fitness:
  162. self.best = copy.deepcopy(self.population[bestIndex])
  163. self.avefitness = np.mean(self.fitness)
  164. self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
  165. self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
  166. print("Generation %d: optimal function value is: %f; average function value is %f" % (
  167. self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
  168. print("Optimal function value is: %f; " % self.trace[self.t, 0])
  169. print "Optimal solution is:"
  170. print self.best.chrom
  171. self.printResult()
  172.  
  173. def printResult(self):
  174. '''
  175. plot the result of abs algorithm
  176. '''
  177. x = np.arange(0, self.MAXGEN)
  178. y1 = self.trace[:, 0]
  179. y2 = self.trace[:, 1]
  180. plt.plot(x, y1, 'r', label='optimal value')
  181. plt.plot(x, y2, 'g', label='average value')
  182. plt.xlabel("Iteration")
  183. plt.ylabel("function value")
  184. plt.title("Artificial Bee Swarm algorithm for function optimization")
  185. plt.legend()
  186. plt.show()

运行程序:

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

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

人工蜂群算法-python实现的更多相关文章

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

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

  2. 人工鱼群算法-python实现

    AFSIndividual.py import numpy as np import ObjFunction import copy class AFSIndividual: "" ...

  3. pageRank算法 python实现

    一.什么是pagerank PageRank的Page可是认为是网页,表示网页排名,也可以认为是Larry Page(google 产品经理),因为他是这个算法的发明者之一,还是google CEO( ...

  4. 常见排序算法-Python实现

    常见排序算法-Python实现 python 排序 算法 1.二分法     python    32行 right = length-  :  ]   ):  test_list = [,,,,,, ...

  5. kmp算法python实现

    kmp算法python实现 kmp算法 kmp算法用于字符串的模式匹配,也就是找到模式字符串在目标字符串的第一次出现的位置比如abababc那么bab在其位置1处,bc在其位置5处我们首先想到的最简单 ...

  6. KMP算法-Python版

                               KMP算法-Python版 传统法: 从左到右一个个匹配,如果这个过程中有某个字符不匹配,就跳回去,将模式串向右移动一位.这有什么难的? 我们可以 ...

  7. 压缩感知重构算法之IRLS算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  8. 压缩感知重构算法之OLS算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  9. 压缩感知重构算法之CoSaMP算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

随机推荐

  1. flex4 s:Datagrid <s:typicalItem

    <s:DataGird <s:typicalItem 这个标签相信大家很陌生吧, 我也是今天准备讲的时候才看到,估计是 flex4.5.1 新加东西,果然摸索 了下,这个标签作用也蛮好用的 ...

  2. SqlMapConfig.xml中的setting属性设置

    <settings     cacheModelsEnabled="true"     lazyLoadingEnabled="false"     en ...

  3. java 21 - 8 复制文本文件的5种方式

    需求:复制文本文件 分析: 由于文本文件我们用记事本打开后可以读懂,所以使用字符流. 而字符流有5种复制的方式: 首先写main方法 public static void main(String[] ...

  4. java 16 -7 泛型方法和泛型接口(泛型类相似)

    写一个ObjectTool类 泛型方法:把泛型定义在方法上 格式 public <泛型类型> 返回类型 方法名(泛型类型) 这样的好处是: 这个泛型方法可以接收任意类型的数据 public ...

  5. Centos中yum方式安装java

    查看CentOS自带JDK是否已安装.◆输入:yum list installed |grep java. 若有自带安装的JDK,如何卸载CentOS系统自带Java环境?◆卸载JDK相关文件输入:y ...

  6. RDLC系列之二 子报表

    本文实现简单的子报表 一.效果图

  7. 3110 PHP常见问题

    1.中文显示 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&g ...

  8. android Camera 如何判断当前使用的摄像头是前置还是后置

    现在 android 平台的智能手机一般都标配有两颗摄像头.在 Camera 中都存在摄像头切换的功能. 并且有一些功能前后置摄像头上会有所不同.譬如人脸检测,人脸识别,自动对焦,闪光灯等功能, 如果 ...

  9. C# 与 Unity 同名函数

    1,Random,直接使用Random会报错,要么使用UnityEngine.Random,要么使用System.Random

  10. 基于.Net FrameWork的 RestFul Service

    关于本文 这篇文章的目的就是向大家阐述如何在.net framework 4.0中创建RestFul Service并且使用它. 什么是web Services,什么是WCF 首先讲到的是web Se ...