【进阶四】Python实现(MD)HVRP常见求解算法——蚁群算法(ACO)

禁忌搜索(Tabu Search)算法及python实现 禁忌搜索(Tabu Search)算法解决及python实现 禁忌搜索(Tabu Search,TS,又称禁忌搜寻法)是一种现代启发式算法,由美国科罗拉多大学教授Fred Glover在1986年左右提出的,是一个用来跳脱局部最优解的搜索方法。其先创立一个初始化的方案;基于此,算法“移动”到一相邻的方案。经过许多连续的移动过程,提高解的质量。本Markdown编辑器使用StackEdit修改而来... 阅读详情

蚁群算法+Split 求解异构车辆路径规划问题

信息传递

1. 适用场景

  • 求解HVRP或MDHVRP
  • 多车辆类型
  • 车辆容量不小于需求节点最大需求
  • (多)车辆基地
  • 车场车辆总数满足实际需求

2. 求解效果

(1)收敛曲线
在这里插入图片描述

(2)车辆路径
在这里插入图片描述

3. 代码分析

在这里插入图片描述
以上算法在搜索过程中需求节点的备选标签规模会非常大,占用内存且降低搜索效率,因此采用了帕累托思想来遗传非支配解(19行~21行)。为了进一步控制备选标签数量,本期文章还附加实现了通过剩余容量与剩余需求来判断是否产生新的备选标签,提前避免产生不可行的标签。尽管如此,当考虑的异构车辆类型较多、需求点规模较大时,求解效率依然较低(代码结构、python特性、硬件环境)。所以本期文章进一步加入了最大标签数量参数来控制每个需求节点的备选标签规模,通过调节该参数实现速度与质量的相对均衡。

4. 数据格式

这里采用solomon开源数据对算法进行测试,数据文件结构如下图所示,共100个需求点,3个车场,3类车辆,以.csv文件储存数据。
demand.csv文件内容如下图,其中第一行为标题栏,节点id从0开始递增编号。

在这里插入图片描述
depot.csv文件内容如下图,其中第一行为标题栏,依次为:车场id,车场平面x坐标,车场平面y坐标,车辆类型,车辆装载量,车辆数量,固定成本,单位里程运输成本。

在这里插入图片描述

5. 分步实现

(1)代码整体架构
在这里插入图片描述

(2)数据结构
定义Sol()类,Demand()类,Vehicle()类,Model()类,其属性如下表:

  • Sol()类,表示一个可行解
属性描述
node_id_list需求节点id有序排列集合
obj优化目标值
route_list车辆路径集合,对应MDVRPTW的解
  • Demand()类,表示一个需求节点
属性描述
id物理节点id,需唯一
x_coord物理节点x坐标
y_coord物理节点y坐标
demand物理节点需求
  • Vehicle()类,表示一个车队节点
属性描述
depot_id车辆归属的车场节点节点id,需唯一
x_coord车辆归属车场节点x坐标
y_coord车辆归属车场节点y坐标
type车辆类型
capacity车辆容量
free_speed车辆运营速度
fixed_cost车辆固定成本
variable_cost车辆变动成本
  • Model()类,存储算法参数
属性描述
best_sol全局最优解,值类型为Sol()
demand_dict需求节点集合(字典),值类型为Demand()
vehicle_dict车队集合(字典),值类型为Vehicle()
vehicle_type_list车队id集合
demand_id_list需求节点id集合
sol_list种群,值类型为Sol()
distance_matrix节点距离矩阵
number_of_demands需求节点数量
alpha信息启发式因子
beta期望启发式因子
Q信息素总量
tau0路径初始信息素
rho信息素挥发因子
tau信息素集合
max_labels节点最多保留标签数量

(3)数据读取

