python实现蚁群算法
蚁群算法(Ant Colony Optimization, ACO)是一种模拟蚂蚁觅食行为的启发式算法,常用于解决优化问题,如旅行商问题(TSP)、调度问题等。这里,将提供一个简化的蚁群算法实现,用于解决旅行商问题(TSP)。
蚁群算法(ACO)解决TSP问题的基本步骤:
- 初始化:设置蚂蚁数量、信息素挥发系数、信息素增加强度系数等参数,初始化信息素矩阵。
- 构建解:每只蚂蚁随机选择起点,根据信息素浓度和启发式信息(如城市间距离的倒数)选择下一个城市,直到访问所有城市。
- 更新信息素:根据蚂蚁的解的质量(如路径长度)更新路径上的信息素。
- 迭代:重复步骤2和3,直到达到最大迭代次数或满足停止条件。
Python 实现:
以下是一个简化的Python程序,用于实现蚁群算法解决TSP问题:
import numpy as np | |
class AntColonyOptimization: | |
def __init__(self, dist_matrix, num_ants, num_cities, alpha=1, beta=5, rho=0.5, Q=100, max_iter=100): | |
self.dist_matrix = dist_matrix | |
self.num_ants = num_ants | |
self.num_cities = num_cities | |
self.alpha = alpha # 信息素重要程度因子 | |
self.beta = beta # 启发式因子重要程度 | |
self.rho = rho # 信息素挥发系数 | |
self.Q = Q # 信息素增加强度系数 | |
self.max_iter = max_iter | |
self.pheromone = np.ones((num_cities, num_cities)) / num_cities # 初始化信息素矩阵 | |
def heuristic(self, dist): | |
"""启发式信息,这里使用距离的倒数""" | |
return 1.0 / (dist + 1e-6) # 加小量防止除以0 | |
def probability(self, tabu, allowed, eta): | |
"""计算转移概率""" | |
tau = self.pheromone[tabu[-1], :] | |
tau_eta = tau ** self.alpha * eta ** self.beta | |
tau_eta[~allowed] = 0 # 不可访问的城市概率为0 | |
return tau_eta / tau_eta.sum() | |
def update_pheromone(self, best_routes): | |
"""更新信息素""" | |
delta_tau = np.zeros_like(self.pheromone) | |
for route in best_routes: | |
for i in range(self.num_cities - 1): | |
j = route[i + 1] | |
delta_tau[route[i], j] += self.Q / self.dist_matrix[route[i], route[i + 1]] | |
self.pheromone *= (1 - self.rho) | |
self.pheromone += delta_tau | |
def solve(self): | |
best_length = float('inf') | |
best_routes = [] | |
for iter_ in range(self.max_iter): | |
all_routes = [] | |
for _ in range(self.num_ants): | |
route = [np.random.randint(self.num_cities)] | |
tabu = set(route) | |
allowed = np.ones(self.num_cities, dtype=bool) | |
allowed[route[0]] = False | |
while len(route) < self.num_cities: | |
probs = self.probability(route, allowed, self.heuristic(self.dist_matrix[route[-1], :])) | |
next_city = np.random.choice(self.num_cities, p=probs) | |
route.append(next_city) | |
tabu.add(next_city) | |
allowed[next_city] = False | |
route_length = sum(self.dist_matrix[route[i], route[i + 1]] for i in range(self.num_cities - 1)) | |
route.append(route[0]) # 回到起点 | |
all_routes.append(route) | |
if route_length < best_length: | |
best_length = route_length | |
best_routes = [route] | |
elif route_length == best_length: | |
best_routes.append(route) | |
self.update_pheromone(best_routes) | |
print(f"Iteration {iter_ + 1}, Best Length: {best_length}") | |
return best_routes, best_length | |
# 示例使用 | |
if __name__ == "__main__": | |
# 创建一个简单的距离矩阵 | |
dist_matrix = np.array([ | |
[0, 10, 15, 20], | |
[10, 0, 35, 25], | |
[15, 35, 0, 30], | |
[20, 25, 30, 0] | |
]) | |
aco = AntColonyOptimization(dist_matrix, num_ants=10, num_cities=4) | |
best_routes, best_length = aco.solve() | |
print("Best Routes:", best_routes) | |
print("Best Length:", best_length) |
这段代码实现了一个基本的蚁群算法来解决TSP问题。注意,为了简单起见,这里没有使用精英策略或局部搜索等高级技术来进一步改进算法性能。