遗传算法之 TSP 问题

admin 2025年1月10日21:57:39评论2 views字数 4665阅读15分33秒阅读模式

遗传算法之 TSP 问题

利用 Python 实现遗传算法解决 TSP 问题, 并画出最优路径图与每代适应度曲线图

代码

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
198
199
200
201
202
# -*- coding: cp936 -*-
import math
import random
import time,os
from matplotlib.pyplot import *
import numpy as np

class Evolution():
def __init__(self, population, mutation_rate, add, retain_rate, data):

self.num = population
self.mutation_rate = mutation_rate
self.add = add
self.retain_rate = retain_rate
self.best = [[1,2],float("inf")]
self.data = data
self.mutationnum = 0
self.insert = range(0, len(self.data))
self.AllMaxy = []
self.d = 0
# 随机生成初始种群
self.population = self.Gene_population()

matplotlib.use('Agg')

def Gene_population(self):
"""
获取初始种群(一个含有 self.num 个长度为 self.chromosome_size 的染色体的列表)
"""
x = []
newx = range(0, len(self.data))

while len(x) < self.num:
if newx not in x:
x += [newx[:]]

random.shuffle(newx)

return x[:]

def Evolve(self):
"""
进化
对当前一代种群依次进行选择、交叉并生成新一代种群,然后对新一代种群进行变异
"""

self.Selection()
result = '目前第 ' + str(self.d) + ' 代, 此代最优为 ' + str(1 / self.Fitness(self.population[0])) + ' , 变异次数为 ' + str(self.mutationnum)
#self.Destroy()
self.Crossover()
self.Force_Insert()
self.Mutation()

self.d += 1
return result

def Fitness(self, xi):
"""
计算适应度,将染色体解码为定义域之间的数字,代入函数计算
因为是求最大值,所以数值越大,适应度越高
"""
start = 0
distance = 0.0

for end in range(1, len(xi)):
distance += ((self.data[xi[start]][1][0] * 1.0 - self.data[xi[end]][1][0]) ** 2 + (self.data[xi[start]][1][1] * 1.0 - self.data[xi[end]][1][1]) ** 2) ** 0.5 #如果 data 的格式有变这里要改
start = end

return 1 / distance

def Selection(self):
"""
选择
先对适应度从大到小排序,选出存活的染色体
再进行随机选择,选出适应度虽然小,但是幸存下来的个体
"""
xy = sorted([(i, j) for i, j in [(self.Fitness(xi), xi) for xi in self.population]], reverse = True)
x = [x1 for y1, x1 in xy]
y = [y1 for y1, x1 in xy]

eMaxy = 1 / y[0] #此代最佳
self.AllMaxy += [eMaxy]

self.population = x[:int(self.num * self.retain_rate)] #精英策略

if eMaxy < self.best[1]:
self.PlotAndSave(x[0], y[0], 1)
os.system('cls')
print x[0], '\n', '最佳第', self.d, '代', '最优路径长度为', eMaxy
self.best = [x[0][:],eMaxy]

def Crossover(self):
"""
染色体的交叉、繁殖,生成新一代的种群
新出生的孩子,最终会被加入存活下来的父母之中,形成新一代的种群。
"""
length = len(self.population)
for i in range(length):
father= random.choice(self.population)
mother = random.choice(self.population)

r1 = np.random.random_integers(0, len(father) - 1)
r2 = np.random.random_integers(1, len(mother) - r1)

DNA1 = father[r1:r1 + r2]

DNA2 = []
for i in range(len(mother)):
if mother[i] not in DNA1:
DNA2 += [mother[i]]

child = []
for i in range(r1):
child += [DNA2[i]]

child += DNA1 + DNA2[r1:]

self.population += [child[:]]


def Force_Insert(self):

while len(self.population) < self.num:
self.population += [self.insert[:]]
random.shuffle(self.insert)


def Mutation(self):
"""
变异
对种群中的所有个体,随机改变某个个体中的某个基因
"""
each_mutation_rate = self.mutation_rate

for i in range(len(self.population)):
if random.uniform(0,1) < each_mutation_rate:
r = np.random.randint(0, len(self.population[i]))
self.population[i][r], self.population[i][len(self.population[i]) - r - 1] = self.population[i][len(self.population[i]) - r - 1], self.population[i][r]
self.mutationnum += 1

each_mutation_rate += self.add


def PlotAndSave(self, x, y, f):

plot(range(1, len(self.AllMaxy) + 1), self.AllMaxy, 'b')
title(str(x) + '\n\n' + str(1 / y), fontsize = 7)

if f:
savefig('Max.jpg')
else:

savefig('%d_Max.jpg' %self.d)

close('all')

xr = []
yr = []
for i in x:
xr += [self.data[i][1][0]]
yr += [self.data[i][1][1]]

xr = np.array(xr + [xr[0]])
yr = np.array(yr + [yr[0]])

x0 = xr[:2]
y0 = yr[:2]
xr = xr[1:]
yr = yr[1:]

quiver(x0[:-1], y0[:-1], x0[1:] - x0[:-1], y0[1:] - y0[:-1], scale_units = 'xy', angles = 'xy', scale = 1, color='r')
quiver(xr[:-1], yr[:-1], xr[1:] - xr[:-1], yr[1:] - yr[:-1], scale_units = 'xy', angles = 'xy', scale = 1)

if f:
savefig('Max_Road.jpg')
else:
savefig('%d_Road.jpg' %self.d)

close('all')


time.clock()

#------------------------------------------------------------------参数设置------------------------------------------------------------------

population = 1000 #种群数量
mutation_rate = 0.001 #变异概率
add = 0.05 #变异概率随着精英程度递减而增大,0.001
retain_rate = 0.5 #种群筛选时保留 20% 的精英
data = [["*", [37, 52]], ["*", [49, 49]], ... ,["*", [30,40]]]

#------------------------------------------------------------------参数设置------------------------------------------------------------------

gene = Evolution(population, mutation_rate, add, retain_rate, data)
while 1:
t = time.clock()
minute, second = divmod(t, 60)
hour, minute = divmod(minute, 60)
try:
print '\r', gene.Evolve(), " 花费时间 %02d:%02d:%02d" %(hour, minute, second),
except:
gene.PlotAndSave(gene.population[:][0], gene.Fitness(gene.population[0]), 0)

注意

  • 历史最优路径图为 Max.jpg, 曲线图以及路径图均保存在运行目录下.
  • 双击运行, 不要用 IDE 运行.
  • 针对不同问题可以对参数进行优化, 以得到更好的结果.
  • 按 Ctrl + C 可以实时保存曲线图以及路径图.

运行结果

  • Eil 51, 为例, 此网站给出的最优解为 426, 而我求出来的是 425.252657142
  • 结果截图
    遗传算法之 TSP 问题
    遗传算法之 TSP 问题

所以, 代码的算法还是比较合理的.

- By:tr0y.wang

免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2025年1月10日21:57:39
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   遗传算法之 TSP 问题https://cn-sec.com/archives/3615774.html
                  免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉.

发表评论

匿名网友 填写信息