蚁群算法(Ant Colony Optimization, ACO)是一种启发式搜索算法,用于寻找优化路径问题的近似解,如旅行商问题(TSP)、调度问题等。这里我将给出一个简单的旅行商问题(TSP)的蚁群算法实现示例。
在TSP中,我们的目标是找到一条最短的路径,使得一个旅行商可以访问n个城市一次并返回起点,且总行程最短。
以下是一个简化的Matlab实现:
|---|-------------------------------------------------------------------------------------|
| | function aco_tsp(numCities, numAnts, numIters, alpha, beta, rho, Q)
|
| | % 初始化参数
|
| | numCities = numCities; % 城市数量
|
| | numAnts = numAnts; % 蚂蚁数量
|
| | numIters = numIters; % 迭代次数
|
| | alpha = alpha; % 信息素重要程度因子
|
| | beta = beta; % 启发式信息重要程度因子
|
| | rho = rho; % 信息素挥发系数
|
| | Q = Q; % 信息素强度
|
| | |
| | % 随机生成城市坐标
|
| | cityLocations = rand(numCities, 2) * 100;
|
| | |
| | % 初始化距离矩阵
|
| | D = squareform(pdist(cityLocations));
|
| | |
| | % 初始化信息素矩阵
|
| | pheromone = ones(numCities, numCities);
|
| | |
| | % 开始迭代
|
| | for iter = 1:numIters
|
| | % 每只蚂蚁的路径
|
| | allPaths = cell(numAnts, 1);
|
| | % 每只蚂蚁的总距离
|
| | allDistances = zeros(numAnts, 1);
|
| | |
| | % 蚂蚁构建路径
|
| | for ant = 1:numAnts
|
| | % 随机选择起始城市
|
| | startCity = randi(numCities);
|
| | path = [startCity];
|
| | unvisited = setdiff(1:numCities, startCity);
|
| | |
| | % 构建路径
|
| | while ~isempty(unvisited)
|
| | probabilities = zeros(1, length(unvisited));
|
| | for j = unvisited
|
| | % 计算启发式信息
|
| | heuristic = 1 / D(path(end), j);
|
| | % 计算选择概率
|
| | probabilities(j) = (pheromone(path(end), j) .^ alpha) * (heuristic .^ beta);
|
| | end
|
| | probabilities = probabilities / sum(probabilities);
|
| | % 轮盘赌选择下一个城市
|
| | nextCity = unvisited(randsrc(1, 1, [unvisited; probabilities(:)]'));
|
| | path = [path, nextCity];
|
| | unvisited(unvisited == nextCity) = [];
|
| | end
|
| | |
| | % 计算路径总距离
|
| | allDistances(ant) = sum(D(sub2ind(size(D), path(1:end-1), path(2:end))));
|
| | allPaths{ant} = path;
|
| | end
|
| | |
| | % 更新信息素
|
| | deltaPheromone = zeros(size(pheromone));
|
| | for ant = 1:numAnts
|
| | % 只在蚂蚁走过的路径上增加信息素
|
| | for i = 1:length(allPaths{ant})-1
|
| | start = allPaths{ant}(i);
|
| | end = allPaths{ant}(i+1);
|
| | deltaPheromone(start, end) = deltaPheromone(start, end) + Q / allDistances(ant);
|
| | end
|
| | end
|
| | |
| | % 信息素挥发和更新
|
| | pheromone = (1 - rho) * pheromone + deltaPheromone;
|
| | |
| | % 可选:打印迭代信息
|
| | fprintf('Iteration %d: Best Distance = %.2f\n', iter, min(allDistances));
|
| | end
|
| | |
| | % 找到最佳路径
|
| | [minDist, bestIdx] = min(allDistances);
|
| | bestPath = allPaths{bestIdx};
|
| | disp(['Best Path: ', num2str(bestPath)]);
|
| | disp(['Best Distance: ', num2str(minDist)]);
|
| | end
|
使用方法
可以通过调用aco_tsp
函数并传入适当的参数来运行蚁群算法。例如:
|---|-----------------------------------------|
| | aco_tsp(50, 20, 100, 1, 5, 0.5, 100);
|
这里设置了50个城市,20只蚂蚁,迭代100次,信息素重要程度因子为1,启发式信息重要程度因子为5,信息素挥发系数为0.5,信息素强度为100。