蚁群算法_Python实现

import numpy as np

class AntColony:
    def __init__(self, distances, n_ants, n_best, n_iterations, decay, alpha=1, beta=1):
        # 初始化蚁群算法的参数
        self.distances = distances  # 城市间的距离矩阵
        # 初始化信息素矩阵, 行列为输入的distances的行列, 每个信息素的初始值为1/distances的行数, 也就是说每行信息素的和都=1
        self.pheromone = np.ones(self.distances.shape) / len(distances)
        self.all_inds = range(len(distances))  # 城市索引, 列表=[0,1,2,3...len(distances)]
        self.n_ants = n_ants  # 蚂蚁数量
        self.n_best = n_best  # 选择的最佳路径数量, b_best=1
        self.n_iterations = n_iterations  # 迭代次数
        self.decay = decay  # 信息素衰减率
        self.alpha = alpha  # 信息素重要性因子
        self.beta = beta  # 启发式信息重要性因子

    def run(self):
        shortest_path = None  # 当前迭代中的最短路径
        all_time_shortest_path = ("placeholder", np.inf)  # 全局最短路径, np.inf代表无穷大
        for i in range(self.n_iterations):
            all_paths = self.gen_all_paths()  # 生成所有蚂蚁的路径
            self.spread_pheronome(all_paths, self.n_best, shortest_path=shortest_path)  # 传播信息素
            shortest_path = min(all_paths, key=lambda x: x[1])  # 找到当前迭代中的最短路径
            if shortest_path[1] < all_time_shortest_path[1]:
                all_time_shortest_path = shortest_path  # 更新全局最短路径
            self.pheromone * self.decay  # 信息素衰减
        return all_time_shortest_path

    def spread_pheronome(self, all_paths, n_best, shortest_path):
        sorted_paths = sorted(all_paths, key=lambda x: x[1])  # 按路径长度排序
        for path, dist in sorted_paths[:n_best]:
            for move in path:
                self.pheromone[move] += 1.0 / self.distances[move]  # 更新信息素

    def gen_path_dist(self, path):
        total_dist = 0
        for ele in path:
            total_dist += self.distances[ele]  # 计算路径总距离
        return total_dist

    def gen_all_paths(self):#形成所有蚂蚁的路径
        all_paths = []
        for i in range(self.n_ants):
            path = self.gen_path(0)  # 生成单个蚂蚁的路径
            all_paths.append((path, self.gen_path_dist(path)))  # 记录单个蚂蚁访问城市的路径和总距离
        return all_paths
    #记录单个蚂蚁访问所有城市的路径图
    def gen_path(self, start):#start代表单个蚂蚁起始位置, 本例中所有蚂蚁都从0号位置开始访问
        path = []
        visited = set()     #初始化一个空的集合
        visited.add(start)  # 标记起始城市为已访问
        prev = start
        for i in range(len(self.distances) - 1):
            move = self.pick_move(self.pheromone[prev], self.distances[prev], visited)  # 选择下一步移动
            path.append((prev, move))  # 记录路径
            prev = move
            visited.add(move)  # 标记城市为已访问
        path.append((prev, start))  # 返回起始城市
        return path


    #从未被访问过的城市中随机选择一个城市访问, 返回被选择的未被访问过的城市的序号
    def pick_move(self
                  , pheromone   #初始化信息素矩阵, 行列为输入的distances的行列, 每个信息素的初始值为1/distances的行数, 也就是说每行信息素的和都=1
                                #self.pheromone = np.ones(self.distances.shape) / len(distances)
                  , dist        #dist代表城市之间的距离矩阵
                  , visited #visited = set()  # 初始化一个空的集合 visited.add(start)  # 标记起始城市为已访问
                  ):#蚂蚁选择下一步要移动的位置

        # 创建信息素数组的副本, pheromone是一个数组,因为传参时传的是self.pheromone[prev], prev=0
        pheromone = np.copy(pheromone)
        #list(visited)是一个集合转成列表, 代表在将列表中的各个元素所在数组中指向的位置中的值设置为0
        pheromone[list(visited)] = 0  # 已访问城市的信息素设为0
        #pheromone ** self.alpha代表城市i到城市j之间的信息素浓度, alpha=1
        #(1.0 / dist)代表启发式信息, 通常是距离的倒数, beta-1
        row = pheromone ** self.alpha * ((1.0 / dist) ** self.beta)  # 计算选择概率

        norm_row = row / row.sum()  # 归一化概率, 由于使用归一化, 所以在当前情况下, 除了值为0的元素(已访问过的城市)之外, 其余城市选择的概率相等
        move = np_choice(self.all_inds         #self.all_inds = range(len(distances))  # 城市索引, 列表=[0,1,2,3...len(distances)]
                         , 1, p=norm_row)[0]  # 按概率选择下一个城市(未被选择过的城市)
        return move

