倍受关注的群体智能算法可归纳为三类:
2000 年以后,研究者们相继提出了一系列新型群体智能算法叫。北京大学谭营教授等人于2010年在第一届国际群体智能大会上发表了烟花算法的第一篇学术论文,题为“Firew orks algorithm for optimization”"2。从此,业界开始关注烟花算法,并逐渐展开烟花算法在群体智能领域的研究。

下载的10年的谭营教授论文的思路的代码
下面有注释
# !usr/bin/env python
# -*- coding: utf-8 -*-
# Time : 2021/12/15 15:02
# @Author : LucXiong
# @Project : Model
# @File : FA.py
"""
Ref:https://github.com/GoodLittleStar/Fireworks/blob/master/FireWork.py
Ref:Tan Y, Zhu Y. Fireworks Algorithm for Optimization[M].
Lecture Notes in Computer Science. City: Springer Berlin Heidelberg, 2010: 355-64[2021-12-08T08:42:21].
"""
import random # random Function
import numpy as np # numpy operations
import copy
import matplotlib.pyplot as plt
import math
import test_function
class FA():
def __init__(self, pop_size=50, n_dim=2, m=50, a=0.04, b=0.8, A=40, lb=-1e5, ub=1e5, max_iter=1000, func=None):
self.a = a
self.b = b
self.m = m
self.A = A
self.pop = pop_size
self.dim = n_dim
self.func = func
self.max_iter = max_iter # max iter
self.epsino = 1e-6
self.mutate = 0.1
self.lb, self.ub = np.array(lb) * np.ones(self.dim), np.array(ub) * np.ones(self.dim)
assert self.dim == len(self.lb) == len(self.ub), 'dim == len(lb) == len(ub) is not True'
assert np.all(self.ub > self.lb), 'upper-bound must be greater than lower-bound'
self.X = np.random.uniform(low=self.lb, high=self.ub, size=(self.pop, self.dim)) #从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high.
self.X = self.X.tolist()
self.Y = [self.func(self.X[i]) for i in range(len(self.X))] # y = f(x) for all particles
self.bestindex = self.Y.index(min(self.Y))
self.gbest_x = self.X[self.bestindex]
self.gbest_y = min(self.Y) # global best y for all particles
self.gbest_y_hist = [self.gbest_y] # gbest_y of every iteration
# self.update_gbest()
def CalculateSi(self): #论文中有的,计算一个烟花产生的火花个数Si , Si也要满足范围的限制,公式2和公式3
self.MaxFitness = max(self.Y)
temp = 0.
self.Si = []
for i in range(0, self.pop):
temp = temp + self.MaxFitness - self.Y[i]
for i in range(0, self.pop):
self.Si.append(self.m * (self.MaxFitness - self.Y[i] + self.epsino) / (temp + self.epsino))
if self.Si[-1] < self.a * self.m:
self.Si[-1] = round(self.a * self.m)
elif self.Si[-1] > self.b * self.m:
self.Si[-1] = round(self.b * self.m)
else:
self.Si[-1] = round(self.Si[-1])
def CalculateExpo(self): #计算Ai ,振动幅度,使用公式4
self.MinFitness = min(self.Y)
temp = 0.
self.Ai = []
for i in range(self.pop):
temp = temp + self.Y[i] - self.MinFitness
#temp是求和后的值。
for i in range(self.pop):
self.Ai.append(self.A * (self.Y[i]- self.MinFitness + self.epsino) / (temp + self.epsino))
def Explosion(self): #算法1: obtain the location of a spark
for k in range(0, self.pop):
for i in range(self.Si[k]):
spark = copy.deepcopy(self.X[k]) #做一个拷贝的工作,但是X[k]的地址和spark的地址是不同的
z = round(self.dim * random.uniform(0, 1)) #z维度,随机(random)
dim_list = range(self.dim)
rand_z = random.sample(dim_list, z)
h = self.Ai[k] * random.uniform(-1, 1) #h 是高斯烟花,算法2里面,计算高斯烟花的爆炸系数
for j in rand_z:
spark[j] += h
if spark[j] < self.lb[j] or spark[j] > self.ub[j]: #根据算法来,如果超界下。需要修改spark[j]
spark[j] = self.lb[j] + abs(spark[j]) % (self.ub[j] - self.lb[j])
self.X.append(spark)
print(self.X)
self.Y.append(self.func(spark))
if(len(self.X) > 5 * self.pop):
break
def Mutation(self): #算法2: Obtain the location of a specific spark
currentsize = len(self.X)
for k in range(round(self.mutate * currentsize)):
randindex = random.randint(0, currentsize - 1)
spark = copy.deepcopy(self.X[randindex])
# print(spark)
# print(randindex)
z = round(self.dim * random.uniform(0, 1))
dim_list = range(self.dim)
rand_z = random.sample(dim_list, z)
g = random.gauss(1, 1)
for j in rand_z:
spark[j] *= g
if spark[j] < self.lb[j] or spark[j] > self.ub[j]: #超界
spark[j] = self.lb[j] + abs(spark[j]) % (self.ub[j] - self.lb[j])
self.X.append(spark)
self.Y.append(self.func(spark))
if (len(self.X) > 10 * self.pop):
break
def Selection(self): #2.3 Selction of Locations
newpop=[]
newpop.append(self.gbest_x)
self.Ri = []
for i in range(len(self.X)):
dis=0.
for j in range(len(self.X)):
for k in range(self.dim):
dis+= (self.X[i][k]-self.X[j][k])**2 # R[xi]
self.Ri.append(math.sqrt(dis))
sr = sum(self.Ri)
px = [self.Ri[i]/sr for i in range(len(self.Ri))] #概率P(xi),用一个列表存
for i in range(self.pop-1):
rr=random.uniform(0,1)
index=0
for j in range(self.pop):
if j==0 and rr<px[j]:
index=j
elif rr>=px[j] and rr<px[j+1]:
index=j+1
newpop.append(self.X[index])
self.X = newpop
self.Y = [self.func(self.X[i]) for i in range(len(self.X))]
def run(self):
for i in range(self.max_iter):
# print(i)
# print(len(self.X))
self.CalculateSi() #公式2和公式3
self.CalculateExpo() #公式4
self.Explosion() #算法1
# print(len(self.X))
self.Mutation() #算法2
# print(len(self.X))
bestindex = self.Y.index(min(self.Y)) #最小就是最好
if self.gbest_y_hist[-1] > self.Y[bestindex]:
self.gbest_y_hist.append(self.Y[bestindex])
self.gbest_x = self.X[bestindex]
else:
self.gbest_y_hist.append(self.gbest_y_hist[-1])
self.Selection()
# print(self.gbest_y_hist[-1])
return self.gbest_x, self.gbest_y_hist[-1]
if __name__ == '__main__':
n_dim = 3
lb = [-100 for i in range(n_dim)]
ub = [100 for i in range(n_dim)]
demo_func = test_function.fm2
pop_size = 10
max_iter = 20
fa = FA(n_dim=n_dim, pop_size=pop_size, max_iter=max_iter, lb=lb, ub=ub, func=demo_func) #初始化烟花类
best_x, bext_y = fa.run()
print(f'{demo_func(fa.gbest_x)}\t{fa.gbest_x}')
plt.plot(fa.gbest_y_hist)
plt.show()