给我一段最近插入的python代码解决TSP问题
时间: 2023-11-22 13:55:06 浏览: 61
TSP问题的python代码
5星 · 资源好评率100%
以下是一个使用遗传算法解决TSP问题的Python代码示例:
```python
import numpy as np
import random
# 创建数据集
num_cities = 10 # 城市数量
x = np.random.randint(0, 100, (num_cities, 2)) # 随机生成坐标
dist_matrix = np.zeros((num_cities, num_cities)) # 创建距离矩阵
for i in range(num_cities):
for j in range(num_cities):
dist_matrix[i, j] = np.sqrt(np.sum((x[i]-x[j])**2)) # 计算欧氏距离
# 定义遗传算法参数
pop_size = 50 # 种群大小
num_generations = 500 # 迭代次数
mutation_rate = 0.02 # 变异率
# 初始化种群
def init_population(pop_size):
population = []
for i in range(pop_size):
chromosome = list(range(num_cities))
random.shuffle(chromosome)
population.append(chromosome)
return population
# 计算适应度
def evaluate(chromosome):
distance = 0
for i in range(num_cities-1):
distance += dist_matrix[chromosome[i], chromosome[i+1]]
distance += dist_matrix[chromosome[-1], chromosome[0]] # 回到起点
return 1/distance
# 选择操作
def select(population):
fitness = [evaluate(chromosome) for chromosome in population]
fitness_sum = sum(fitness)
select_prob = [f/fitness_sum for f in fitness]
selected_idx = np.random.choice(range(pop_size), size=pop_size, replace=True, p=select_prob)
return [population[idx] for idx in selected_idx]
# 交叉操作
def crossover(parent1, parent2):
point1 = random.randint(0, num_cities-1)
point2 = random.randint(0, num_cities-1)
start = min(point1, point2)
end = max(point1, point2)
child = [-1] * num_cities
for i in range(start, end+1):
child[i] = parent1[i]
idx = end
for i in range(num_cities):
if idx == num_cities:
idx = 0
if parent2[i] not in child:
child[idx] = parent2[i]
idx += 1
return child
# 变异操作
def mutate(chromosome):
if random.random() < mutation_rate:
idx1 = random.randint(0, num_cities-1)
idx2 = random.randint(0, num_cities-1)
chromosome[idx1], chromosome[idx2] = chromosome[idx2], chromosome[idx1]
# 遗传算法主函数
def genetic_algorithm():
population = init_population(pop_size)
best_chromosome = []
best_fitness = 0
for _ in range(num_generations):
population = select(population)
offspring = []
for i in range(int(pop_size/2)):
parent1 = population[i]
parent2 = population[pop_size-i-1]
child1 = crossover(parent1, parent2)
child2 = crossover(parent2, parent1)
mutate(child1)
mutate(child2)
offspring.append(child1)
offspring.append(child2)
population = offspring
fitness = [evaluate(chromosome) for chromosome in population]
max_fitness = max(fitness)
if max_fitness > best_fitness:
best_fitness = max_fitness
best_chromosome = population[fitness.index(max_fitness)]
return best_chromosome, 1/best_fitness
# 运行遗传算法
best_chromosome, best_distance = genetic_algorithm()
print("最短路径: ", best_chromosome)
print("最短距离: ", best_distance)
```
这段代码使用遗传算法解决TSP问题,生成了一个包含10个城市的随机数据集,并输出了最短路径和最短距离。您可以根据需要修改数据集的大小和参数的值。
阅读全文