用蚁群算法求旅行商问题的最优解的python代码
时间: 2024-01-15 13:04:13 浏览: 82
一种求解旅行商问题的改进蚁群算法
以下是一个用蚁群算法求解旅行商问题的 Python 代码:
```
import numpy as np
from scipy.spatial import distance_matrix
# 蚂蚁类
class Ant:
def __init__(self, num_cities):
self.route = np.zeros(num_cities, dtype=np.int) # 记录路线
self.visited_cities = np.zeros(num_cities, dtype=bool) # 记录已访问城市
self.index = 0 # 当前所在城市的下标
# 移动蚂蚁到下一个城市
def move_to_next_city(self, tau, eta, alpha, beta):
q0 = 0.9
probabilities = self.compute_probabilities(tau, eta, alpha, beta)
if np.random.random() < q0:
next_city = np.argmax(probabilities)
else:
next_city = np.random.choice(range(len(probabilities)), p=probabilities)
self.route[self.index] = next_city
self.visited_cities[next_city] = True
self.index = next_city
# 计算下一个城市的概率
def compute_probabilities(self, tau, eta, alpha, beta):
pheromones = tau[self.index] ** alpha
heuristic = (eta[self.index] ** beta) * (tau[self.index] ** alpha)
probabilities = pheromones * heuristic
probabilities[self.visited_cities] = 0
probabilities = probabilities / np.sum(probabilities)
return probabilities
# 蚁群算法求解旅行商问题
class AntColonyOptimization:
def __init__(self, num_ants, num_iterations, decay, alpha, beta, q):
self.num_ants = num_ants # 蚂蚁数量
self.num_iterations = num_iterations # 迭代次数
self.decay = decay # 信息素挥发因子
self.alpha = alpha # alpha参数
self.beta = beta # beta参数
self.q = q # 信息素增量常数
# 求解旅行商问题
def solve_tsp(self, distance_matrix):
num_cities = distance_matrix.shape[0]
tau = np.ones((num_cities, num_cities)) # 信息素矩阵
eta = 1 / distance_matrix # 启发值矩阵
best_route = None
best_cost = float('inf')
for i in range(self.num_iterations):
ants = [Ant(num_cities) for _ in range(self.num_ants)] # 创建蚂蚁
for ant in ants:
while not np.all(ant.visited_cities):
ant.move_to_next_city(tau, eta, self.alpha, self.beta) # 蚂蚁走一步
distance = distance_matrix[ant.route[-1], ant.route[0]] # 回到起点
for j in range(num_cities - 1):
distance += distance_matrix[ant.route[j], ant.route[j+1]]
if distance < best_cost: # 更新最优解
best_route = ant.route
best_cost = distance
# 更新信息素
for j in range(num_cities - 1):
tau[ant.route[j], ant.route[j+1]] = (1 - self.decay) * tau[ant.route[j], ant.route[j+1]] + self.q / distance
tau[ant.route[-1], ant.route[0]] = (1 - self.decay) * tau[ant.route[-1], ant.route[0]] + self.q / distance
ant.route = np.zeros(num_cities, dtype=np.int)
ant.visited_cities = np.zeros(num_cities, dtype=bool)
ant.index = 0
tau = (1 - self.decay) * tau # 信息素挥发
if i % 10 == 0:
print("Iteration {:2d}, Best Cost {:.2f}".format(i, best_cost))
return best_route, best_cost
# 测试
if __name__ == '__main__':
# 构造测试数据
num_cities = 10
np.random.seed(0)
cities = np.random.rand(num_cities, 2)
distance_matrix = distance_matrix(cities, cities)
# 求解旅行商问题
aco = AntColonyOptimization(num_ants=100, num_iterations=500, decay=0.5, alpha=1, beta=5, q=10)
best_route, best_cost = aco.solve_tsp(distance_matrix)
# 输出结果
print("Best Route: {}".format(best_route))
print("Best Cost: {:.2f}".format(best_cost))
```
以上是一个用蚁群算法求解旅行商问题的 Python 代码。
阅读全文