细菌觅食算法-python实现
BFOIndividual.py
import numpy as np
import ObjFunction class BFOIndividual: '''
individual of baterial clony foraging 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 baterial clony foraging 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)
s1 = 0.
s2 = 1.
for i in range(1, self.vardim + 1):
s1 = s1 + self.chrom[i - 1] ** 2
s2 = s2 * np.cos(self.chrom[i - 1] / np.sqrt(i))
y = (1. / 4000.) * s1 - s2 + 1
self.fitness = y
BFO.py
import numpy as np
from BFOIndividual import BFOIndividual
import random
import copy
import matplotlib.pyplot as plt
import math class BacterialForagingOptimization: '''
The class for baterial foraging optimization algorithm
''' def __init__(self, sizepop, vardim, bound, params):
'''
sizepop: population sizepop
vardim: dimension of variables
bound: boundaries of variables
param: algorithm required parameters, it is a list which is consisting of [Ned, Nre, Nc, Ns, C, ped, d_attract, w_attract, d_repellant, w_repellant]
'''
self.sizepop = sizepop
self.vardim = vardim
self.bound = bound
self.population = []
self.bestPopulation = []
self.accuFitness = np.zeros(self.sizepop)
self.fitness = np.zeros(self.sizepop)
self.params = params
self.trace = np.zeros(
(self.params[0] * self.params[1] * self.params[2], 2)) def initialize(self):
'''
initialize the population
'''
for i in xrange(0, self.sizepop):
ind = BFOIndividual(self.vardim, self.bound)
ind.generate()
self.population.append(ind) def evaluate(self):
'''
evaluation of the population fitnesses
'''
for i in xrange(0, self.sizepop):
self.population[i].calculateFitness()
self.fitness[i] = self.population[i].fitness def sortPopulation(self):
'''
sort population according descending order
'''
sortedIdx = np.argsort(self.accuFitness)
newpop = []
newFitness = np.zeros(self.sizepop)
for i in xrange(0, self.sizepop):
ind = self.population[sortedIdx[i]]
newpop.append(ind)
self.fitness[i] = ind.fitness
self.population = newpop def solve(self):
'''
evolution process of baterial clony foraging algorithm
'''
self.t = 0
self.initialize()
self.evaluate()
bestIndex = np.argmin(self.fitness)
self.best = copy.deepcopy(self.population[bestIndex]) for i in xrange(0, self.params[0]):
for j in xrange(0, self.params[1]):
for k in xrange(0, self.params[2]):
self.t += 1
self.chemotaxls()
self.evaluate()
best = np.min(self.fitness)
bestIndex = np.argmin(self.fitness)
if best < self.best.fitness:
self.best = copy.deepcopy(self.population[bestIndex])
self.avefitness = np.mean(self.fitness)
self.trace[self.t - 1, 0] = self.best.fitness
self.trace[self.t - 1, 1] = self.avefitness
print("Generation %d: optimal function value is: %f; average function value is %f" % (
self.t, self.trace[self.t - 1, 0], self.trace[self.t - 1, 1]))
self.reproduction()
self.eliminationAndDispersal() print("Optimal function value is: %f; " %
self.trace[self.t - 1, 0])
print "Optimal solution is:"
print self.best.chrom
self.printResult() def chemotaxls(self):
'''
chemotaxls behavior of baterials
'''
for i in xrange(0, self.sizepop):
tmpInd = copy.deepcopy(self.population[i])
self.fitness[i] += self.communication(tmpInd)
Jlast = self.fitness[i]
rnd = np.random.uniform(low=-1, high=1.0, size=self.vardim)
phi = rnd / np.linalg.norm(rnd)
tmpInd.chrom += self.params[4] * phi
for k in xrange(0, self.vardim):
if tmpInd.chrom[k] < self.bound[0, k]:
tmpInd.chrom[k] = self.bound[0, k]
if tmpInd.chrom[k] > self.bound[1, k]:
tmpInd.chrom[k] = self.bound[1, k]
tmpInd.calculateFitness()
m = 0
while m < self.params[3]:
if tmpInd.fitness < Jlast:
Jlast = tmpInd.fitness
self.population[i] = copy.deepcopy(tmpInd)
# print m, Jlast
tmpInd.fitness += self.communication(tmpInd)
tmpInd.chrom += self.params[4] * phi
for k in xrange(0, self.vardim):
if tmpInd.chrom[k] < self.bound[0, k]:
tmpInd.chrom[k] = self.bound[0, k]
if tmpInd.chrom[k] > self.bound[1, k]:
tmpInd.chrom[k] = self.bound[1, k]
tmpInd.calculateFitness()
m += 1
else:
m = self.params[3]
self.fitness[i] = Jlast
self.accuFitness[i] += Jlast def communication(self, ind):
'''
cell to cell communication
'''
Jcc = 0.0
term1 = 0.0
term2 = 0.0
for j in xrange(0, self.sizepop):
term = 0.0
for k in xrange(0, self.vardim):
term += (ind.chrom[k] -
self.population[j].chrom[k]) ** 2
term1 -= self.params[6] * np.exp(-1 * self.params[7] * term)
term2 += self.params[8] * np.exp(-1 * self.params[9] * term)
Jcc = term1 + term2 return Jcc def reproduction(self):
'''
reproduction of baterials
'''
self.sortPopulation()
newpop = []
for i in xrange(0, self.sizepop / 2):
newpop.append(self.population[i])
for i in xrange(self.sizepop / 2, self.sizepop):
self.population[i] = newpop[i - self.sizepop / 2] def eliminationAndDispersal(self):
'''
elimination and dispersal of baterials
'''
for i in xrange(0, self.sizepop):
rnd = random.random()
if rnd < self.params[5]:
self.population[i].generate() def printResult(self):
'''
plot the result of the baterial clony foraging algorithm
'''
x = np.arange(0, self.t)
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(
"Baterial clony foraging algorithm for function optimization")
plt.legend()
plt.show()
运行程序:
if __name__ == "__main__": bound = np.tile([[-600], [600]], 25)
bfo = BFO(60, 25, bound, [2, 2, 50, 4, 50, 0.25, 0.1, 0.2, 0.1, 10])
bfo.solve()
ObjFunction见简单遗传算法-python实现。
细菌觅食算法-python实现的更多相关文章
- 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实现 压缩感知重构 ...
- 压缩感知重构算法之IHT算法python实现
压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...
- 压缩感知重构算法之SP算法python实现
压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...
随机推荐
- Floyd判最小环算法模板
算法思想:如果存在最小环,会在编号最大的点u更新最短路径前找到这个环,发现的方法是,更新最短路径前,遍历i,j点对,一定会发现某对i到j的最短路径长度dis[i][j]+mp[j][u]+mp[u][ ...
- JavaWeb学习之Servlet(三)----Servlet的映射匹配问题、线程安全问题
[声明] 欢迎转载,但请保留文章原始出处→_→ 文章来源:http://www.cnblogs.com/smyhvae/p/4140529.html 一.Servlet映射匹配问题: 在第一篇文章中的 ...
- 如何使用AutoIT完成单机测试
下面我们来介绍如何使用AutoIT完成单机程序的自动化测试.使用AutoIT完成桌面应用程序的自动化测试,最重要的是找到识别GUI对象的方法,然后调用AutoIT函数来操纵它或读取它的属性值,并与正确 ...
- 为什么需要DTO(数据传输对象)
DTO即数据传输对象.之前不明白有些框架中为什么要专门定义DTO来绑定表现层中的数据,为什么不能直接用实体模型呢,有了DTO同时还要维护DTO与Model之间的映射关系,多麻烦. 然后看了这篇文章中的 ...
- 以下是关于ASP.NET中保存各种信息的对象的比较,理解这些对象的原理,对制作完善的程序来说是相当有必要的(摘至互联网,并非原创--xukunping)
在ASP.NET中,有很多种保存信息的对象.例如:APPlication,Session,Cookie,ViewState和Cache等,那么它们有什么区别呢?每一种对象应用的环境是什么? 为了 ...
- OpenCV人脸检测demo--facedetect
&1 问题来源 在运行官网的facedetect这个demo的时候,总是不会出来result的图形,电脑右下角提示的错误是“显示器驱动程序已停止响应,而且已恢复 windows 8(R)”. ...
- Code First开发系列之管理并发和事务(转)
转自:http://www.cnblogs.com/farb/p/ConcurrencyAndTransctionManagement.html 返回<8天掌握EF的Code First开发&g ...
- 安装Ubuntu 16.04后要做的事
Ubuntu 16.04发布了,带来了很多新特性,同样也依然带着很多不习惯的东西,所以装完系统后还要进行一系列的优化. 1.删除libreoffice libreoffice虽然是开源的,但是Java ...
- Linux第二次报告20135221
学习计时:共xxx小时 读书: 代码: 作业: 博客: 一.学习目标 1. 熟悉Linux系统下的开发环境 2. 熟悉vi的基本操作 3. 熟悉gcc编译器的基本原理 4. 熟练使用gcc ...
- ios UILocalNotification的使用
iOS下的Notification的使用 Notification是智能手机应用编程中非常常用的一种传递信息的机制,而且可以非常好的节省资源,不用消耗资源来不停地检查信息状态(Pooling),在iO ...