用遗传算法写一个TSP问题
时间: 2024-05-13 11:14:59 浏览: 118
遗传算法求TSP问题
5星 · 资源好评率100%
TSP问题是指旅行商问题,即给定一系列城市和每对城市之间的距离,求解访问每一座城市恰好一次并回到起始城市的最短回路。
遗传算法是一种启发式优化算法,可用于解决TSP问题。下面是一个用遗传算法求解TSP问题的示例代码:
```
import random
# 定义城市坐标
city_locations = [(60, 200), (180, 200), (80, 180), (140, 180), (20, 160),
(100, 160), (200, 160), (140, 140), (40, 120), (100, 120),
(180, 100), (60, 80), (120, 80), (180, 60), (20, 40),
(100, 40), (200, 40), (20, 20), (60, 20), (160, 20)]
# 计算两个城市之间的距离
def distance(city1, city2):
x1, y1 = city1
x2, y2 = city2
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
# 计算一个路径的总距离
def path_distance(path):
distance_sum = 0
for i in range(len(path)):
distance_sum += distance(city_locations[path[i-1]], city_locations[path[i]])
return distance_sum
# 初始化种群
def init_population(pop_size, gene_length):
population = []
for i in range(pop_size):
individual = list(range(gene_length))
random.shuffle(individual)
population.append(individual)
return population
# 交叉操作
def crossover(parent1, parent2):
child = [-1] * len(parent1)
start_pos = random.randint(0, len(parent1) - 1)
end_pos = random.randint(0, len(parent1) - 1)
if start_pos > end_pos:
start_pos, end_pos = end_pos, start_pos
for i in range(start_pos, end_pos + 1):
child[i] = parent1[i]
j = 0
for i in range(len(parent2)):
if parent2[i] not in child:
while child[j] != -1:
j += 1
child[j] = parent2[i]
return child
# 变异操作
def mutation(individual, mutation_rate):
for i in range(len(individual)):
if random.random() < mutation_rate:
j = random.randint(0, len(individual) - 1)
individual[i], individual[j] = individual[j], individual[i]
return individual
# 选择操作
def selection(population, fitness, num_parents):
parents = []
for i in range(num_parents):
max_fitness_index = fitness.index(max(fitness))
parents.append(population[max_fitness_index])
population.pop(max_fitness_index)
fitness.pop(max_fitness_index)
return parents
# 遗传算法求解TSP问题
def tsp_ga(pop_size, num_generations, mutation_rate):
gene_length = len(city_locations)
population = init_population(pop_size, gene_length)
for i in range(num_generations):
fitness = [1.0 / path_distance(individual) for individual in population]
parents = selection(population, fitness, 2)
offspring = crossover(parents[0], parents[1])
offspring = mutation(offspring, mutation_rate)
population.append(offspring)
fitness = [1.0 / path_distance(individual) for individual in population]
best_index = fitness.index(max(fitness))
best_individual = population[best_index]
return best_individual, path_distance(best_individual)
# 测试
best_individual, shortest_distance = tsp_ga(100, 500, 0.01)
print("最短路径:", best_individual)
print("最短距离:", shortest_distance)
```
在上面的代码中,我们定义了一个`distance()`函数来计算两个城市之间的距离,一个`path_distance()`函数来计算一个路径的总距离,一个`init_population()`函数来初始化种群,一个`crossover()`函数来进行交叉操作,一个`mutation()`函数来进行变异操作,一个`selection()`函数来进行选择操作,一个`tsp_ga()`函数来执行遗传算法求解TSP问题。
我们将初始化种群大小设置为100,迭代次数设置为500次,变异率设置为0.01,运行代码后可以得到最短路径和最短距离的输出结果。需要注意的是,由于遗传算法是一种启发式算法,无法保证得到全局最优解,因此每一次运行的结果可能会有所不同。
阅读全文