def readCSVFile(demand_file,depot_file,model):
    with open(demand_file,'r') as f:
        demand_reader=csv.DictReader(f)
        for row in demand_reader:
            demand = Demand()
            demand.id = int(row['id'])
            demand.x_coord = float(row['x_coord'])
            demand.y_coord = float(row['y_coord'])
            demand.demand = float(row['demand'])
            model.demand_dict[demand.id] = demand
            model.demand_id_list.append(demand.id)
        model.number_of_demands=len(model.demand_id_list)

    with open(depot_file, 'r') as f:
        depot_reader = csv.DictReader(f)
        for row in depot_reader:
            vehicle = Vehicle()
            vehicle.depot_id = row['depot_id']
            vehicle.x_coord = float(row['x_coord'])
            vehicle.y_coord = float(row['y_coord'])
            vehicle.type = row['vehicle_type']
            vehicle.capacity=float(row['vehicle_capacity'])
            vehicle.numbers=float(row['number_of_vehicle'])
            vehicle.fixed_cost=float(row['fixed_cost'])
            vehicle.variable_cost=float(row['variable_cost'])
            model.vehicle_dict[vehicle.type] = vehicle
            model.vehicle_type_list.append(vehicle.type)

(4)计算距离矩阵及初始信息素

def initDistanceTau(model):
    for i in range(len(model.demand_id_list)):
        from_node_id = model.demand_id_list[i]
        for j in range(i + 1, len(model.demand_id_list)):
            to_node_id = model.demand_id_list[j]
            dist = math.sqrt((model.demand_dict[from_node_id].x_coord - model.demand_dict[to_node_id].x_coord) ** 2
                             + (model.demand_dict[from_node_id].y_coord - model.demand_dict[to_node_id].y_coord) ** 2)
            model.distance_matrix[from_node_id, to_node_id] = int(dist)
            model.distance_matrix[to_node_id, from_node_id] = int(dist)
            model.tau[from_node_id,to_node_id]=model.tau0
            model.tau[to_node_id,from_node_id]=model.tau0
        for _, vehicle in model.vehicle_dict.items():
            dist = math.sqrt((model.demand_dict[from_node_id].x_coord - vehicle.x_coord) ** 2
                             + (model.demand_dict[from_node_id].y_coord - vehicle.y_coord) ** 2)
            model.distance_matrix[from_node_id, vehicle.type] = int(dist)
            model.distance_matrix[vehicle.type, from_node_id] = int(dist)

(5)路径成本计算

def calTravelCost(route_list,model):
    obj=0
    for route in route_list:
        vehicle=model.vehicle_dict[route[0]]
        distance=0
        fixed_cost=vehicle.fixed_cost
        variable_cost=vehicle.variable_cost
        for i in range(len(route) - 1):
            from_node = route[i]
            to_node = route[i + 1]
            distance += model.distance_matrix[from_node, to_node]
        obj += fixed_cost + distance * variable_cost
    return obj

(6)目标函数计算

def calObj(node_id_list,model):
    vehicle_routes = splitRoutes(node_id_list, model)
    if vehicle_routes:
        return calTravelCost(vehicle_routes,model),vehicle_routes
    else:
        return 10**9,None

(7)蚂蚁移动

def movePosition(model):
    sol_list=[]
    local_sol=Sol()
    local_sol.obj=float('inf')
    for k in range(model.popsize):
        #随机初始化蚂蚁位置
        nodes_id=[int(random.randint(0,len(model.demand_id_list)-1))]
        all_nodes_id=copy.deepcopy(model.demand_id_list)
        all_nodes_id.remove(nodes_id[-1])
        #确定下一个访问节点
        while len(all_nodes_id)>0:
            next_node_no=searchNextNode(model,nodes_id[-1],all_nodes_id)
            nodes_id.append(next_node_no)
            all_nodes_id.remove(next_node_no)
        sol=Sol()
        sol.node_id_list=nodes_id
        sol.obj,sol.routes=calObj(nodes_id,model)
        sol_list.append(sol)
        if sol.obj<local_sol.obj:
            local_sol=copy.deepcopy(sol)
    model.sol_list=copy.deepcopy(sol_list)
    if local_sol.obj<model.best_sol.obj:
        model.best_sol=copy.deepcopy(local_sol)

(8)更新路径信息素

