1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
| import math import random import pandas as pd import matplotlib.pyplot as plt from matplotlib.pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
def calFitness(line, dis_matrix): dis_sum = 0 dis = 0 for i in range(len(line)): if i < len(line) - 1: dis = dis_matrix.loc[line[i], line[i + 1]] dis_sum = dis_sum + dis else: dis = dis_matrix.loc[line[i], line[0]] dis_sum = dis_sum + dis return round(dis_sum, 1)
def tournament_select(pops, popsize, fits, tournament_size): new_pops, new_fits = [], [] while len(new_pops) < len(pops): tournament_list = random.sample(range(0, popsize), tournament_size) tournament_fit = [fits[i] for i in tournament_list] tournament_df = pd.DataFrame \ ([tournament_list, tournament_fit]).transpose().sort_values(by=1).reset_index(drop=True) fit = tournament_df.iloc[0, 1] pop = pops[int(tournament_df.iloc[0, 0])] new_pops.append(pop) new_fits.append(fit) return new_pops, new_fits
def crossover(popsize, parent1_pops, parent2_pops, pc): child_pops = [] for i in range(popsize): child = [None] * len(parent1_pops[i]) parent1 = parent1_pops[i] parent2 = parent2_pops[i] if random.random() >= pc: child = parent1.copy() random.shuffle(child) else: start_pos = random.randint(0, len(parent1) - 1) end_pos = random.randint(0, len(parent1) - 1) if start_pos > end_pos: tem_pop = start_pos start_pos = end_pos end_pos = tem_pop child[start_pos:end_pos + 1] = parent1[start_pos:end_pos + 1].copy() list1 = list(range(end_pos + 1, len(parent2))) list2 = list(range(0, start_pos)) list_index = list1 + list2 j = -1 for i in list_index: for j in range(j + 1, len(parent2)): if parent2[j] not in child: child[i] = parent2[j] break child_pops.append(child) return child_pops
def mutate(pops, pm): pops_mutate = [] for i in range(len(pops)): pop = pops[i].copy() t = random.randint(1, 5) count = 0 while count < t: if random.random() < pm: mut_pos1 = random.randint(0, len(pop) - 1) mut_pos2 = random.randint(0, len(pop) - 1) if mut_pos1 != mut_pos2: tem = pop[mut_pos1] pop[mut_pos1] = pop[mut_pos2] pop[mut_pos2] = tem pops_mutate.append(pop) count += 1 return pops_mutate
def draw_path(line, CityCoordinates): x, y = [], [] for i in line: Coordinate = CityCoordinates[i] x.append(Coordinate[0]) y.append(Coordinate[1]) x.append(x[0]) y.append(y[0]) plt.plot(x, y, 'r-', color='#FF3030', alpha=0.8, linewidth=2.2) plt.xlabel('x') plt.ylabel('y') plt.show() if __name__ == '__main__': CityNum = 20 MinCoordinate = 0 MaxCoordinate = 101 generation = 100 popsize = 100 tournament_size = 5 pc = 0.95 pm = 0.1 CityCoordinates = \ [(random.randint(MinCoordinate, MaxCoordinate), random.randint(MinCoordinate, MaxCoordinate)) for i in range(CityNum)] dis_matrix = \ pd.DataFrame(data=None, columns=range(len(CityCoordinates)), index=range(len(CityCoordinates))) for i in range(len(CityCoordinates)): xi, yi = CityCoordinates[i][0], CityCoordinates[i][1] for j in range(len(CityCoordinates)): xj, yj = CityCoordinates[j][0], CityCoordinates[j][1] dis_matrix.iloc[i, j] = round(math.sqrt((xi - xj) ** 2 + (yi - yj) ** 2), 2) iteration = 0 pops = \ [random.sample([i for i in list(range(len(CityCoordinates)))], len(CityCoordinates)) for j in range(popsize)] draw_path(pops[i], CityCoordinates) fits = [None] * popsize for i in range(popsize): fits[i] = calFitness(pops[i], dis_matrix) best_fit = min(fits) best_pop = pops[fits.index(best_fit)] print('初代最优值 %.1f' % (best_fit)) best_fit_list = [] best_fit_list.append(best_fit) while iteration <= generation: pop1, fits1 = tournament_select(pops, popsize, fits, tournament_size) pop2, fits2 = tournament_select(pops, popsize, fits, tournament_size) child_pops = crossover(popsize, pop1, pop2, pc) child_pops = mutate(child_pops, pm) child_fits = [None] * popsize for i in range(popsize): child_fits[i] = calFitness(child_pops[i], dis_matrix) for i in range(popsize): if fits[i] > child_fits[i]: fits[i] = child_fits[i] pops[i] = child_pops[i] if best_fit > min(fits): best_fit = min(fits) best_pop = pops[fits.index(best_fit)] best_fit_list.append(best_fit) print('第%d代最优值 %.1f' % (iteration, best_fit)) iteration += 1 print(best_pop) draw_path(best_pop, CityCoordinates)
|