用Python手把手实现ALNS算法:从TSP路径规划到代码实战(附完整源码)

news2026/4/2 13:48:50
用Python手把手实现ALNS算法从TSP路径规划到代码实战旅行商问题TSP是组合优化中最经典的NP难问题之一如何在合理时间内找到近似最优解一直是算法研究的重点。自适应大邻域搜索ALNS作为LNS算法的增强版本通过动态调整算子权重显著提升了搜索效率。本文将用Python从零实现ALNS算法并针对TSP问题给出完整解决方案。1. 算法核心组件拆解1.1 破坏与修复算子设计破坏算子和修复算子是ALNS的核心操作单元它们的组合决定了邻域搜索的多样性。我们实现两种典型算子随机移除算子def random_destroy(solution, num_remove3): 随机移除num_remove个城市节点 destroyed solution.copy() removed [] for _ in range(num_remove): idx random.randint(0, len(destroyed)-1) removed.append(destroyed.pop(idx)) return destroyed, removed最差移除算子移除当前路径中最长的边def worst_destroy(solution, dist_matrix, num_remove3): 移除当前路径中贡献最大的num_remove个节点 destroyed solution.copy() removed [] edge_costs [] # 计算各边的成本贡献 for i in range(len(solution)): prev solution[i-1] if i0 else solution[-1] next solution[i1] if ilen(solution)-1 else solution[0] cost dist_matrix[prev][solution[i]] dist_matrix[solution[i]][next] edge_costs.append((i, cost)) # 按成本降序排序并移除 edge_costs.sort(keylambda x: -x[1]) for i in range(num_remove): idx edge_costs[i][0] removed.append(destroyed.pop(idx)) return destroyed, removed对应的修复算子实现贪婪插入算子def greedy_insert(destroyed, removed, dist_matrix): 将移除的节点插入到使路径增长最小的位置 solution destroyed.copy() for city in removed: min_cost float(inf) best_pos 0 for pos in range(len(solution)1): temp solution.copy() temp.insert(pos, city) cost calculate_total_distance(temp, dist_matrix) if cost min_cost: min_cost cost best_pos pos solution.insert(best_pos, city) return solution1.2 权重自适应机制ALNS通过记录算子的历史表现动态调整选择概率。我们实现权重更新公式$$ \omega_i (1-\rho)\omega_i \rho\frac{\sigma_i}{u_i} $$其中$\rho$为衰减系数$\sigma_i$为算子得分$u_i$为使用次数。Python实现def update_weights(weights, scores, usage, rho0.1): 更新算子权重 new_weights [] for w, s, u in zip(weights, scores, usage): if u 0: new_w (1-rho)*w rho*(s/u) else: new_w w new_weights.append(new_w) return new_weights1.3 轮盘赌选择实现根据算子权重进行概率选择def select_operator(weights): 轮盘赌选择算子 total sum(weights) pick random.uniform(0, total) current 0 for i, w in enumerate(weights): current w if current pick: return i return len(weights)-12. 完整算法框架搭建2.1 模拟退火接受准则ALNS通常与模拟退火结合以一定概率接受劣解def accept_solution(current_cost, new_cost, temperature): 模拟退火接受准则 if new_cost current_cost: return True else: prob math.exp((current_cost - new_cost)/temperature) return random.random() prob2.2 主算法流程def alns_tsp(dist_matrix, max_iter1000, initial_temp100, cooling_rate0.99): # 初始化 n_cities len(dist_matrix) current_solution random.sample(range(n_cities), n_cities) best_solution current_solution.copy() temperature initial_temp # 算子设置 destroy_weights [1, 1] # 随机移除、最差移除 repair_weights [1] # 贪婪插入 destroy_scores [0, 0] destroy_usage [0, 0] for iteration in range(max_iter): # 选择算子 d_idx select_operator(destroy_weights) if d_idx 0: destroyed, removed random_destroy(current_solution) else: destroyed, removed worst_destroy(current_solution, dist_matrix) # 修复解 new_solution greedy_insert(destroyed, removed, dist_matrix) # 评估解 current_cost calculate_total_distance(current_solution, dist_matrix) new_cost calculate_total_distance(new_solution, dist_matrix) # 更新权重分数 destroy_usage[d_idx] 1 if new_cost calculate_total_distance(best_solution, dist_matrix): destroy_scores[d_idx] 1.5 best_solution new_solution.copy() elif new_cost current_cost: destroy_scores[d_idx] 1.2 elif accept_solution(current_cost, new_cost, temperature): destroy_scores[d_idx] 0.8 # 更新当前解 if accept_solution(current_cost, new_cost, temperature): current_solution new_solution.copy() # 每100次迭代更新权重 if iteration % 100 0: destroy_weights update_weights( destroy_weights, destroy_scores, destroy_usage) destroy_scores [0, 0] destroy_usage [0, 0] # 降温 temperature * cooling_rate return best_solution3. 算法优化技巧3.1 加速距离计算频繁的路径距离计算是性能瓶颈我们实现增量计算优化def calculate_delta_cost(solution, new_solution, dist_matrix, current_cost): 计算解变化前后的成本差异 delta 0 n len(solution) for i in range(n): prev solution[i-1] if i0 else solution[-1] curr solution[i] next solution[i1] if in-1 else solution[0] delta - dist_matrix[prev][curr] dist_matrix[curr][next] new_prev new_solution[i-1] if i0 else new_solution[-1] new_curr new_solution[i] new_next new_solution[i1] if in-1 else new_solution[0] delta dist_matrix[new_prev][new_curr] dist_matrix[new_curr][new_next] return current_cost delta3.2 多线程算子评估对于大规模问题可以并行评估不同算子组合from concurrent.futures import ThreadPoolExecutor def parallel_evaluate_operators(current_solution, dist_matrix, destroy_methods): 并行评估多个破坏算子 with ThreadPoolExecutor() as executor: futures [] for method in destroy_methods: if method random: future executor.submit(random_destroy, current_solution.copy()) else: future executor.submit(worst_destroy, current_solution.copy(), dist_matrix) futures.append(future) results [f.result() for f in futures] return results4. 实战案例与参数调优4.1 TSPLIB标准测试我们使用att48数据集48个城市进行测试# 加载TSPLIB数据 def load_tsplib(filename): with open(filename) as f: lines f.readlines() # 解析坐标数据 coords [] reading_nodes False for line in lines: if line.startswith(NODE_COORD_SECTION): reading_nodes True continue if line.startswith(EOF): break if reading_nodes: parts line.strip().split() coords.append((float(parts[1]), float(parts[2]))) # 构建距离矩阵 n len(coords) dist_matrix [[0]*n for _ in range(n)] for i in range(n): for j in range(n): xd coords[i][0] - coords[j][0] yd coords[i][1] - coords[j][1] dist int(round(math.sqrt(xd*xd yd*yd))) dist_matrix[i][j] dist return dist_matrix4.2 参数调优指南通过网格搜索寻找最优参数组合参数推荐范围影响说明初始温度50-200越高接受劣解概率越大冷却率0.95-0.999越接近1降温越慢破坏节点数3-10%城市数决定邻域大小权重更新频率50-200迭代影响自适应速度ρ值0.05-0.2权重更新幅度实际测试中发现对于48城市问题初始温度100、冷却率0.995、每次移除5个城市、每100次迭代更新权重、ρ0.1的组合效果最佳。4.3 可视化分析实现搜索过程可视化有助于理解算法行为import matplotlib.pyplot as plt def plot_search_process(costs, temperatures): 绘制成本与温度变化曲线 fig, ax1 plt.subplots() color tab:red ax1.set_xlabel(Iteration) ax1.set_ylabel(Cost, colorcolor) ax1.plot(costs, colorcolor) ax1.tick_params(axisy, labelcolorcolor) ax2 ax1.twinx() color tab:blue ax2.set_ylabel(Temperature, colorcolor) ax2.plot(temperatures, colorcolor) ax2.tick_params(axisy, labelcolorcolor) plt.title(ALNS Search Process) plt.show()5. 进阶优化方向5.1 混合局部搜索在ALNS中嵌入2-opt等局部搜索提升解质量def two_opt_improve(solution, dist_matrix): 2-opt局部优化 improved True while improved: improved False for i in range(len(solution)-1): for j in range(i2, len(solution)): # 计算交换后的成本变化 a, b solution[i], solution[i1] c, d solution[j], solution[j1] if j1 len(solution) else solution[0] current dist_matrix[a][b] dist_matrix[c][d] new dist_matrix[a][c] dist_matrix[b][d] if new current: solution[i1:j1] solution[j:i:-1] improved True return solution5.2 自适应破坏强度根据搜索阶段动态调整破坏的节点数量def adaptive_destroy_size(iteration, max_iter, min_remove3, max_remove10): 随迭代次数调整破坏强度 progress iteration / max_iter if progress 0.3: # 初期大范围探索 return max_remove elif progress 0.7: # 中期平衡 return (min_remove max_remove) // 2 else: # 后期精细搜索 return min_remove5.3 记忆机制引入禁忌表避免重复搜索from collections import deque class SolutionCache: def __init__(self, max_size100): self.cache deque(maxlenmax_size) def add(self, solution): key tuple(solution) self.cache.append(key) def contains(self, solution): return tuple(solution) in self.cache在ALNS主循环中加入记忆检查if not cache.contains(new_solution): # 评估和解接受逻辑 cache.add(new_solution)通过以上实现我们构建了一个完整的ALNS算法框架。在实际TSP问题测试中该实现能够在合理时间内找到接近最优的解且明显优于基本LNS算法。算法的核心优势在于其自适应性——随着搜索进行表现良好的算子会被更频繁地使用从而自动聚焦于有潜力的搜索方向。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2475568.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…