def upateTau(model):
    rho=model.rho
    for k in model.tau.keys():
        model.tau[k]=(1-rho)*model.tau[k]
    #根据解的node_id_list属性更新路径信息素(TSP问题的解)
    for sol in model.sol_list:
        nodes_id=sol.node_id_list
        for i in range(len(nodes_id)-1):
            from_node_id=nodes_id[i]
            to_node_id=nodes_id[i+1]
            model.tau[from_node_id,to_node_id]+=model.Q/sol.obj

(9)绘制收敛曲线

def plotObj(obj_list):
    plt.rcParams['font.sans-serif'] = ['SimHei'] #show chinese
    plt.rcParams['axes.unicode_minus'] = False  # Show minus sign
    plt.plot(np.arange(1,len(obj_list)+1),obj_list)
    plt.xlabel('Iterations')
    plt.ylabel('Obj Value')
    plt.grid()
    plt.xlim(1,len(obj_list)+1)
    plt.show()

(10)绘制车辆路径

def plotRoutes(model):
    for route in model.best_sol.route_list:
        x_coord=[model.vehicle_dict[route[0]].x_coord]
        y_coord=[model.vehicle_dict[route[0]].y_coord]
        for node_id in route[1:-1]:
            x_coord.append(model.demand_dict[node_id].x_coord)
            y_coord.append(model.demand_dict[node_id].y_coord)
        x_coord.append(model.vehicle_dict[route[-1]].x_coord)
        y_coord.append(model.vehicle_dict[route[-1]].y_coord)
        plt.grid()
        if route[0]=='v1':
            plt.plot(x_coord,y_coord,marker='o',color='black',linewidth=0.5,markersize=5)
        elif route[0]=='v2':
            plt.plot(x_coord,y_coord,marker='o',color='orange',linewidth=0.5,markersize=5)
        elif route[0]=='v3':
            plt.plot(x_coord,y_coord,marker='o',color='r',linewidth=0.5,markersize=5)
        else:
            plt.plot(x_coord, y_coord, marker='o', color='b', linewidth=0.5, markersize=5)
    plt.xlabel('x_coord')
    plt.ylabel('y_coord')
    plt.show()

(11)输出结果

def outPut(model):
    work=xlsxwriter.Workbook('result.xlsx')
    worksheet=work.add_worksheet()
    worksheet.write(0, 0, 'obj')
    worksheet.write(0, 1,model.best_sol.obj)
    worksheet.write(1, 0,'vehicleID')
    worksheet.write(1, 1,'depotID')
    worksheet.write(1, 2, 'vehicleType')
    worksheet.write(1, 3,'route')
    for row,route in enumerate(model.best_sol.route_list):
        worksheet.write(row+2,0,str(row+1))
        depot_id=model.vehicle_dict[route[0]].depot_id
        worksheet.write(row+2,1,depot_id)
        worksheet.write(row+2,2,route[0])
        r=[str(i)for i in route]
        worksheet.write(row+2,3, '-'.join(r))
    work.close()

(12)主函数

def run(demand_file,depot_file,Q,tau0,alpha,beta,rho,epochs,popsize,max_labels):
    """
    :param demand_file: demand 文件路径
    :param depot_file: depot 文件路径
    :param Q: 信息素总量
    :param tau0: 路径信息素初始值
    :param alpha: 信息启发式因子
    :param beta: 期望启发式因子
    :param rho: 信息挥发因子
    :param epochs: 迭代次数
    :param v_cap: 车辆容量
    :param opt_type: 优化类型:0:最小化车辆数,1:最小化行驶距离
    :param popsize: 蚁群规模
    :return:
    """
    model=Model()
    model.alpha=alpha
    model.beta=beta
    model.max_labels = max_labels
    model.Q=Q
    model.tau0=tau0
    model.rho=rho
    model.popsize=popsize
    sol=Sol()
    sol.obj=float('inf')
    model.best_sol=sol
    history_best_obj = []
    readCSVFile(demand_file,depot_file,model)
    initDistanceTau(model)
    start_time = time.time()
    for ep in range(epochs):
        movePosition(model)
        upateTau(model)
        history_best_obj.append(model.best_sol.obj)
        print("%s/%s, best obj: %.3f, runtime: %.3f" % (ep + 1, epochs, model.best_sol.obj, time.time() - start_time))
    plotObj(history_best_obj)
    plotRoutes(model)
    outPut(model)

