蚁群算法解决旅行商问题的完整Python实现

发布时间:2024年01月11日

蚁群算法(Ant Colony Optimization,简称ACO)是一种模拟蚂蚁觅食行为的启发式优化算法。它通过模拟蚂蚁在寻找食物时释放信息素的行为,来解决组合优化问题,特别是旅行商问题(TSP)。

蚁群算法的基本思想是,蚂蚁在搜索过程中通过释放信息素来引导其他蚂蚁的行为。蚂蚁在路径上释放的信息素会被其他蚂蚁感知到,并且更倾向于选择信息素浓度较高的路径。随着时间的推移,信息素会逐渐蒸发,从而使路径上的信息素浓度趋于平衡。

下面是一个使用蚁群算法解决旅行商问题的Python代码示例:

import numpy as np

class AntColonyOptimizer:
    def __init__(self, num_ants, num_iterations, alpha, beta, rho, Q):
        self.num_ants = num_ants
        self.num_iterations = num_iterations
        self.alpha = alpha
        self.beta = beta
        self.rho = rho
        self.Q = Q

    def optimize(self, distance_matrix):
        num_cities = distance_matrix.shape[0]
        pheromone_matrix = np.ones((num_cities, num_cities))
        best_path = None
        best_distance = np.inf

        for iteration in range(self.num_iterations):
            paths = self.construct_paths(distance_matrix, pheromone_matrix)
            self.update_pheromones(pheromone_matrix, paths)

            current_best_path = min(paths, key=lambda x: self.calculate_distance(x, distance_matrix))
            current_best_distance = self.calculate_distance(current_best_path, distance_matrix)

            if current_best_distance < best_distance:
                best_path = current_best_path
                best_distance = current_best_distance

            self.evaporate_pheromones(pheromone_matrix)

        return best_path, best_distance

    def construct_paths(self, distance_matrix, pheromone_matrix):
        num_cities = distance_matrix.shape[0]
        paths = []

        for ant in range(self.num_ants):
            path = [0]  # Start from city 0
            visited = set([0])

            while len(path) < num_cities:
                current_city = path[-1]
                next_city = self.select_next_city(current_city, visited, pheromone_matrix, distance_matrix)
                path.append(next_city)
                visited.add(next_city)

            path.append(0)  # Return to city 0
            paths.append(path)

        return paths

    def select_next_city(self, current_city, visited, pheromone_matrix, distance_matrix):
        num_cities = distance_matrix.shape[0]
        unvisited_cities = set(range(num_cities)) - visited
        probabilities = []

        for city in unvisited_cities:
            pheromone = pheromone_matrix[current_city, city]
            distance = distance_matrix[current_city, city]
            probability = pheromone**self.alpha * (1/distance)**self.beta
            probabilities.append(probability)

        probabilities = np.array(probabilities)
        probabilities /= np.sum(probabilities)
        next_city = np.random.choice(list(unvisited_cities), p=probabilities)

        return next_city

    def update_pheromones(self, pheromone_matrix, paths):
        for path in paths:
            distance = self.calculate_distance(path, distance_matrix)
            pheromone_deposit = self.Q / distance

            for i in range(len(path)-1):
                city_a = path[i]
                city_b = path[i+1]
                pheromone_matrix[city_a, city_b] += pheromone_deposit

    def evaporate_pheromones(self, pheromone_matrix):
        pheromone_matrix *= (1 - self.rho)

    def calculate_distance(self, path, distance_matrix):
        distance = 0

        for i in range(len(path)-1):
            city_a = path[i]
            city_b = path[i+1]
            distance += distance_matrix[city_a, city_b]

        return distance

# Example usage
distance_matrix = np.array([[0, 2, 9, 10],
                            [1, 0, 6, 4],
                            [15, 7, 0, 8],
                            [6, 3, 12, 0]])

aco = AntColonyOptimizer(num_ants=10, num_iterations=100, alpha=1, beta=2, rho=0.5, Q=1)
best_path, best_distance = aco.optimize(distance_matrix)

print("Best path:", best_path)
print("Best distance:", best_distance)

示例中使用一个4x4的距离矩阵来表示城市之间的距离。可以根据需要修改距离矩阵的大小和内容。蚁群算法的参数包括蚂蚁数量(num_ants)、迭代次数(num_iterations)、信息素重要程度(alpha)、启发式信息重要程度(beta)、信息素蒸发率(rho)和信息素增量(Q)根据具体问题进行调整。

程序输出如下:

Best path: [0, 1, 2, 3, 0]
Best distance: 22

文章来源:https://blog.csdn.net/qq_38563206/article/details/135502745
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。