用Python写一个狼群算法解决tsp问题的完整代码
时间: 2024-03-17 08:42:01 浏览: 56
求解TSP问题的蚁群算法程序
以下是用Python编写狼群算法解决TSP问题的完整代码:
```python
import numpy as np
import random
# 定义城市坐标
CITY_POSITIONS = np.array([[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]])
# 常量定义
ALPHA = 0.5
BETA = 0.8
DELTA = 1
N_POP = 10
N_ITERS = 100
N_CITIES = CITY_POSITIONS.shape[0]
DISTANCES = np.zeros((N_CITIES, N_CITIES))
for i in range(N_CITIES):
for j in range(i + 1, N_CITIES):
DISTANCES[i][j] = np.sqrt(np.sum((CITY_POSITIONS[i] - CITY_POSITIONS[j]) ** 2))
DISTANCES[j][i] = DISTANCES[i][j]
# 初始化狼群
class Wolf:
def __init__(self):
self.position = np.random.permutation(N_CITIES)
self.fitness = self.evaluate_fitness()
def evaluate_fitness(self):
return sum([DISTANCES[self.position[i - 1]][self.position[i]] for i in range(N_CITIES)]) + DISTANCES[self.position[-1]][self.position[0]]
wolves = [Wolf() for i in range(N_POP)]
# 迭代优化
for i in range(N_ITERS):
# 排序
wolves = sorted(wolves, key=lambda x: x.fitness)
# 更新最优解
best_wolf = wolves[0]
best_fitness = best_wolf.fitness
# 更新每只狼的位置
for wolf in wolves:
# 狼最优解向量
x1 = best_wolf.position
# 狼当前解向量
x2 = wolf.position
# 狼随机解向量
x3 = wolves[random.randint(0, N_POP - 1)].position
# 狼位置更新
wolf.position = np.array([x2[i] + ALPHA * (x1[i] - x2[i]) + BETA * (x3[i] - x2[i]) for i in range(N_CITIES)])
# 边界处理
wolf.position = np.array([np.clip(wolf.position[i], 0, N_CITIES - 1) for i in range(N_CITIES)])
# 评估适应度
wolf.fitness = wolf.evaluate_fitness()
# 挑选最优解
wolves = sorted(wolves, key=lambda x: x.fitness)
wolves = wolves[:DELTA]
# 输出最优解
print('Iteration:', i, 'Best Fitness:', best_fitness, 'Best Solution:', best_wolf.position)
```
代码中使用了numpy库进行矩阵计算和边界处理。代码中定义了一个Wolf类,表示狼,其中包含了狼的位置和适应度。首先对狼群进行初始化,然后进行迭代优化。每次迭代,首先对狼群按适应度进行排序,然后更新最优解,再更新每只狼的位置。更新位置时,每只狼会受到最优解向量、当前解向量和随机解向量的影响,其中ALPHA和BETA是控制影响程度的参数。更新位置后,对边界进行处理,再评估适应度。更新完所有狼的位置后,再挑选最优解,删除其他狼,输出最优解。
阅读全文