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. POJ 2449 Remmarguts' Date --K短路

    题意就是要求第K短的路的长度(S->T). 对于K短路,朴素想法是bfs,使用优先队列从源点s进行bfs,当第K次遍历到T的时候,就是K短路的长度. 但是这种方法效率太低,会扩展出很多状态,所以 ...

  2. YOU ARE MY SUNSHINE

    /*you are sunshine, my only sunshine, you make me happy when skies are grey. you'll never know dear ...

  3. Flash Builder快捷键

    代码助手:Ctrl+Space(简体中文操作系统是Alt+/)快速修正:Ctrl+1单词补全:Alt+/打开外部Java文档:Shift+F2 显示搜索对话框:Ctrl+H快速Outline:Ctrl ...

  4. java11-4 字符串的遍历以及字符串中各类字符的统计

    1.需求:获取字符串中的每一个字符   分析: A:如何能够拿到每一个字符呢?  char charAt(int index) B:我怎么知道字符到底有多少个呢? int length() publi ...

  5. win10自动更新彻底关闭

    http://app.techweb.com.cn/wp/2016-10-24/2418646.shtml

  6. Gradle的HelloWorld

    Gradle的脚本名为  build.gradle task hello{ doLast{ println("Hello World") } } 运行:gradle -q hell ...

  7. 微软职位内部推荐-Senior Development Engineer

    微软近期Open的职位: Job Title: Senior Software Development Engineering Work Location: Suzhou, China Enterpr ...

  8. memcached缓存失效时的高并发访问问题解决

    memcached一般用于在访问一些性能相对低下的数据接口时(如数据库),为了保证这些数据接口的稳定性,加上memcached以减少访问次数,保证这些数据接口的健壮性.一般memcached的数据都是 ...

  9. VBA的一些使用心得

    VBA的知识比较零散,因此开一贴记录一下使用VBA时的一些方法和心得.主要针对Excel,参考在这里 1. Collection Class 大部分情况下,Collection Class是比数组(A ...

  10. Go视频教程整理

    [Go Web基础]01博客项目设计 |Go视频教程|Go语言基础 http://www.tudou.com/programs/view/gXZb9tGNsGU/ [Go Web基础]02初窥 Web ...