6. 完整代码

如有错误,欢迎交流。
私信获取

参考

  1. Order-first split-second methods for vehicle routing problems: A review
优化模型验证关键代码26:异构车队车辆路径问题模型及gurobipy实现 问题描述、数学模型和gurobipy代码和可视化 阅读详情

相关推荐

禁忌搜索算法Tabu Search代码复现【Python】

禁忌搜索(Tabu Search, TS)是属于模拟人类智能的一种优化算法。 基本流程:禁忌搜索算法在初始化的时候,在搜索空间随机生成一个初始解 i,禁忌表H置空,当前解i记为历史最优解 s,然后进入迭代的搜索过程。在每一次迭代中,都从当前的解i出发,在当前禁忌表H的限制下,构造出解i的邻域A,然后从A中选出适应值最好的解 j 来替换解 i,同时更新禁忌表H。在解 j 替换解 i 之后,如果解 i 的质量得到改善,那么历史最优的解 s 将被解 i 替换;否则,s 保持不变,即使解 i 虽然暂时变差了,但是由于扩大了搜索空间,仍有利于跳出局部最优。得到了新的当前解 i 之后,算法返回迭代的开始继续进行,直到找到最优解或者运行了一定的迭代次数等终止条件的时候结束算法。 &mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash;&mdash; 介绍链接:https://blog.youkuaiyun.com/qq_44186838/article/details/109270374

【进阶四】Python实现(MD)HVRP常见求解算法——禁忌搜索算法(TS)

禁忌搜索算法+Split 求解异构车辆路径规划问题

Better.C的博客 1854

什么是论文的创新点?公式化描述算是创新点吗?

写科研论文时,挑战之一就是如何让你的工作“脱颖而出”,也就是要有创新性。不管实验多么精确、推导多么复杂,若没有真正的创新,论文很可能会被拒。关于如何创新问题上,我最近在看刘雪峰老师的《科技论文写作指南》,看到了很多关于写作的新论述,在这里和大家进行分享。

加百力 的技术博客 1927

禁忌搜索算法python

使用python对旅行商问题进行求解和可视化,提供完整的python代码(一步一步注释说明),并详细说明紧急表长度对算法性能的影响以及禁忌长度的设置方法。

天下弈星~的博客 1545

Android 的端智能学习路径

基础层:先补齐 Android 进阶(JNI / 性能优化)和 AI 基础概念,无需深入算法开发;核心层:掌握 TFLite 的模型加载、推理、量化,能完成基础端侧推理;落地层:聚焦实战场景(图像 / OCR / 语音),解决工程化问题(模型管理、异常处理);优化层:通过模型量化、硬件加速、工程优化,提升推理性能和用户体验。

hqiangtai的博客 346

使用python获取同花顺免费版和同花顺远航版自选股数据用于量化交易

在做量化交易时,有时需要在盘中实时监控同花顺自选股的数量,以便灵活地自定义提醒、捕捉买卖时点等。那么,如何使用python获取同花顺自选股数据呢?

tzzqn2008的专栏 3687

【进阶三】Python实现(MD)HFVRPTW常见求解算法——蚁群算法(ACO)

基于python语言,实现经典蚁群算法(ACO)对多车场(Multi-depot)、异构固定车辆(heterogeneous fixed fleet)、带有服务时间窗(time window)等限制约束的车辆路径规划问题((MD)HFVRPTW)进行求解。

Better.C的博客 2286

Ubuntu 22.04 LTS下Xenomai 3.3实时内核配置全攻略(附常见错误排查)

