使用启发式算法解决TSP问题代码
时间: 2024-03-16 08:46:56 浏览: 15
以下是使用遗传算法解决TSP问题的示例代码:
```python
import random
import numpy as np
# 数据集
cities = np.array([[0, 1, 2, 3, 4, 5, 6],
[1, 0, 4, 2, 8, 3, 6],
[2, 4, 0, 5, 1, 7, 3],
[3, 2, 5, 0, 6, 4, 1],
[4, 8, 1, 6, 0, 5, 2],
[5, 3, 7, 4, 5, 0, 6],
[6, 6, 3, 1, 2, 6, 0]])
# 遗传算法参数
POPULATION_SIZE = 20 # 种群大小
MUTATION_RATE = 0.1 # 变异率
GENERATIONS = 100 # 迭代次数
# 计算路径长度
def get_path_length(path):
length = 0
for i in range(len(path) - 1):
length += cities[path[i], path[i+1]]
length += cities[path[-1], path[0]]
return length
# 初始化种群
def init_population(size, n):
population = []
for i in range(size):
path = list(range(n))
random.shuffle(path)
population.append(path)
return population
# 选择
def selection(population):
fitness = [1 / get_path_length(p) for p in population]
idx = random.choices(range(len(population)), weights=fitness, k=2)
return population[idx[0]], population[idx[1]]
# 交叉
def crossover(p1, p2):
n = len(p1)
idx1, idx2 = sorted(random.sample(range(n), 2))
temp = [-1] * n
for i in range(idx1, idx2+1):
temp[i] = p1[i]
for i in range(n):
if p2[i] not in temp:
for j in range(n):
if temp[j] == -1:
temp[j] = p2[i]
break
return temp
# 变异
def mutation(path):
n = len(path)
idx1, idx2 = sorted(random.sample(range(n), 2))
path[idx1], path[idx2] = path[idx2], path[idx1]
return path
# 遗传算法主程序
def genetic_algorithm():
# 初始化种群
population = init_population(POPULATION_SIZE, len(cities))
# 迭代
for i in range(GENERATIONS):
# 选择、交叉、变异
new_population = []
for j in range(POPULATION_SIZE):
p1, p2 = selection(population)
child = crossover(p1, p2)
if random.random() < MUTATION_RATE:
child = mutation(child)
new_population.append(child)
# 更新种群
population = new_population
# 输出结果
best_path = min(population, key=get_path_length)
print('Generation {}: best path length = {}'.format(i+1, get_path_length(best_path)))
if __name__ == '__main__':
genetic_algorithm()
```
该代码实现了遗传算法解决TSP问题的基本框架,其中包含初始化种群、选择、交叉、变异等操作。通过调节参数,可以得到更好的解决方案。