人工鱼群算法-python实现

AFSIndividual.py

 1 import numpy as np
 2 import ObjFunction
 3 import copy
 4
 5
 6 class AFSIndividual:
 7
 8     """class for AFSIndividual"""
 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
18     def generate(self):
19         ‘‘‘
20         generate a rondom chromsome
21         ‘‘‘
22         len = self.vardim
23         rnd = np.random.random(size=len)
24         self.chrom = np.zeros(len)
25         self.velocity = np.random.random(size=len)
26         for i in xrange(0, len):
27             self.chrom[i] = self.bound[0, i] + 28                 (self.bound[1, i] - self.bound[0, i]) * rnd[i]
29         self.bestPosition = np.zeros(len)
30         self.bestFitness = 0.
31
32     def calculateFitness(self):
33         ‘‘‘
34         calculate the fitness of the chromsome
35         ‘‘‘
36         self.fitness = ObjFunction.GrieFunc(
37             self.vardim, self.chrom, self.bound)

AFS.py

  1 import numpy as np
  2 from AFSIndividual import AFSIndividual
  3 import random
  4 import copy
  5 import matplotlib.pyplot as plt
  6
  7
  8 class ArtificialFishSwarm:
  9
 10     """class for  ArtificialFishSwarm"""
 11
 12     def __init__(self, sizepop, vardim, bound, MAXGEN, params):
 13         ‘‘‘
 14         sizepop: population sizepop
 15         vardim: dimension of variables
 16         bound: boundaries of variables, 2*vardim
 17         MAXGEN: termination condition
 18         params: algorithm required parameters, it is a list which is consisting of[visual, step, delta, trynum]
 19         ‘‘‘
 20         self.sizepop = sizepop
 21         self.vardim = vardim
 22         self.bound = bound
 23         self.MAXGEN = MAXGEN
 24         self.params = params
 25         self.population = []
 26         self.fitness = np.zeros((self.sizepop, 1))
 27         self.trace = np.zeros((self.MAXGEN, 2))
 28         self.lennorm = 6000
 29
 30     def initialize(self):
 31         ‘‘‘
 32         initialize the population of afs
 33         ‘‘‘
 34         for i in xrange(0, self.sizepop):
 35             ind = AFSIndividual(self.vardim, self.bound)
 36             ind.generate()
 37             self.population.append(ind)
 38
 39     def evaluation(self, x):
 40         ‘‘‘
 41         evaluation the fitness of the individual
 42         ‘‘‘
 43         x.calculateFitness()
 44
 45     def forage(self, x):
 46         ‘‘‘
 47         artificial fish foraging behavior
 48         ‘‘‘
 49         newInd = copy.deepcopy(x)
 50         found = False
 51         for i in xrange(0, self.params[3]):
 52             indi = self.randSearch(x, self.params[0])
 53             if indi.fitness > x.fitness:
 54                 newInd.chrom = x.chrom + np.random.random(self.vardim) * self.params[1] * self.lennorm * (
 55                     indi.chrom - x.chrom) / np.linalg.norm(indi.chrom - x.chrom)
 56                 newInd = indi
 57                 found = True
 58                 break
 59         if not (found):
 60             newInd = self.randSearch(x, self.params[1])
 61         return newInd
 62
 63     def randSearch(self, x, searLen):
 64         ‘‘‘
 65         artificial fish random search behavior
 66         ‘‘‘
 67         ind = copy.deepcopy(x)
 68         ind.chrom += np.random.uniform(-1, 1,
 69                                        self.vardim) * searLen * self.lennorm
 70         for j in xrange(0, self.vardim):
 71             if ind.chrom[j] < self.bound[0, j]:
 72                 ind.chrom[j] = self.bound[0, j]
 73             if ind.chrom[j] > self.bound[1, j]:
 74                 ind.chrom[j] = self.bound[1, j]
 75         self.evaluation(ind)
 76         return ind
 77
 78     def huddle(self, x):
 79         ‘‘‘
 80         artificial fish huddling behavior
 81         ‘‘‘
 82         newInd = copy.deepcopy(x)
 83         dist = self.distance(x)
 84         index = []
 85         for i in xrange(1, self.sizepop):
 86             if dist[i] > 0 and dist[i] < self.params[0] * self.lennorm:
 87                 index.append(i)
 88         nf = len(index)
 89         if nf > 0:
 90             xc = np.zeros(self.vardim)
 91             for i in xrange(0, nf):
 92                 xc += self.population[index[i]].chrom
 93             xc = xc / nf
 94             cind = AFSIndividual(self.vardim, self.bound)
 95             cind.chrom = xc
 96             cind.calculateFitness()
 97             if (cind.fitness / nf) > (self.params[2] * x.fitness):
 98                 xnext = x.chrom + np.random.random(
 99                     self.vardim) * self.params[1] * self.lennorm * (xc - x.chrom) / np.linalg.norm(xc - x.chrom)
