蚁群算法解决TSP问题代码
时间: 2023-08-17 21:06:02 浏览: 121
用蚁群算法解决TSP问题
下面是基于Python实现的蚁群算法解决TSP问题的示例代码:
```python
import numpy as np
# 城市数量
num_cities = 10
# 城市坐标
cities = np.random.rand(num_cities, 2) * 100
# 初始化参数
num_ants = 10
alpha = 1
beta = 5
rho = 0.1
Q = 1
num_iterations = 100
# 计算城市之间的距离
def get_distance(city1, city2):
return np.sqrt(np.sum((city1 - city2) ** 2))
distances = np.zeros((num_cities, num_cities))
for i in range(num_cities):
for j in range(num_cities):
distances[i][j] = get_distance(cities[i], cities[j])
# 初始化信息素矩阵
pheromones = np.ones((num_cities, num_cities))
# 迭代搜索
for iteration in range(num_iterations):
# 初始化蚂蚁位置
ant_positions = np.zeros((num_ants, num_cities), dtype=int)
for i in range(num_ants):
ant_positions[i][0] = np.random.randint(num_cities)
# 蚂蚁搜索路径
for i in range(num_ants):
for j in range(num_cities - 1):
current_city = ant_positions[i][j]
remaining_cities = list(set(range(num_cities)) - set(ant_positions[i][:j+1]))
next_city = -1
max_pheromone = -1
for city in remaining_cities:
pheromone = pheromones[current_city][city] ** alpha * (1.0 / distances[current_city][city]) ** beta
if pheromone > max_pheromone:
max_pheromone = pheromone
next_city = city
ant_positions[i][j+1] = next_city
# 更新信息素矩阵
delta_pheromones = np.zeros((num_cities, num_cities))
for i in range(num_ants):
path_distance = 0
for j in range(num_cities - 1):
current_city = ant_positions[i][j]
next_city = ant_positions[i][j+1]
path_distance += distances[current_city][next_city]
delta_pheromones += Q / path_distance * np.outer(np.ones(num_cities), np.ones(num_cities))
for j in range(num_cities - 1):
current_city = ant_positions[i][j]
next_city = ant_positions[i][j+1]
delta_pheromones[current_city][next_city] += -Q / path_distance
pheromones = (1 - rho) * pheromones + delta_pheromones
# 输出最优路径
best_ant_position = ant_positions[0]
best_distance = get_distance(cities[best_ant_position[-1]], cities[best_ant_position[0]])
for i in range(num_cities - 1):
best_distance += get_distance(cities[best_ant_position[i]], cities[best_ant_position[i+1]])
print("Best distance:", best_distance)
print("Best path:", best_ant_position)
```
这段代码中,我们首先生成了一些随机的城市坐标,然后计算城市之间的距离,初始化信息素矩阵。在迭代搜索中,我们首先初始化蚂蚁的位置,然后让每只蚂蚁按照一定的规则搜索路径,并记录下每只蚂蚁的路径。接着,我们根据每只蚂蚁的路径更新信息素矩阵。最后,输出最优路径和最优距离。
阅读全文