本文详细介绍了在Ubuntu 22.04 LTS系统上配置Xenomai 3.3实时内核的完整流程,包括环境准备、内核补丁应用、编译优化及常见错误排查。特别针对工业自动化和机器人控制场景,提供了性能优化建议和故障解决方案,帮助开发者实现毫秒级精度的实时任务处理。

weixin_29268385的博客 464

启发式算法-禁忌搜索(Python)

启发式算法-禁忌搜索 python实现

qq_42250782的博客 1106

基于共识的捆绑算法CBBA在多无人机多任务调度中的实现

在捆绑过程中,每个无人机根据自己的任务清单和其他无人机的任务清单,确定一个被称为“束”的集合。通过合理的任务分配和无人机协作,CBBA算法能够实现最优的任务调度,提高了多无人机系统的效率和执行能力。在每一轮迭代中,无人机根据自己的当前任务和位置信息将任务清单发送给其他无人机,并接收其他无人机发送过来的任务清单。通过比较其他无人机的任务清单和自身的任务清单,每个无人机可以更新自己的任务分配情况。在这一步中,每个无人机根据自己选择的新任务,更新自身的任务清单,并将更新后的清单发送给其他无人机。

持续更新 1156

基于Python的军事装备信息爬虫实战:Scrapy+Playwright+智能反反爬技术

本文将详细介绍如何使用Python构建一个高效的军事装备信息爬虫系统。我们将从基础的HTTP请求开始,逐步深入到使用Scrapy框架、Playwright浏览器自动化以及最新的反反爬技术。文章包含完整的代码实现、性能优化策略以及数据处理方案,旨在为读者提供一个全面的军事信息爬取解决方案。关键词:Python爬虫、军事装备、Scrapy、Playwright、反反爬。

2201_76125261的博客 1156

【MATLAB源码-第49期】基于蚁群算法(ACO)算法的栅格路径规划,输出最佳路径图和算法收敛曲线图。

通过上述步骤,蚁群算法在栅格环境中逐渐找到从起始点到终止点的最佳路径。在蚁群系统中,通过模拟蚂蚁之间通过信息素沟通的方式来寻找最短路径。- 每只蚂蚁根据邻近的格子上的信息素浓度和启发函数(例如距离目标的距离)来选择下一个格子。- 那些被更多蚂蚁选择的路径上的信息素浓度会增加,从而吸引更多的蚂蚁。- 路径上的信息素会随时间蒸发,模拟真实环境中的信息素挥发性。- 蚂蚁在移动过程中会在其经过的路径上释放一定量的信息素。- 所有蚂蚁完成一次搜索后,所有路径上的信息素会进行更新。- 初始化所有的路径上的信息素浓度。

Matlab程序猿i的博客 714

nvidia系列教程-AGX-Orin系统刷机及备份

NVIDIA AGX Orin 是一款高性能的嵌入式计算平台,专为边缘计算和 AI 应用而设计。为了确保系统的稳定性和适应不同的应用场景,用户可能需要对 AGX Orin 进行系统刷机和备份操作。本文将详细介绍如何完成这些操作,帮助您更好地管理和维护 AGX Orin 设备。通过以上步骤,您可以成功地为 NVIDIA AGX Orin 刷写系统并创建备份。这些操作不仅能帮助您保持系统的更新和安全,还能在遇到问题时快速恢复系统。

flypig has a dream! 3328

ALNS求MDHVRPTW问题 python实现

ALNS python实现 VRP MDHVRPTW 自适应大邻域搜索

anthea_luo的博客 1775

大疆RoboMaster嵌入式面试,电机FOC调不出来当场走人

摘要:大疆RoboMaster嵌入式工程师面试以实战能力著称,重点考察FreeRTOS任务调度、FOC电机控制和CAN总线三大核心技能。FreeRTOS部分涉及优先级调度、栈溢出排查及信号量与互斥锁的区别;FOC控制要求现场编写电流环代码,并解释Clarke/Park变换原理;CAN总线则关注仲裁机制、CANopen协议应用及错误帧排查方法。面试强调工程实践,需具备STM32开发经验,建议搭建实际环境进行练习。该岗位被誉为"硬件版修罗场",充分体现大疆对实际开发能力的严格要求。

