#库的导入
import numpy as np
import matplotlib.pyplot as plt
import heapq
#待求解问题,求解问题为求最小值
def function(x):
y1 = 0
for i in range(len(x)-1):
y2 = 100*((x[i+1] - x[i]**2)**2)+(x[i]-1)**2
y1 = y1 + y2
y = abs(0 - y1)
return y
m = 30 #种群数量
imax = 100 #迭代次数
dimen = 20 #解的搜索维度
rangelow = -10 #解的最小取值
rangehigh = 10 #解的最大取值
amax = 2 #系数向量初始值
#pop用于存储种群个体的位置信息,pop_fitness用于存储个体对应的适应度值
pop = np.zeros((m,dimen))
pop_fitness = np.zeros(m)
#对种群个体进行初始化并计算对应适应度值
for j in range(m):
pop[j] = np.random.uniform(low=rangelow, high=rangehigh,size=(1, dimen))
pop_fitness[j] = function(pop[j])
#allbestpop,allbestfit分别存储种群在历史迭代过程中最优个体解及对应适应度
allbestpop,allbestfit = pop[pop_fitness.argmin()].copy(),pop_fitness.min()
#通过排序找出种群中适应度值最优的前三个个体,并获得它们的位置信息
pop_fitness1 = pop_fitness.flatten()
pop_fitness1 = pop_fitness1.tolist()
three = list(map(pop_fitness1.index, heapq.nsmallest(3, pop_fitness1)))
Xalpha = pop[three[0]]
Xbeta = pop[three[1]]
Xdelta = pop[three[2]]
#his_bestfit存储每次迭代时种群历史适应度值最优的个体适应度
his_bestfit=np.zeros(imax)
#开始训练
for i in range(imax):
print("The iteration is:", i + 1)
#对系数向量的计算参数a进行计算
iratio = i / imax
a = amax * (1 - iratio)
#对每个个体进行位置更新
for j in range(m):
#分别计算在适应度值最优的前三个个体的影响下,个体的位置移动量X1、X2、X3
C1 = 2 * np.random.rand()
Dalpha = np.abs(C1 * Xalpha - pop[j])
A1 = 2 * a * np.random.rand() - a
X1 = Xalpha - A1 * Dalpha
C2 = 2 * np.random.rand()
Dbeta = np.abs(C2 * Xbeta - pop[j])
A2 = 2 * a * np.random.rand() - a
X2 = Xbeta - A2 * Dbeta
C3 = 2 * np.random.rand()
Ddelta = np.abs(C3 * Xdelta - pop[j])
A3 = 2 * a * np.random.rand() - a
X3 = Xdelta - A3 * Ddelta
#计算个体移动后的位置及适应度值
pop[j] = (X1 + X2 + X3) / 3
pop_fitness[j] = function(pop[j])
#对种群历史最优位置信息与适应度值进行更新
if pop_fitness.min() < allbestfit:
allbestfit = pop_fitness.min()
allbestpop = pop[pop_fitness.argmin()].copy()
#通过排序找出种群中适应度值最优的前三个个体,并获得它们的位置信息
pop_fitness1 = pop_fitness.flatten()
pop_fitness1 = pop_fitness1.tolist()
three = list(map(pop_fitness1.index, heapq.nsmallest(3, pop_fitness1)))
Xalpha = pop[three[0]]
Xbeta = pop[three[1]]
Xdelta = pop[three[2]]
#存储当前迭代下的种群历史最优适应度值并输出
his_bestfit[i] = allbestfit
print("The best fitness is:", allbestfit)
print("After iteration, the best pop is:",allbestpop)
print("After iteration, the best fitness is:","%e"%allbestfit)
#输出训练后种群个体适应度值的均值与标准差
mean = np.sum(pop_fitness)/m
std = np.std(pop_fitness)
print("After iteration, the mean fitness of the swarm is:","%e"%mean)
print("After iteration, the std fitness of the swarm is:","%e"%std)
#将结果进行绘图
fig=plt.figure(figsize=(12, 10), dpi=300)
plt.title('The change of best fitness',fontdict={'weight':'normal','size': 30})
x=range(1,101,1)
plt.plot(x,his_bestfit,color="red",label="GWO",linewidth=3.0, linestyle="-")
plt.tick_params(labelsize=25)
plt.xlim(0,101)
plt.yscale("log")
plt.xlabel("Epoch",fontdict={'weight':'normal','size': 30})
plt.ylabel("Fitness value",fontdict={'weight':'normal','size': 30})
plt.xticks(range(0,101,10))
plt.legend(loc="upper right",prop={'size':20})
plt.savefig("GWO.png")
plt.show()