蚁群算法实际应用,需要代码
时间: 2024-06-11 20:09:41 浏览: 71
以下是一个简单的蚁群算法的Python代码示例,用于解决TSP问题(旅行商问题):
```python
import random
import numpy as np
# 定义城市坐标
cities = np.array([[0, 0], [1, 1], [1, 2], [2, 2], [2, 1]])
# 定义蚂蚁类
class Ant:
def __init__(self, start_city):
self.visited_cities = [] # 已访问城市
self.current_city = start_city # 当前城市
self.visited_cities.append(start_city)
def next_city(self, pheromone_matrix, alpha, beta):
# 计算当前城市与未访问城市之间的选择概率
unvisited_cities = [city for city in range(len(cities)) if city not in self.visited_cities]
probabilities = []
for city in unvisited_cities:
pheromone = pheromone_matrix[self.current_city][city]
distance = np.linalg.norm(cities[self.current_city] - cities[city])
probabilities.append((city, pheromone ** alpha * (1 / distance) ** beta))
probabilities = np.array(probabilities)
probabilities[:, 1] /= np.sum(probabilities[:, 1])
# 根据概率选择下一个城市
next_city_index = np.random.choice(probabilities[:, 0], p=probabilities[:, 1])
self.current_city = next_city_index
self.visited_cities.append(next_city_index)
# 定义蚁群类
class AntColony:
def __init__(self, num_ants, num_iterations, alpha, beta, evaporation_rate):
self.num_ants = num_ants # 蚂蚁数量
self.num_iterations = num_iterations # 迭代次数
self.alpha = alpha # 信息素重要程度
self.beta = beta # 启发式信息重要程度
self.evaporation_rate = evaporation_rate # 信息素的挥发速率
self.pheromone_matrix = np.ones((len(cities), len(cities))) # 信息素矩阵
self.best_path = None # 最优路径
self.best_distance = None # 最优距离
def run(self):
for iteration in range(self.num_iterations):
# 初始化蚂蚁
ants = [Ant(random.randint(0, len(cities) - 1)) for _ in range(self.num_ants)]
# 让蚂蚁走完所有城市
for _ in range(len(cities) - 1):
for ant in ants:
ant.next_city(self.pheromone_matrix, self.alpha, self.beta)
# 计算每只蚂蚁的路径距离并更新最优路径
for ant in ants:
distance = 0
for i in range(len(ant.visited_cities) - 1):
distance += np.linalg.norm(cities[ant.visited_cities[i]] - cities[ant.visited_cities[i+1]])
if self.best_distance is None or distance < self.best_distance:
self.best_distance = distance
self.best_path = ant.visited_cities
# 更新信息素矩阵
delta_pheromone_matrix = np.zeros((len(cities), len(cities)))
for ant in ants:
for i in range(len(ant.visited_cities) - 1):
delta_pheromone_matrix[ant.visited_cities[i]][ant.visited_cities[i+1]] += 1 / self.best_distance
delta_pheromone_matrix[ant.visited_cities[-1]][ant.visited_cities[0]] += 1 / self.best_distance
self.pheromone_matrix = (1 - self.evaporation_rate) * self.pheromone_matrix + delta_pheromone_matrix
# 衰减信息素
self.pheromone_matrix = self.pheromone_matrix * self.evaporation_rate
return self.best_path, self.best_distance
# 运行蚁群算法
ant_colony = AntColony(num_ants=10, num_iterations=100, alpha=1, beta=2, evaporation_rate=0.5)
best_path, best_distance = ant_colony.run()
print("最优路径:", best_path)
print("最优距离:", best_distance)
```
代码中使用了Numpy库来处理城市坐标和信息素矩阵。蚂蚁类和蚁群类分别定义了蚂蚁和蚁群的行为。在蚁群类的run方法中,每次迭代都会初始化蚂蚁、让蚂蚁走完所有城市、计算每只蚂蚁的路径距离并更新最优路径、更新信息素矩阵、衰减信息素。最后返回最优路径和最优距离。
阅读全文