郑伟强dev的专栏 151

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【VRP问题】基于禁忌搜索求解带软时间窗的车辆路径规划TWVRP问题

禁忌搜索算法简介 禁忌搜索算法(Tabu Search Algorithm,简称TS)起源于对于人类记忆功能的模仿,是一种亚启发式算法(meta-heuristics)。它从一个初始可行解(initial feasible solution)出发,试探一系列的特定搜索方向(移动),选择让特定的目标函数值提升最多的移动。为了避免陷入局部最优解,禁忌搜索对已经历过的搜索过程信息进行记录,从而指导下一...

m0_60703264的博客 1376

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

禁忌搜索算法(tabu search)及Python实现

禁忌算法实例

oyoli的博客 998

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

遗传算法解决VRP问题学习笔记

GA遗传算法

weixin_60734616的博客 1711

3. Python实现VRP常见求解算法——禁忌搜索(TS)

参考笔记 https://github.com/PariseC/Algorithms_for_solving_VRP TS算法原理详解 禁忌搜索(Tabu Search)算法及python实现 邻域 对于组合优化问题,给定任意可行解x,x∈D,D是决策变量的定义域,对于D上的一个映射:N:x∈D→N(x)∈2(D) 其中2(D)表示D的所有子集组成的集合,N(x)成为x的一个邻域,y∈N(x)称为x的一个邻居。 候选集合 候选集合一般由邻域中的邻居组成,可以将某解的所有邻居作为候选集合,也可以通过最优提取

qq_36744449的博客 4227

图说蚁群算法(ACO)附源码

PS:再过几天就可以返校收拾东西了,回想疫情宅家的这半年,真是充满了焦虑、惊喜、忙碌、充实又时而无聊,同时又在时时刻刻想念着她。。。返校只能待三天又让人有点小遗憾呐。就想着趁还在家这几天,把毕设用到的一些算法整理一下吧! 废话不多说了,这次要讲的是蚁群算法(下称ACO)。 ① 初识ACO:这是个啥玩意? 蚁群算法是一种用来规划最优路径的概率型算法,其原理参考了蚁群在寻找食物过程中发现最短路径的行为。这里我们先不谈高大上的数学原理,我们先定性地说下蚁群算法的基本原理蚁群在不同环境下寻找到达食物源最短路径

Flag_ing的博客 9496

禁忌搜索算法求解TSP问题-python实现

禁忌搜索算法求解TSP问题-python实现(附代码)

_2312 7801

【进阶二】Python实现VRPTW常见求解算法——禁忌搜索(TS)

基于python语言,实现经典禁忌搜索算法(TS)对带有时间窗的车辆路径规划问题(VRPTW )进行求解。

Better.C的博客 4038

【Python】禁忌搜索算法求解最短路径问题(含python代码实现)

python实现禁忌搜索算法求解最短路径问题

kk的博客 1159

蚁群优化算法(ACO)

背景 思路

qq_44865735的博客 1万+

python实现模拟退火算法解决旅行商(TSP)问题

TSP的难点在于随着城市数量的增加,搜索所有可能的路径将变得非常耗时,因为路径的数量是城市数量的阶乘。:在当前解的基础上进行微小的扰动,例如交换两个城市的顺序,得到一个新的解。这种随机性和“接受劣解”的策略使得模拟退火算法有可能避免陷入局部最优解,同时在搜索空间中进行广泛的探索,从而找到更优的解。算法中的温度和接受劣解的概率是关键的参数,它们影响了算法的探索性能。在TSP问题中,模拟退火算法在解决旅行商问题(TSP)时的思路是通过在解空间中进行随机游走,模拟“退火”过程中的分子在热系统中的运动。

qq_49370210的博客 3447
上一篇: 【进阶四】Python实现(MD)HVRP常见求解算法——禁忌搜索算法(TS)
下一篇: 【第一期】看图识车站,快来看看你是不是资深铁路迷
Better.C
博客等级 码龄9年 1万+粉丝 72原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Better.C

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值