100                 for j in xrange(0, self.vardim):
101                     if xnext[j] < self.bound[0, j]:
102                         xnext[j] = self.bound[0, j]
103                     if xnext[j] > self.bound[1, j]:
104                         xnext[j] = self.bound[1, j]
105                 newInd.chrom = xnext
106                 self.evaluation(newInd)
107                 # print "hudding"
108                 return newInd
109             else:
110                 return self.forage(x)
111         else:
112             return self.forage(x)
113
114     def follow(self, x):
115         ‘‘‘
116         artificial fish following behivior
117         ‘‘‘
118         newInd = copy.deepcopy(x)
119         dist = self.distance(x)
120         index = []
121         for i in xrange(1, self.sizepop):
122             if dist[i] > 0 and dist[i] < self.params[0] * self.lennorm:
123                 index.append(i)
124         nf = len(index)
125         if nf > 0:
126             best = -999999999.
127             bestIndex = 0
128             for i in xrange(0, nf):
129                 if self.population[index[i]].fitness > best:
130                     best = self.population[index[i]].fitness
131                     bestIndex = index[i]
132             if (self.population[bestIndex].fitness / nf) > (self.params[2] * x.fitness):
133                 xnext = x.chrom + np.random.random(
134                     self.vardim) * self.params[1] * self.lennorm * (self.population[bestIndex].chrom - x.chrom) / np.linalg.norm(self.population[bestIndex].chrom - x.chrom)
135                 for j in xrange(0, self.vardim):
136                     if xnext[j] < self.bound[0, j]:
137                         xnext[j] = self.bound[0, j]
138                     if xnext[j] > self.bound[1, j]:
139                         xnext[j] = self.bound[1, j]
140                 newInd.chrom = xnext
141                 self.evaluation(newInd)
142                 # print "follow"
143                 return newInd
144             else:
145                 return self.forage(x)
146         else:
147             return self.forage(x)
148
149     def solve(self):
150         ‘‘‘
151         evolution process for afs algorithm
152         ‘‘‘
153         self.t = 0
154         self.initialize()
155         # evaluation the population
156         for i in xrange(0, self.sizepop):
157             self.evaluation(self.population[i])
158             self.fitness[i] = self.population[i].fitness
159         best = np.max(self.fitness)
160         bestIndex = np.argmax(self.fitness)
161         self.best = copy.deepcopy(self.population[bestIndex])
162         self.avefitness = np.mean(self.fitness)
163         self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
164         self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
165         print("Generation %d: optimal function value is: %f; average function value is %f" % (
166             self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
167         while self.t < self.MAXGEN - 1:
168             self.t += 1
169             # newpop = []
170             for i in xrange(0, self.sizepop):
171                 xi1 = self.huddle(self.population[i])
172                 xi2 = self.follow(self.population[i])
173                 if xi1.fitness > xi2.fitness:
174                     self.population[i] = xi1
175                     self.fitness[i] = xi1.fitness
176                 else:
177                     self.population[i] = xi2
178                     self.fitness[i] = xi2.fitness
179             best = np.max(self.fitness)
180             bestIndex = np.argmax(self.fitness)
181             if best > self.best.fitness:
182                 self.best = copy.deepcopy(self.population[bestIndex])
183             self.avefitness = np.mean(self.fitness)
184             self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness
185             self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness
186             print("Generation %d: optimal function value is: %f; average function value is %f" % (
187                 self.t, self.trace[self.t, 0], self.trace[self.t, 1]))
188
189         print("Optimal function value is: %f; " % self.trace[self.t, 0])
190         print "Optimal solution is:"
191         print self.best.chrom
192         self.printResult()
193
194     def distance(self, x):
195         ‘‘‘
196         return the distance array to a individual
197         ‘‘‘
198         dist = np.zeros(self.sizepop)
199         for i in xrange(0, self.sizepop):
200             dist[i] = np.linalg.norm(x.chrom - self.population[i].chrom) / 6000
201         return dist
202
203     def printResult(self):
204         ‘‘‘
205         plot the result of afs algorithm
206         ‘‘‘
207         x = np.arange(0, self.MAXGEN)
208         y1 = self.trace[:, 0]
209         y2 = self.trace[:, 1]
210         plt.plot(x, y1, ‘r‘, label=‘optimal value‘)
211         plt.plot(x, y2, ‘g‘, label=‘average value‘)
212         plt.xlabel("Iteration")
213         plt.ylabel("function value")
214         plt.title("Artificial Fish Swarm algorithm for function optimization")
215         plt.legend()
216         plt.show()

运行程序:

1 if __name__ == "__main__":
2
3     bound = np.tile([[-600], [600]], 25)
4     afs = AFS(60, 25, bound, 500, [0.001, 0.0001, 0.618, 40])
5     afs.solve()

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

时间: 2025-01-05 02:49:09

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

人工鱼群算法简介及应用

简介 定义 人工鱼群算法为山东大学副教授李晓磊2002年从鱼找寻食物的现象中表现的种种移动寻觅特点中得到启发而阐述的仿生学优化方案.在一片水域中,鱼往往能自行或尾随其他鱼找到营养物质多的地方,因而鱼生存数目最多的地方一般就是本水域中营养物质最多的地方,人工鱼群算法就是根据这一特点,通过构造人工鱼来模仿鱼群的觅食.聚群及追尾行为,从而实现寻优.人工鱼拥有以下几种典型行为: /p> (1)觅食行为:一般情况下鱼在水中随机地自由游动,当发现食物时,则会向食物逐渐增多的方向快速游去. (2)聚群行为:鱼

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

其实一直以来也没有准备在园子里发这样的文章,相对来说,算法改进放在园子里还是会稍稍显得格格不入.但是最近邮箱收到的几封邮件让我觉得有必要通过我的博客把过去做过的东西分享出去更给更多需要的人.从论文刊登后,陆陆续续收到本科生.研究生还有博士生的来信和短信微信等,表示了对论文的兴趣以及寻求算法的效果和实现细节,所以,我也就通过邮件或者短信微信来回信,但是有时候也会忘记回复. 另外一个原因也是时间久了,我对于论文以及改进的算法的记忆也越来越模糊,或者那天无意间把代码遗失在哪个角落,真的很难想象我还会全

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

01 前言 本着学习的心态,还是想把这个算法写一写,给大家科普一下的吧. 02 人工鱼群算法 2.1 定义 人工鱼群算法为山东大学副教授李晓磊2002年从鱼找寻食物的现象中表现的种种移动寻觅特点中得到启发而阐述的仿生学优化方案.在一片水域中,鱼往往能自行或尾随其他鱼找到营养物质多的地方,因而鱼生存数目最多的地方一般就是本水域中营养物质最多的地方,人工鱼群算法就是根据这一特点,通过构造人工鱼来模仿鱼群的觅食.聚群及追尾行为,从而实现寻优.人工鱼拥有以下几种典型行为: (1)觅食行为:一般情况下鱼在

MATLAB面向对象编程实现鱼群算法

计划10天完成初稿. day1 今天第一天的目标是安装好MATLAB,了解鱼群算法,并且复习MATLAB的知识. 这个MATLAB版本应该是比较基础的,不过对菜鸟来说应该足够了, 祭出网址: 下载及说明:http://www.pc6.com/softview/SoftView_4819.html#download 下载的百度云链接:http://pan.baidu.com/s/1AbsJk

【机器学习算法-python实现】采样算法的简单实现

1.背景 采样算法是机器学习中比较常用,也比较容易实现的(出去分层采样).常用的采样算法有以下几种(来自百度知道): 一.单纯随机抽样(simple random sampling) 将调查总体全部观察单位编号,再用抽签法或随机数字表随机抽取部分观察单位组成样本. 优点:操作简单,均数.率及相应的标准误计算简单. 缺点:总体较大时,难以一一编号. 二.系统抽样(systematic sampling) 又称机械抽样.等距抽样,即先将总体的观察单位按某一顺序号分成n个部分,再从第一部分随机抽取第k

【机器学习算法-python实现】矩阵去噪以及归一化

1.背景 项目需要,打算用python实现矩阵的去噪和归一化.用numpy这些数学库没有找到很理想的函数,所以一怒之下自己用标准库写了一个去噪和归一化的算法,效率有点低,不过还能用,大家如果有需要可以拿去. (1)去噪算法:根据概率论的知识,如果一组数据服从正态分布,我们设均值是n,方差是v,那么对于每个离散数值有百分之九十二以上的概率会在(n-3*v,n+3*v)的区间内.所以这里的去噪功能主要是实现如果超出了区间就将这个值标记为区间所能容忍最大值. (2)归一化:找到输入队列最大值max,最

【机器学习算法-python实现】协同过滤(cf)的三种方法实现

(转载请注明出处:http://blog.csdn.net/buptgshengod) 1.背景 协同过滤(collaborative filtering)是推荐系统常用的一种方法.cf的主要思想就是找出物品相似度高的归为一类进行推荐.cf又分为icf和ucf.icf指的是item collaborative filtering,是将商品进行分析推荐.同理ucf的u指的是user,他是找出知趣相似的人,进行推荐.通常来讲icf的准确率可能会高一些,通过这次参加天猫大数据比赛,我觉得只有在数据量非

【机器学习算法-python实现】svm支持向量机(2)—简化版SMO算法

(转载请注明出处:http://blog.csdn.net/buptgshengod) 1.背景知识 通过上一节我们通过引入拉格朗日乗子得到支持向量机变形公式.详细变法可以参考这位大神的博客--地址 参照拉格朗日公式F(x1,x2,...λ)=f(x1,x2,...)-λg(x1,x2...).我们把上面的式子变型为: 约束条件就变成了: 下面就根据最小优化算法SMO(Sequential Minimal Optimization).找出距离分隔面最近的点,也就是支持向量集.如下图的蓝色点所示.

【机器学习算法-python实现】K-means无监督学习实现分类

1.背景 无监督学习的定义就不多说了,不懂得可以google.因为项目需要,需要进行无监督的分类学习. K-means里面的K指的是将数据分成的份数,基本上用的就是算距离的方法. 大致的思路就是给定一个矩阵,假设K的值是2,也就是分成两个部分,那么我们首先确定两个质心.一开始是找矩阵每一列的最大值max,最小值min,算出range=max-min,然后设质心就是min+range*random.之后在逐渐递归跟进,其实要想明白还是要跟一遍代码,自己每一步都输出一下看看跟自己想象的是否一样. (