蚁群算法求解TSP问题-python实现

蚁群算法求解TSP问题

1. TSP问题简介

旅行商人要拜访n个城市,并最终回到出发城市,要求每个城市只能拜访一次,优化目标是最小化路程之和。

2. 例子求解结果

20个城市坐标:(88, 16),(42, 76),(5, 76),(69, 13),(73, 56),(100, 100),(22, 92),(48, 74),(73, 46),(39, 1),(51, 75),(92, 2),(101, 44),(55, 26),(71, 27),(42, 81),(51, 91),(89, 54),(33, 18),(40, 78)
结果路径图如下:
在这里插入图片描述

3. 蚁群算法简介

3.1 蚁群算法基本原理

1、蚂蚁在行走过程中会依据信息素来选择道路,选择信息素较浓的路走,并且在行走的路径中会释放信息素,对于所有蚂蚁都没经过的路,则随机选择一条路走;
2、蚂蚁释放的信息素浓度与长度相关,通常与路径长度成反比;
3、信息素浓的路径会受到蚂蚁更大概率的选择,形成正向反馈,最短路径上的信息素浓度会越来越大,最终蚁群就都按这条最短路径走。

信息素计算公式、转移概率、信息素重要程度因子、启发函数重要程度因子、信息素挥发因子等详细介绍可参考蚁群算法详细讲解TSP解决之道——蚁群算法

3.2 算法的两个关键步骤

1、选择:为蚂蚁选择下一个城市,信息素越多的路径被选中概率较大,可用轮盘赌算法实现;
2、信息素更新:一段时间后(蚂蚁走完一个城市或者走完整个路径后)重新计算信息素(计算方法:历史累计信息素-信息素挥发量+蚂蚁行走释放量),蚂蚁行走释放量的常见方法有三种:蚁周算法(ant-cycle,蚂蚁走完整个路径后,蚂蚁行走释放部分用Q/L计算,Q表示蚂蚁释放信息素的量,为常量,L表示路径总长度)、蚁密算法(ant-density,蚂蚁走完一个城市后,蚂蚁行走释放用Q表示)、蚁量算法(ant-quantity,蚂蚁走完一个城市后,蚂蚁行走释放用Q/dij表示,dij表示城市i和j之间的距离)。

4. 蚁群算法设计

在本算法设计中,包含两层循环,外循环是迭代次数循环,内循环遍历每一只蚂蚁,其中信息素增量在每一只蚂蚁走完整体路径后对当前信息素更新,而信息素挥发只在每一代蚂蚁都走完后对当前信息素更新,流程如下:
在这里插入图片描述

# -*- coding: utf-8 -*-
"""
蚁群算法求解TSP问题
随机在(0,101)二维平面生成20个点
距离最小化
"""
import math
import random
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.pylab import mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']  # 添加这条可以让图形显示中文


#计算路径距离,即评价函数
def calFitness(line,dis_matrix):
    dis_sum = 0
    dis = 0
    for i in range(len(line)-1):
        dis = dis_matrix.loc[line[i],line[i+1]]#计算距离
        dis_sum = dis_sum+dis
    dis = dis_matrix.loc[line[-1],line[0]]
    dis_sum = dis_sum+dis
    
    return round(dis_sum,1)


def intialize(CityCoordinates,antNum):
    """
    初始化,为蚂蚁分配初始城市
    输入:CityCoordinates-城市坐标;antNum-蚂蚁数量
    输出:cityList-蚂蚁初始城市列表,记录蚂蚁初始城市;cityTabu-蚂蚁城市禁忌列表,记录蚂蚁未经过城市
    """
    cityList,cityTabu = [None]*antNum,[None]*antNum#初始化
    for i in range(len(cityList)):
        city = random.randint(0, len(CityCoordinates)-1)#初始城市,默认城市序号为0开始计算
        cityList[i] = [city]
        cityTabu[i] = list(range(len(CityCoordinates)))
        cityTabu[i].remove(city)
    
    return cityList,cityTabu


def select(antCityList,antCityTabu,trans_p):
    '''
    轮盘赌选择,根据出发城市选出途径所有城市
    输入:trans_p-概率矩阵;antCityTabu-城市禁忌表,即未经过城市;
    输出:完整城市路径-antCityList;
    '''
    while len(antCityTabu) > 0:  
        if len(antCityTabu) == 1:
            nextCity = antCityTabu[0]
        else:
            fitness = []
            for i in antCityTabu:fitness.append(trans_p.loc[antCityList[-1],i])#取出antCityTabu对应的城市转移概率
            sumFitness = sum(fitness)
            randNum = random.uniform(0, sumFitness)
            accumulator = 0.0
            for i, ele in enumerate(fitness):
                accumulator += ele
                if accumulator >= randNum:
                    nextCity = antCityTabu[i]
                    break
        antCityList.append(nextCity)
        antCityTabu.remove(nextCity)
    
    return antCityList


