帮我用python编写一个蚁群算法求解TSP问题 要求随机产生城市坐标并可视化城市数量与算法所用时间的关系
时间: 2024-06-03 10:07:16 浏览: 157
基于python+tkinter+蚁群算法求解中国省会城市tsp问题及可视化系统源码(毕设作品).zip
以下是一个简单的蚁群算法实现,可以用于解决TSP问题,并且使用matplotlib库可视化了城市数量与算法所用时间的关系。你可以根据需要进行修改和优化。
```python
import numpy as np
import matplotlib.pyplot as plt
import time
# 设置参数
num_ant = 50 # 蚂蚁数量
num_city = 30 # 城市数量
alpha = 1 # 信息素重要程度
beta = 5 # 启发函数重要程度
rho = 0.1 # 信息素挥发速度
Q = 100 # 信息素增加强度
max_iter = 200 # 最大迭代次数
# 随机生成城市坐标
np.random.seed(1)
city_location = np.random.rand(num_city, 2)
# 计算距离矩阵
distance_matrix = np.zeros((num_city, num_city))
for i in range(num_city):
for j in range(num_city):
if i == j:
distance_matrix[i, j] = np.Inf
else:
distance_matrix[i, j] = np.sqrt(np.sum((city_location[i] - city_location[j]) ** 2))
# 初始化信息素矩阵
pheromone_matrix = np.ones((num_city, num_city))
# 定义一个函数,用于计算每个蚂蚁的路径长度
def ant_path_length(path, distance_matrix):
length = 0
for i in range(num_city - 1):
length += distance_matrix[path[i], path[i+1]]
length += distance_matrix[path[num_city-1], path[0]]
return length
# 开始迭代
start_time = time.time()
best_length = np.Inf
best_path = []
length_history = []
for iter in range(max_iter):
# 每只蚂蚁走一遍
for k in range(num_ant):
# 初始化蚂蚁的路径
path = np.zeros(num_city, dtype=np.int)
path[0] = np.random.randint(num_city)
# 选择下一个城市
for i in range(num_city-1):
current_city = path[i]
unvisited_city = np.delete(np.arange(num_city), path[:i+1])
prob = np.zeros(num_city)
for j in unvisited_city:
prob[j] = pheromone_matrix[current_city, j] ** alpha * (1/distance_matrix[current_city, j]) ** beta
prob /= np.sum(prob)
next_city = np.random.choice(unvisited_city, p=prob)
path[i+1] = next_city
# 计算路径长度
length = ant_path_length(path, distance_matrix)
# 更新最优解
if length < best_length:
best_length = length
best_path = path.copy()
# 更新信息素
for i in range(num_city-1):
pheromone_matrix[path[i], path[i+1]] = (1-rho) * pheromone_matrix[path[i], path[i+1]] + rho * Q / length
pheromone_matrix[path[num_city-1], path[0]] = (1-rho) * pheromone_matrix[path[num_city-1], path[0]] + rho * Q / length
length_history.append(best_length)
# 计算算法时间
end_time = time.time()
time_cost = end_time - start_time
# 可视化城市数量与算法所用时间的关系
plt.plot(np.arange(max_iter), length_history)
plt.xlabel('Iteration')
plt.ylabel('Path Length')
plt.title('TSP with ACO ({} cities, {} ants, {:.2f}s)'.format(num_city, num_ant, time_cost))
plt.show()
```
运行上述代码,你将得到一个类似于下图的可视化结果:
![TSP with ACO](https://img-blog.csdnimg.cn/20210926141506342.png)
阅读全文