AFSIndividual.py

 import numpy as np
import ObjFunction
import copy class AFSIndividual: """class for AFSIndividual""" def __init__(self, vardim, bound):
'''
vardim: dimension of variables
bound: boundaries of variables
'''
self.vardim = vardim
self.bound = bound def generate(self):
'''
generate a rondom chromsome
'''
len = self.vardim
rnd = np.random.random(size=len)
self.chrom = np.zeros(len)
self.velocity = np.random.random(size=len)
for i in xrange(0, len):
self.chrom[i] = self.bound[0, i] + \
(self.bound[1, i] - self.bound[0, i]) * rnd[i]
self.bestPosition = np.zeros(len)
self.bestFitness = 0. def calculateFitness(self):
'''
calculate the fitness of the chromsome
'''
self.fitness = ObjFunction.GrieFunc(
self.vardim, self.chrom, self.bound)

AFS.py

 import numpy as np
from AFSIndividual import AFSIndividual
import random
import copy
import matplotlib.pyplot as plt class ArtificialFishSwarm: """class for ArtificialFishSwarm""" def __init__(self, sizepop, vardim, bound, MAXGEN, params):
'''
sizepop: population sizepop
vardim: dimension of variables
bound: boundaries of variables, 2*vardim
MAXGEN: termination condition
params: algorithm required parameters, it is a list which is consisting of[visual, step, delta, trynum]
'''
self.sizepop = sizepop
self.vardim = vardim
self.bound = bound
self.MAXGEN = MAXGEN
self.params = params
self.population = []
self.fitness = np.zeros((self.sizepop, 1))
self.trace = np.zeros((self.MAXGEN, 2))
self.lennorm = 6000 def initialize(self):
'''
initialize the population of afs
'''
for i in xrange(0, self.sizepop):
ind = AFSIndividual(self.vardim, self.bound)
ind.generate()
self.population.append(ind) def evaluation(self, x):
'''
evaluation the fitness of the individual
'''
x.calculateFitness() def forage(self, x):
'''
artificial fish foraging behavior
'''
newInd = copy.deepcopy(x)
found = False
for i in xrange(0, self.params[3]):
indi = self.randSearch(x, self.params[0])
if indi.fitness > x.fitness:
newInd.chrom = x.chrom + np.random.random(self.vardim) * self.params[1] * self.lennorm * (
indi.chrom - x.chrom) / np.linalg.norm(indi.chrom - x.chrom)
newInd = indi
found = True
break
if not (found):
newInd = self.randSearch(x, self.params[1])
return newInd def randSearch(self, x, searLen):
'''
artificial fish random search behavior
'''
ind = copy.deepcopy(x)
ind.chrom += np.random.uniform(-1, 1,
self.vardim) * searLen * self.lennorm
for j in xrange(0, self.vardim):
if ind.chrom[j] < self.bound[0, j]:
ind.chrom[j] = self.bound[0, j]
if ind.chrom[j] > self.bound[1, j]:
ind.chrom[j] = self.bound[1, j]
self.evaluation(ind)
return ind def huddle(self, x):
'''
artificial fish huddling behavior
'''
newInd = copy.deepcopy(x)
dist = self.distance(x)
index = []
for i in xrange(1, self.sizepop):
if dist[i] > 0 and dist[i] < self.params[0] * self.lennorm:
index.append(i)
nf = len(index)
if nf > 0:
xc = np.zeros(self.vardim)
for i in xrange(0, nf):
xc += self.population[index[i]].chrom
xc = xc / nf
cind = AFSIndividual(self.vardim, self.bound)
cind.chrom = xc
cind.calculateFitness()
if (cind.fitness / nf) > (self.params[2] * x.fitness):
xnext = x.chrom + np.random.random(
self.vardim) * self.params[1] * self.lennorm * (xc - x.chrom) / np.linalg.norm(xc - x.chrom)
for j in xrange(0, self.vardim):
if xnext[j] < self.bound[0, j]:
xnext[j] = self.bound[0, j]
if xnext[j] > self.bound[1, j]:
xnext[j] = self.bound[1, j]
newInd.chrom = xnext
self.evaluation(newInd)
# print "hudding"
return newInd
else:
return self.forage(x)
else:
return self.forage(x) def follow(self, x):
'''
artificial fish following behivior
'''
newInd = copy.deepcopy(x)
dist = self.distance(x)
index = []
for i in xrange(1, self.sizepop):
if dist[i] > 0 and dist[i] < self.params[0] * self.lennorm:
index.append(i)
nf = len(index)
if nf > 0:
best = -999999999.
bestIndex = 0
for i in xrange(0, nf):
if self.population[index[i]].fitness > best:
best = self.population[index[i]].fitness
bestIndex = index[i]
if (self.population[bestIndex].fitness / nf) > (self.params[2] * x.fitness):
xnext = x.chrom + np.random.random(
self.vardim) * self.params[1] * self.lennorm * (self.population[bestIndex].chrom - x.chrom) / np.linalg.norm(self.population[bestIndex].chrom - x.chrom)
for j in xrange(0, self.vardim):
if xnext[j] < self.bound[0, j]:
xnext[j] = self.bound[0, j]
if xnext[j] > self.bound[1, j]:
xnext[j] = self.bound[1, j]
newInd.chrom = xnext
self.evaluation(newInd)
# print "follow"
return newInd
else:
return self.forage(x)
else:
return self.forage(x) def solve(self):
'''
evolution process for afs algorithm
'''
self.t = 0
self.initialize()
# evaluation the population
for i in xrange(0, self.sizepop):
self.evaluation(self.population[i])
self.fitness[i] = self.population[i].fitness
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
# newpop = []
for i in xrange(0, self.sizepop):
xi1 = self.huddle(self.population[i])
xi2 = self.follow(self.population[i])
if xi1.fitness > xi2.fitness:
self.population[i] = xi1
self.fitness[i] = xi1.fitness
else:
self.population[i] = xi2
self.fitness[i] = xi2.fitness
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 distance(self, x):
'''
return the distance array to a individual
'''
dist = np.zeros(self.sizepop)
for i in xrange(0, self.sizepop):
dist[i] = np.linalg.norm(x.chrom - self.population[i].chrom) / 6000
return dist def printResult(self):
'''
plot the result of afs 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 Fish Swarm algorithm for function optimization")
plt.legend()
plt.show()

运行程序:

 if __name__ == "__main__":

     bound = np.tile([[-600], [600]], 25)
afs = AFS(60, 25, bound, 500, [0.001, 0.0001, 0.618, 40])
afs.solve()

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

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

  1. 人工蜂群算法-python实现

    ABSIndividual.py import numpy as np import ObjFunction class ABSIndividual: ''' individual of artifi ...

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

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

  3. 人工鱼群算法超详细解析附带JAVA代码

    01 前言 本着学习的心态,还是想把这个算法写一写,给大家科普一下的吧. 02 人工鱼群算法 2.1 定义 人工鱼群算法为山东大学副教授李晓磊2002年从鱼找寻食物的现象中表现的种种移动寻觅特点中得到 ...

  4. pageRank算法 python实现

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

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

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

  6. kmp算法python实现

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

  7. KMP算法-Python版

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

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

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

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

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

