import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import matplotlib as mpl import copy as copy def initialization(pop,ub,lb,dim): ''' 种群初始化函数''' X = np.zeros([pop,dim]) #声明空间 for i in range(pop): for j in range(dim): X[i,j]=(ub[j]-lb[j])*np.random.random()+lb[j] #生成[lb,ub]之间的随机数 return X def BorderCheck(X,ub,lb,pop,dim): '''边界检查函数''' for i in range(pop): for j in range(dim): if X[i,j]>ub[j]: X[i,j] = ub[j] elif X[i,j]=L: for j in range(dim): X[i, j] = np.random.random() * (ub[j] - lb[j]) + lb[j] C[i] = 0 fitness = CaculateFitness(X, fun) # 计算适应度值 fitness, sortIndex = SortFitness(fitness) # 对适应度值排序 X = SortPosition(X, sortIndex) # 种群排序 if fitness[0] <= GbestScore: # 更新全局最优 GbestScore = copy.copy(fitness[0]) GbestPositon[0,:] = copy.copy(X[0, :]) Curve[t] = GbestScore print(t,MaxIter) return GbestScore, GbestPositon, Curve '''适应度函数''' def fun(x): fitness=0 for i in range(3): fitness=fitness+(x[i]**2-10*np.cos(2*np.pi*x[i])+10) return fitness if __name__=="__main__": #设置参数 pop = 50 #种群数量 MaxIter = 500 #最大迭代次数 dim = 3 #维度 lb = np.array([-5,-5,-5]) #下边界 ub = np.array([5,5,5])#上边界 #适应度函数选择 fobj = fun GbestScore,GbestPositon,Curve = ABC(pop,dim,lb,ub,MaxIter,fobj) print('最优适应度值:',GbestScore) print('最优解:',GbestPositon) #绘制适应度曲线 plt.figure(1) plt.plot(Curve,'r-',linewidth=2) plt.xlabel('Iteration',fontsize='medium') plt.ylabel("Fitness",fontsize='medium') plt.grid() plt.title('ABC',fontsize='large') plt.show()