def selection(self): newSpecies = np.zeros([self.Population, self.GeneLen]) B = self.decoding(self.Species) # ---------------------------------------------------- # 两种适应度 # ---------------------------------------------------- self.fitness = np.exp(-f2(B[:, 0], B[:, 1])) # self.fitness = 1 / f2(B[:, 0], B[:, 1]) if self.fitness.max() > self.bestfitness: self.bestfitness = self.fitness.max() self.elite = self.Species[self.fitness.argmax()] # ---------------------------------------------------- # 传说中的联赛选择 # ---------------------------------------------------- # for rank in range(self.Population): # n1, n2 = np.random.randint(0, self.Population, 2) # choice = n1 if self.fitness[n1] > self.fitness[n2] else n2 # newSpecies[rank] = self.Species[choice] # self.Species = newSpecies # ---------------------------------------------------- # 俄罗斯轮盘赌 # ---------------------------------------------------- prob = self.fitness/self.fitness.sum() probRank = prob.cumsum() for rank in range(self.Population): rand = np.random.random() for index, item in enumerate(probRank): if item > rand: newSpecies[rank] = self.Species[index] break self.Species = newSpecies return self.fitness.mean(), self.fitness.max()
def Calculation(self, swarms): """计算适应度""" fit = f2(swarms[:, 0], swarms[:, 1]) if fit.min() < self.Gfit: self.Gfit = fit.min() self.Gcoor = swarms[fit.argmin()] return fit
avg, pbest = self.selection() self.crossover() self.mutation() avgArray[rank] = avg pbestArray[rank] = pbest GbestArray[rank] = self.bestfitness return avgArray, pbestArray, GbestArray, route if __name__ == "__main__": N = 500 ga = GA(128) avgArray, pbestArray, GbestArray, route = ga.iterations(Iters=N) B = ga.decoding(ga.elite.reshape(1, ga.GeneLen)) print(B) print(f2(B[:, 0], B[:, 1])) plt.rcParams["font.sans-serif"] = ["SimHei"] plt.rcParams["axes.unicode_minus"] = False fig = plt.figure() ax = axisartist.Subplot(fig, 1, 1, 1) fig.add_axes(ax) ax.axis[:].set_visible(False) ax.axis["x"] = ax.new_floating_axis(0, 0.2) ax.axis["x"].set_axisline_style("->", size=2.0) ax.axis["y"] = ax.new_floating_axis(1, 0) ax.axis["y"].set_axisline_style("->", size=2.0) ax.axis["y"].set_axis_direction('left') ax.annotate(s='适应度值', xy=(1, 1), xytext=(1, 1)) ax.annotate(s='迭代/次', xy=(N, 0.2), xytext=(N, 0.2)) plt.plot(avgArray, "-.", lw=2)
ax.axis["y"].set_axisline_style("->", size=2.0) ax.axis["y"].set_axis_direction('left') ax.annotate(s='适应度值', xy=(1, 1), xytext=(1, 1)) ax.annotate(s='迭代/次', xy=(N, 0), xytext=(N, 0)) plt.plot(avgArray, "-.", lw=2) plt.plot(pbestArray, ":", lw=2) plt.plot(GbestArray, "--", lw=2) plt.legend(["avgArray", "pbestArray", "GbestArray"], loc="upper center") plt.show() plt.figure() delta = 0.1 X1 = np.arange(-4, 4.1, delta) Y1 = np.arange(-4, 4.1, delta) X, Y = np.meshgrid(X1, Y1) Z = f2(X, Y) """ 二维等高线图figsize=(5, 4), dpi=200 """ # 20表示绘制的等高线数量=20 contour = plt.contour(X, Y, Z, 20, linewidths=0.5, linestyles="-.") # 等高线上标明z(即高度)的值,字体大小是10,颜色分别是黑色和红色 plt.clabel(contour, fontsize=4, colors=('k', 'w')) for i in range(sa.population): plt.scatter(route[:, i, 0], route[:, i, 1], s=2) plt.text(route[0, i, 0], route[0, i, 1], "0") plt.text(route[-1, i, 0], route[-1, i, 1], "-1") plt.show()