def calTrans_p(pheromone,alpha,beta,dis_matrix,Q):
    '''
    根据信息素计算转移概率
    输入:pheromone-当前信息素;alpha-信息素重要程度因子;beta-启发函数重要程度因子;dis_matrix-城市间距离矩阵;Q-信息素常量;
    输出:当前信息素+增量-transProb
    '''
    transProb = Q/dis_matrix # 初始化transProb存储转移概率,同时计算增量
    for i in range(len(transProb)):
        for j in range(len(transProb)):
            transProb.iloc[i,j] = pow(pheromone.iloc[i,j], alpha) * pow(transProb.iloc[i,j], beta)
    
    return transProb


def updatePheromone(pheromone,fit,antCity,rho,Q):
    '''
    更新信息素,蚁周算法
    输入:pheromone-当前信息素;fit-路径长度;antCity-路径;rho-ρ信息素挥发因子;Q-信息素常量
    输出:更新后信息素-pheromone
    '''
    for i in range(len(antCity)-1):
        pheromone.iloc[antCity[i],antCity[i+1]] += Q/fit
    pheromone.iloc[antCity[-1],antCity[0]] += Q/fit
    
    return pheromone

#画路径图
def draw_path(line,CityCoordinates):
    x,y= [],[]
    for i in line:
        Coordinate = CityCoordinates[i]
        x.append(Coordinate[0])
        y.append(Coordinate[1])
    x.append(x[0])
    y.append(y[0])
    
    plt.plot(x, y,'r-', color='#4169E1', alpha=0.8, linewidth=0.8)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()


if __name__ == '__main__':
    #参数
    CityNum = 20#城市数量
    MinCoordinate = 0#二维坐标最小值
    MaxCoordinate = 101#二维坐标最大值
    iterMax = 100#迭代次数
    iterI = 1#当前迭代次数
    #ACO参数
    antNum = 50#蚂蚁数量
    alpha = 2#信息素重要程度因子
    beta = 1#启发函数重要程度因子
    rho = 0.2#信息素挥发因子
    Q = 100.0#常数
    
    best_fit = math.pow(10,10)#较大的初始值,存储最优解
    best_line = []#存储最优路径
    
    #随机生成城市数据,城市序号为0,1,2,3...
    # CityCoordinates = [(random.randint(MinCoordinate,MaxCoordinate),random.randint(MinCoordinate,MaxCoordinate)) for i in range(CityNum)]
    CityCoordinates = [(88, 16),(42, 76),(5, 76),(69, 13),(73, 56),(100, 100),(22, 92),(48, 74),(73, 46),(39, 1),(51, 75),(92, 2),(101, 44),(55, 26),(71, 27),(42, 81),(51, 91),(89, 54),(33, 18),(40, 78)]
    
    #计算城市间距离,生成矩阵
    dis_matrix = pd.DataFrame(data=None,columns=range(len(CityCoordinates)),index=range(len(CityCoordinates)))
    for i in range(len(CityCoordinates)):
        xi,yi = CityCoordinates[i][0],CityCoordinates[i][1]
        for j in range(len(CityCoordinates)):
            xj,yj = CityCoordinates[j][0],CityCoordinates[j][1]
            if (xi==xj) & (yi==yj):
                dis_matrix.iloc[i,j] = round(math.pow(10,10))
            else:
                dis_matrix.iloc[i,j] = round(math.sqrt((xi-xj)**2+(yi-yj)**2),2)
    
    pheromone = pd.DataFrame(data=Q,columns=range(len(CityCoordinates)),index=range(len(CityCoordinates)))#初始化信息素,所有路径都为Q
    trans_p = calTrans_p(pheromone,alpha,beta,dis_matrix,Q)#计算初始转移概率
    
    while iterI <= iterMax:
        '''
        每一代更新一次环境因素导致的信息素减少,每一代中的每一个蚂蚁完成路径后,都进行信息素增量更新(采用蚁周模型)和转移概率更新;
        每一代开始都先初始化蚂蚁出发城市;
        '''
        antCityList,antCityTabu = intialize(CityCoordinates,antNum)#初始化城市
        fitList = [None]*antNum#适应值列表
        
        for i in range(antNum):#根据转移概率选择后续途径城市,并计算适应值
            antCityList[i] = select(antCityList[i],antCityTabu[i],trans_p)
            fitList[i] = calFitness(antCityList[i],dis_matrix)#适应度,即路径长度
            pheromone = updatePheromone(pheromone,fitList[i],antCityList[i],rho,Q)#更新当前蚂蚁信息素增量
            trans_p = calTrans_p(pheromone,alpha,beta,dis_matrix,Q)
        
        if best_fit >= min(fitList):
            best_fit = min(fitList)
            best_line = antCityList[fitList.index(min(fitList))]
            
        print(iterI,best_fit)#打印当前代数和最佳适应度值
        iterI += 1#迭代计数加一
        pheromone = pheromone*(1-rho)#信息素挥发更新
    
    print(best_line)#路径顺序
    draw_path(best_line,CityCoordinates)#画路径图

