一、基本原理
一只蚂蚁从一个城市出发,在访问其他城市时留下信息素踪迹。其他蚂蚁沿着这些踪迹并开辟自己的路径。信息素在访问频率较高的路径上积累得更密集,这种密度增加了其他蚂蚁选择该路径的可能性。
import randomdistances = [[0, 2, 5, 7],[2, 0, 6, 3],[5, 6, 0, 8],[7, 3, 8, 0]
]numAnts = 5
numCities = 4
maxIterations = 100 //最大迭代次数
evaporationRate = 0.5 //表示信息素的挥发率。
alpha = 1.0
beta = 2.0 //计算选择下一个城市概率的参数pheromones = []
//初始化信息素矩阵,初始值都为 1.0
def initialize_pheromones():global pheromonespheromones = [[1.0] * numCities for _ in range(numCities)]
//生成一只蚂蚁的行走路径。它随机选择一个起始城市,然后根据信息素和距离的启发式信息选择下一个未访问的城市,直到访问完所有城市。
def generate_ant_path():path = []visited = [False] * numCitiesstart = random.randint(0, numCities - 1)current = startpath.append(current)visited[current] = Truewhile len(path) < numCities:next_city = select_next_city(current, visited)path.append(next_city)visited[next_city] = Truecurrent = next_cityreturn path
//根据当前城市、已访问状态、信息素和距离启发式信息计算选择下一个城市的概率,并根据随机数确定选择的城市。
def select_next_city(current, visited):probabilities = []total = 0.0for city in range(numCities):if not visited[city]:pheromone = pheromones[current][city]distance = distances[current][city]heuristic = 1.0 / distanceprobability = pheromone ** alpha * heuristic ** betaprobabilities.append((city, probability))total += probabilityprobabilities = [(city, probability / total) for city, probability in probabilities]probabilities.sort(key=lambda x: x[1], reverse=True)cumulative_prob = 0.0random_value = random.random()for city, probability in probabilities:cumulative_prob += probabilityif random_value <= cumulative_prob:return city
//根据蚂蚁走过的路径增加相应路径上的信息素。
def update_pheromones(path):for i in range(numCities - 1):city1 = path[i]city2 = path[i + 1]pheromones[city1][city2] += 1.0 / distances[city1][city2]
// 对信息素进行挥发。
def evaporate_pheromones():for i in range(numCities):for j in range(numCities):pheromones[i][j] *= (1.0 - evaporationRate)
// 在每次迭代中生成蚂蚁的路径,更新信息素,挥发信息素,并记录每次迭代的最佳路径。
def main():initialize_pheromones()for iteration in range(maxIterations):antPaths = []for ant in range(numAnts):path = generate_ant_path()antPaths.append(path)update_pheromones(path)evaporate_pheromones()bestPath = antPaths[0]print(f"Iteration {iteration + 1}: Best Path -> {' -> '.join(map(str, bestPath))}")if __name__ == '__main__':main()
在没有蒸发的情况下:
局部最优问题:信息素路径不断增加,使得特定路径极其强大。这可能会导致算法不断探索这条路径,而忽略其他可能的更好解决方案。
灵活性较差:发现新途径可能会变得困难。蒸发通过减少不太喜欢的路径的信息素痕迹来鼓励新路径的发现。缺乏蒸发可能会导致算法卡在现有路径上。
解决方案达到平衡:蒸发使算法保持平衡。如果没有蒸发,信息素痕迹可能会导致一定的不平衡并导致溶液整体质量的下降。
改进后:
import random
import mathdistances = [[0, 2, 5, 7],[2, 0, 6, 3],[5, 6, 0, 8],[7, 3, 8, 0]
]numAnts = 5
numCities = 4
maxIterations = 100
evaporationRate = 0.5
alpha = 1.0
beta = 2.0pheromones = []def main():random.seed()initialize_pheromones()for iter in range(maxIterations):antPaths = []for ant in range(numAnts):path = generate_ant_path()antPaths.append(path)update_pheromones(path)evaporate_pheromones()bestPath = antPaths[0]print(f"Iteration {iter + 1}: Best Path -> {' -> '.join(map(str, bestPath))}")def initialize_pheromones():global pheromonespheromones = [[1.0] * numCities for _ in range(numCities)]def generate_ant_path():startCity = 0path = [startCity]while len(path) < numCities:currentCity = path[-1]nextCity = choose_next_city(currentCity, path)path.append(nextCity)return pathdef choose_next_city(currentCity, path):availableCities = [city for city in range(numCities) if city not in path]probabilities = []totalProbability = 0.0for nextCity in availableCities:pheromone = math.pow(pheromones[currentCity][nextCity], alpha)distance = 1.0 / distances[currentCity][nextCity]probability = pheromone * distanceprobabilities.append(probability)totalProbability += probabilityprobabilities = [probability / totalProbability for probability in probabilities]randomValue = random.random()cumulativeProbability = 0.0for i, probability in enumerate(probabilities):cumulativeProbability += probabilityif randomValue <= cumulativeProbability:return availableCities[i]return availableCities[-1]def update_pheromones(path):pheromoneDeposit = 1.0for i in range(len(path) - 1):currentCity = path[i]nextCity = path[i + 1]pheromones[currentCity][nextCity] += pheromoneDepositpheromones[nextCity][currentCity] += pheromoneDepositdef evaporate_pheromones():for i in range(numCities):for j in range(numCities):pheromones[i][j] *= (1.0 - evaporationRate)if __name__ == '__main__':main()
二、优点:
灵活性和适用性:它提供了广泛的应用,能够适应不同的问题。它可用于旅游供应商、路线优化等许多领域。
分布式并行结构:蚁群算法基于多只蚂蚁的同时处理来解决问题。这种分布式结构可以更快地解决大型问题。
高改进潜力:该算法使用信息素踪迹来强化最佳路径并让其他蚂蚁跟随它们。这样,在给定的时间内改进的潜力就很大。
自然并行处理:蚂蚁通过相互跟随来解决问题的过程自然地并行进行,这可以减少计算时间。
三、缺点:
局部最优问题:在某些情况下,它可能会关注较短的路径而不是最佳路径。在这种情况下,算法可能会陷入局部最优。
参数灵敏度:算法使用的参数(信息素更新率、跟踪强度等)会影响性能。选择正确的参数很重要。
收敛速度慢:对于大问题或者复杂问题,算法的收敛速度可能会很慢。
最初的性能不佳:最初,信息素追踪可能无效,算法可能很难发现正确的路径。