人工蜂群算法-python实现
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实现的更多相关文章
- 基于改进人工蜂群算法的K均值聚类算法(附MATLAB版源代码)
其实一直以来也没有准备在园子里发这样的文章,相对来说,算法改进放在园子里还是会稍稍显得格格不入.但是最近邮箱收到的几封邮件让我觉得有必要通过我的博客把过去做过的东西分享出去更给更多需要的人.从论文刊登 ...
- 人工鱼群算法-python实现
AFSIndividual.py import numpy as np import ObjFunction import copy class AFSIndividual: "" ...
- pageRank算法 python实现
一.什么是pagerank PageRank的Page可是认为是网页,表示网页排名,也可以认为是Larry Page(google 产品经理),因为他是这个算法的发明者之一,还是google CEO( ...
- 常见排序算法-Python实现
常见排序算法-Python实现 python 排序 算法 1.二分法 python 32行 right = length- : ] ): test_list = [,,,,,, ...
- kmp算法python实现
kmp算法python实现 kmp算法 kmp算法用于字符串的模式匹配,也就是找到模式字符串在目标字符串的第一次出现的位置比如abababc那么bab在其位置1处,bc在其位置5处我们首先想到的最简单 ...
- KMP算法-Python版
KMP算法-Python版 传统法: 从左到右一个个匹配,如果这个过程中有某个字符不匹配,就跳回去,将模式串向右移动一位.这有什么难的? 我们可以 ...
- 压缩感知重构算法之IRLS算法python实现
压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...
- 压缩感知重构算法之OLS算法python实现
压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...
- 压缩感知重构算法之CoSaMP算法python实现
压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...
随机推荐
- HDU 1896 Stones --优先队列+搜索
一直向前搜..做法有点像模拟.但是要用到出队入队,有点像搜索. 代码: #include <iostream> #include <cstdio> #include <c ...
- [cb]ScriptableObject 序列化
ScriptableObject ScriptableObject是一个类,它允许你存储大量用于共享的数据独立脚本实例,不要迷惑这个类同样可以叫做 SerializableObject,可以理解成是一 ...
- Jenkins遇到问题一:jenkins配置权限不对导致无法登陆或者空白页面解决办法
找到.jenkins/config.xml文件:替换为:1.<authorizationStrategy class="hudson.security.AuthorizationStr ...
- javascript单元测试工具
单元测试关注的是验证一个模块或一段代码的执行效果是否和设计或预期一样.有些开发人员认为,编写测试用例浪费时间而宁愿去编写新的模块.然而,在处理大型应用程序时,单元测试实际上会节省时间:它能帮助您跟踪问 ...
- Android中static和final用法小结
Java关键字static.final使用小结 static 1. static变量 按照是否静态的对类成员变量进行分类可分两种:一种是被static修饰的变量,叫静态变量或类变量:另一种是 ...
- 微软职位内部推荐-Software Engineer II
微软近期Open的职位: Job Description Group: Search Technology Center Asia (STCA)/Search Ads Title: SDEII-Sen ...
- ls -F一种非常有用的ls格式
ls -F一种非常有用的ls格式 tz/y/yupeng > ls -F#q# News/ doc/ images/ mbox ...
- scrapy 爬取自己的博客
定义项目 # -*- coding: utf-8 -*- # items.py import scrapy class LianxiCnblogsItem(scrapy.Item): # define ...
- 《生活就像练习》读书笔记(一)——AQAL理论和象限
摘自<生活就像练习>肯威尔伯 著 北京:同心出版社,2012.6 AQAL整合理论 AQAL的意思是“所有象限.所有层面.所有路线.所有状态.所有类型”.练习的真正目的是:努力阐释瞬息万变 ...
- application/x-www-form-urlencoded multipart/form-data text/plain 后台返回的数据响应的格式类型
application/x-www-form-urlencoded multipart/form-data text/plain 为什么上传文件的表单里要加个属性 enctype 后台返回的数据响应 ...