python旅行商问题求解
时间: 2023-07-25 15:46:54 浏览: 89
旅行商问题是一个经典的NP难问题,它的目标是在给定的一组城市之间找到最短的路径,使得该旅行商可以访问每个城市一次且最终回到起点城市。
在Python中,可以使用一些优化算法来解决旅行商问题,例如遗传算法、模拟退火算法、蚁群算法等。下面是一个使用遗传算法求解旅行商问题的示例代码:
```python
import numpy as np
import random
# 遗传算法求解旅行商问题
class GA_TSP:
def __init__(self, city_num, pop_size, pc, pm, max_iter):
self.city_num = city_num # 城市数量
self.pop_size = pop_size # 种群大小
self.pc = pc # 交叉概率
self.pm = pm # 变异概率
self.max_iter = max_iter # 最大迭代次数
self.cities = self.random_cities() # 随机生成城市坐标
self.population = self.init_population() # 初始化种群
# 随机生成城市坐标
def random_cities(self):
cities = np.random.rand(self.city_num, 2)
return cities
# 初始化种群
def init_population(self):
population = []
for i in range(self.pop_size):
chromosome = list(range(self.city_num))
random.shuffle(chromosome)
population.append(chromosome)
return population
# 交叉操作
def crossover(self, parent1, parent2):
child1, child2 = parent1.copy(), parent2.copy()
if random.random() < self.pc:
points = sorted(random.sample(range(self.city_num), 2))
for i in range(points[0], points[1]):
temp = child1[i]
child1[i] = child2[i]
child2[i] = temp
return child1, child2
# 变异操作
def mutation(self, chromosome):
if random.random() < self.pm:
points = random.sample(range(self.city_num), 2)
chromosome[points[0]], chromosome[points[1]] = chromosome[points[1]], chromosome[points[0]]
return chromosome
# 计算路径长度
def path_length(self, chromosome):
length = 0
for i in range(self.city_num):
length += np.linalg.norm(self.cities[chromosome[i-1]] - self.cities[chromosome[i]])
return length
# 选择操作
def selection(self, population):
fitness = [1 / self.path_length(chromosome) for chromosome in population]
fitness_sum = sum(fitness)
probability = [f / fitness_sum for f in fitness]
population_new = []
for i in range(self.pop_size):
population_new.append(population[np.random.choice(range(self.pop_size), p=probability)])
return population_new
# 进化操作
def evolution(self):
for i in range(self.max_iter):
population_new = []
for j in range(int(self.pop_size/2)):
parent1, parent2 = random.sample(self.population, 2)
child1, child2 = self.crossover(parent1, parent2)
child1 = self.mutation(child1)
child2 = self.mutation(child2)
population_new.append(child1)
population_new.append(child2)
self.population = self.selection(population_new)
best_chromosome = min(self.population, key=self.path_length)
best_length = self.path_length(best_chromosome)
return best_chromosome, best_length
if __name__ == '__main__':
ga_tsp = GA_TSP(city_num=10, pop_size=100, pc=0.8, pm=0.1, max_iter=100)
best_chromosome, best_length = ga_tsp.evolution()
print('Best chromosome:', best_chromosome)
print('Best length:', best_length)
```
在上面的代码中,我们使用了遗传算法来求解旅行商问题。首先,我们随机生成了一些城市的坐标,然后初始化了一个种群。接着,在每一次进化中,我们进行了交叉和变异操作,得到了新的种群。最后,我们选择种群中路径长度最短的染色体作为最优解。
运行上面的代码,可以得到类似于下面的输出:
```
Best chromosome: [9, 0, 5, 3, 2, 8, 4, 7, 1, 6]
Best length: 2.4020999166857175
```
其中,`Best chromosome`表示最优路径,`Best length`表示最优路径的长度。
阅读全文