FAIndividual.py

 import numpy as np
import ObjFunction class FAIndividual: '''
individual of firefly 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 firefly 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)

FA.py

 import numpy as np
from FAIndividual import FAIndividual
import random
import copy
import matplotlib.pyplot as plt class FireflyAlgorithm: '''
The class for firefly algorithm
''' def __init__(self, sizepop, vardim, bound, MAXGEN, params):
'''
sizepop: population sizepop
vardim: dimension of variables
bound: boundaries of variables
MAXGEN: termination condition
param: algorithm required parameters, it is a list which is consisting of [beta0, gamma, alpha]
'''
self.sizepop = sizepop
self.MAXGEN = MAXGEN
self.vardim = vardim
self.bound = bound
self.population = []
self.fitness = np.zeros((self.sizepop, 1))
self.trace = np.zeros((self.MAXGEN, 2))
self.params = params def initialize(self):
'''
initialize the population
'''
for i in xrange(0, self.sizepop):
ind = FAIndividual(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 solve(self):
'''
evolution process of firefly algorithm
'''
self.t = 0
self.initialize()
self.evaluate()
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.move()
self.evaluate()
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 move(self):
'''
move the a firefly to another brighter firefly
'''
for i in xrange(0, self.sizepop):
for j in xrange(0, self.sizepop):
if self.fitness[j] > self.fitness[i]:
r = np.linalg.norm(
self.population[i].chrom - self.population[j].chrom)
beta = self.params[0] * \
np.exp(-1 * self.params[1] * (r ** 2))
# beta = 1 / (1 + self.params[1] * r)
# print beta
self.population[i].chrom += beta * (self.population[j].chrom - self.population[
i].chrom) + self.params[2] * np.random.uniform(low=-1, high=1, size=self.vardim)
for k in xrange(0, self.vardim):
if self.population[i].chrom[k] < self.bound[0, k]:
self.population[i].chrom[k] = self.bound[0, k]
if self.population[i].chrom[k] > self.bound[1, k]:
self.population[i].chrom[k] = self.bound[1, k]
self.population[i].calculateFitness()
self.fitness[i] = self.population[i].fitness def printResult(self):
'''
plot the result of the firefly 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("Firefly Algorithm for function optimization")
plt.legend()
plt.show()

运行程序:

 if __name__ == "__main__":

     bound = np.tile([[-600], [600]], 25)
fa = FA(60, 25, bound, 200, [1.0, 0.000001, 0.6])
fa.solve()

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

萤火虫算法-python实现的更多相关文章

  1. pageRank算法 python实现

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

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

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

  3. kmp算法python实现

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

  4. KMP算法-Python版

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

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

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

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

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

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

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

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

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

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

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

随机推荐

  1. 基础KMP两道

    1. HDU 1711 Number Sequence 代码: #include <iostream> #include <cstdio> #include <cstri ...

  2. Android系列之网络(三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  3. 文件泄露&php代码审计

    这道题,还是很不错的.卡在了token绕过那里,不得已看了别人的writeUp,才做出来,惭愧! 但还是想写写WriteUp做一下记录! 首先是打开题目,习惯性查看源码,发现了点蛛丝马迹 知道了,管理 ...

  4. 只有图片拼接的html页面图片之间有白条的解决方法

    有时候会有这样的页面,整个页面也就是几张切好的图片组成,但是把这些图片使用代码拼接好,又总会出现图片间有白条的问题,如下图: 解决方法:给图片的父容器添加 line-height: 0; 就好了,因为 ...

  5. 关联:objc_getAssociatedObject和objc_setAssociatedObject使用

    为UIButton的category添加属性 UIButton+subTitle.h #import <UIKit/UIKit.h> #import <objc/runtime.h& ...

  6. The Linux Storage Stack Diagram

    相关文章: 如何提高Linux下块设备IO的整体性能?

  7. flex 3 rows layout

    html,body{height:100%} .wraper{ display:flex; flex-direction:column; height:100%; flex-wrap: nowrap; ...

  8. 将Axure用于需求分析工具

    http://www.cnblogs.com/hnlong1/p/4113517.html?utm_source=tuicool 今年以来开始接触需求分析工作,uml是必用的建模语言. 一开始是使用最 ...

  9. Jsoup开发简单网站客户端之读取本地html文件

    用jsoup解析网页,相比于那些返回api数据来说 肯定耗流量,加载慢,所以程序assts中预先放了一个最新的html文件,第一次进来不走网络,直接从本地取,以后会加上wifi离线功能. 首先离线网站 ...

  10. [CareerCup] 14.5 Object Reflection 对象反射

    14.5 Explain what object reflection is in Java and why it is useful. Java中的对象反射机制可以获得Java类和对象的反射信息,并 ...