def np_choice(a, size, replace=True, p=None):#replace=True代表允许重复, size代表要选择的个数
    return np.random.choice(a, size, replace, p)#从剩下的城市中随机选择一个城市

if __name__ == "__main__":
    #城市之间的距离, 代表i号城市和j号城市之间的距离, 每一行代表i号城市与其它城市之间的距离
    #例子: 第0行代表0号城市与0,1,2,3,4号城市之间的距离; 第1行代表1号城市与1,2,3,4,5号城市之间的距离. 是一个对称矩阵
    distances = np.array([[np.inf, 2, 2, 5, 7],
                          [2, np.inf, 4, 8, 2],
                          [2, 4, np.inf, 1, 3],
                          [5, 8, 1, np.inf, 2],
                          [7, 2, 3, 2, np.inf]])

    ant_colony = AntColony(distances, 3, 1, 100, 0.95, alpha=1, beta=2)
    shortest_path = ant_colony.run()
    print("shortest_path: {}".format(shortest_path))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
蚁群算法是一种模拟蚂蚁寻找食物的行为来解决优化问题的算法。下面介绍如何使用 Python 实现蚁群算法。 步骤1:定义问题 首先,需要定义一个优化问题,例如:求解函数 $f(x)=x^2+2x+1$ 的最小值,其中 $x$ 的范围为 $[-5,5]$。 步骤2:初始化参数 在蚁群算法中,需要定义许多参数,包括蚂蚁数量、迭代次数、信息素挥发系数、信息素增加系数等。这里定义蚂蚁数量为 20,迭代次数为 100,信息素挥发系数为 0.5,信息素增加系数为 1。 ```python ant_num = 20 # 蚂蚁数量 iter_num = 100 # 迭代次数 evap_rate = 0.5 # 信息素挥发系数 alpha = 1 # 信息素增加系数 ``` 步骤3:初始化蚂蚁位置和信息素 接下来,需要随机初始化蚂蚁的位置和信息素的初始值。蚂蚁的位置可以在 $[-5,5]$ 的范围内随机生成,信息素的初始值设置为一个很小的数,例如 0.01。 ```python import numpy as np ant_pos = np.random.uniform(-5, 5, size=(ant_num, 1)) # 蚂蚁位置 pheromone = np.ones((100,)) * 0.01 # 信息素 ``` 步骤4:定义蚂蚁的移动规则 根据蚂蚁寻找食物的行为,蚂蚁在搜索过程中会遵循一定的规则。这里定义蚂蚁的移动规则为:蚂蚁按照一定的概率选择下一步的移动方向,概率与当前位置的信息素浓度有关;蚂蚁移动一步后,会在当前位置留下一定的信息素。 ```python def ant_move(ant_pos, pheromone): # 计算每只蚂蚁下一步移动的方向 prob = pheromone / np.sum(pheromone) move_dir = np.random.choice([-1, 1], size=(ant_num,), p=[prob, 1 - prob]) # 更新蚂蚁的位置和留下的信息素 ant_pos += move_dir.reshape(-1, 1) for i in range(ant_num): idx = int(ant_pos[i]) pheromone[idx] += alpha return ant_pos, pheromone ``` 步骤5:定义蚂蚁的选择规则 当所有蚂蚁都完成一次移动后,需要根据蚂蚁的选择规则更新信息素。在蚁群算法中,蚂蚁会选择路径上信息素浓度高的方向,因此需要根据蚂蚁的位置更新信息素。 ```python def update_pheromone(ant_pos, pheromone, evap_rate): # 计算每只蚂蚁经过的路径上留下的信息素 ant_path = np.zeros((100,)) for i in range(ant_num): idx = int(ant_pos[i]) ant_path[idx] += 1 # 更新信息素 pheromone *= (1 - evap_rate) # 信息素挥发 pheromone += ant_path # 信息素增加 return pheromone ``` 步骤6:迭代求解 最后,将上述步骤组合起来,进行迭代求解。每次迭代后,记录当前的最优解和最优解对应的位置。迭代结束后,返回最优解和最优解对应的位置。 ```python def ant_colony_optimization(): ant_pos = np.random.uniform(-5, 5, size=(ant_num, 1)) pheromone = np.ones((100,)) * 0.01 best_fitness = np.inf best_position = None for i in range(iter_num): ant_pos, pheromone = ant_move(ant_pos, pheromone) fitness = ant_pos ** 2 + 2 * ant_pos + 1 if np.min(fitness) < best_fitness: best_fitness = np.min(fitness) best_position = ant_pos[np.argmin(fitness)] pheromone = update_pheromone(ant_pos, pheromone, evap_rate) return best_fitness, best_position ``` 完整代码如下:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值