TSP系列目录
智能优化算法类别启发式算法求解TSP问题系列博文
进化算法遗传算法求解TSP问题
仿人智能优化算法禁忌搜索算法求解TSP问题
仿自然优化算法模拟退火算法求解TSP问题
群智能优化算法蚁群算法求解TSP问题
群智能优化算法粒子群算法求解TSP问题
总结篇五种常见启发式算法求解TSP问题
改进篇遗传-粒子群算法&遗传-禁忌搜索算法求解TSP问题

记录学习过程,欢迎指正

  • 8
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
蚁群算法是一种模拟蚂蚁觅食行为的优化算法,常用于求解TSP问题。以下是Python实现蚁群算法求解TSP问题的示例代码: ``` python import numpy as np import random # TSP距离矩阵 distance_matrix = [[0, 1, 2, 3, 4], [1, 0, 3, 2, 5], [2, 3, 0, 4, 6], [3, 2, 4, 0, 7], [4, 5, 6, 7, 0]] # 蚂蚁数量 ant_count = 10 # 蚂蚁移动距离的影响因子 alpha = 1 # 蚂蚁信息素浓度的影响因子 beta = 5 # 信息素的挥发系数 rho = 0.1 # 初始信息素浓度 tau0 = 1 # 迭代次数 iteration_count = 100 # 初始化信息素浓度矩阵 tau = np.zeros((5, 5)) + tau0 # 计算路径长度 def path_length(path): length = 0 for i in range(len(path) - 1): length += distance_matrix[path[i]][path[i + 1]] length += distance_matrix[path[-1]][path[0]] return length # 选择下一个节点 def select_next_node(current_node, visited_nodes): # 计算当前节点到其他节点的信息素浓度和启发式因子 probabilities = [] for i in range(len(distance_matrix)): if i not in visited_nodes: tau_ij = tau[current_node][i] eta_ij = 1 / distance_matrix[current_node][i] p = (tau_ij ** alpha) * (eta_ij ** beta) probabilities.append(p) else: probabilities.append(0) # 根据概率选择下一个节点 probabilities = probabilities / np.sum(probabilities) next_node = np.random.choice(range(len(distance_matrix)), p=probabilities) return next_node # 更新信息素浓度 def update_pheromone(ant_paths): global tau # 挥发信息素 tau = (1 - rho) * tau # 更新信息素 for path in ant_paths: length = path_length(path) for i in range(len(path) - 1): tau[path[i]][path[i + 1]] += 1 / length tau[path[-1]][path[0]] += 1 / length # 蚁群算法主函数 def ant_colony_optimization(): global tau shortest_path_length = float('inf') shortest_path = [] for i in range(iteration_count): # 初始化蚂蚁位置 ant_positions = [random.randint(0, len(distance_matrix) - 1) for _ in range(ant_count)] ant_paths = [] # 蚂蚁移动 for j in range(len(distance_matrix) - 1): for k in range(ant_count): current_node = ant_positions[k] visited_nodes = ant_positions[:k] + ant_positions[k + 1:j + 1] next_node = select_next_node(current_node, visited_nodes) ant_positions[k] = next_node ant_paths.append(ant_positions.copy()) # 更新信息素浓度 update_pheromone(ant_paths) # 记录最短路径 min_path_index = np.argmin([path_length(path) for path in ant_paths]) if path_length(ant_paths[min_path_index]) < shortest_path_length: shortest_path_length = path_length(ant_paths[min_path_index]) shortest_path = ant_paths[min_path_index] return shortest_path, shortest_path_length # 测试 shortest_path, shortest_path_length = ant_colony_optimization() print('Shortest path:', shortest_path) print('Shortest path length:', shortest_path_length) ``` 注:该示例代码中的TSP距离矩阵为一个简单的5个节点的例子,实际使用时需根据具体问题进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值