随机推荐

  1. 数字对 (长乐一中模拟赛day2T2)

    2.数字对 [题目描述] 小H是个善于思考的学生,现在她又在思考一个有关序列的问题. 她的面前浮现出一个长度为n的序列{ai},她想找出一段区间[L, R](1 <= L <= R < ...

  2. [3D跑酷] UI事件处理系统

    在我们的Unity游戏项目中,GUI的表现采用NGUI.记录一下我们的处理方式: 需要解决的问题 1.需要处理大量按钮的点击事件 2.需要处理界面跳转事件 3.需要处理界面元素更新事件 解决方案 GU ...

  3. [转]Rapid Reporter——轻量级ET测试记录工具

    下载地址:http://testing.gershon.info/reporter/ 特别感谢:邰晓梅老师 在一次ET的在线培训课程,邰晓梅老师使用的是这个工具. Rapid Reproter,是一款 ...

  4. smarty变量调节器

    smarty中变量调解器的作用:在模板中需要对PHP分配过来的变量在输出之前,对变量进行处理 注册变量调解器方式:$smarty->registerPlugin("modifier&q ...

  5. mysqli_stmt预处理类

    <?php  $mysqli=new mysqli("localhost", "root", "123456", "xsph ...

  6. python算法:rangeBitwiseAnd(连续整数的与)

    def rangeBitwiseAnd(self, m, n): i = 0 while m != n: m >>= 1 n >>= 1 i += 1 return n < ...

  7. NOI 1.7编程基础之字符串(35题)

    01:统计数字字符个数 查看 提交 统计 提问 总时间限制:  1000ms 内存限制:  65536kB 描述 输入一行字符,统计出其中数字字符的个数. 输入 一行字符串,总长度不超过255. 输出 ...

  8. JS框架之收集专帖

    1.KNOCKOUT.JS 官网:http://knockoutjs.com/ 学习:http://www.cnblogs.com/TomXu/archive/2011/11/21/2257154.h ...

  9. [6]Telerik TreeView 复选框

    参考连接:http://demos.telerik.com/aspnet-mvc/razor/treeview/clientsideapi 问题: Telerik TreeView 选择或取消 父选项 ...

  10. Console的使用——Google Chrome代码调试

    Google Chrome控制台为开发者提供了网页和应用程序调试的几种方法,本文通过基本操作.控制台API.命令行API来介绍控制台的使用. 基本操作 1.开启控制台     可以通过下列三种方式开启 ...