智能优化算法之蚁群算法ACO

蚁群算法(Ant Colony Optimization, ACO)由意大利学者马尔科·多里戈(Marco Dorigo)于1992年在其博士论文中首次提出。灵感来自于自然界中的蚂蚁群体行为,特别是蚂蚁在寻找食物过程中所展示的路径优化能力。蚁群算法属于一种基于群体智能的优化算法,通过模拟蚂蚁在路径上释放信息素的行为来解决复杂的优化问题。

数学原理

蚁群算法的基本思想是通过模拟蚂蚁在路径上释放和挥发信息素的过程,逐步找到问题的最优解。其核心步骤如下:

  1. 初始化信息素矩阵:为所有路径初始化相同量的信息素。

  2. 路径选择:蚂蚁根据路径上的信息素浓度和启发式信息(如距离)选择下一步要走的路径。路径选择概率公式为:

    其中,是路径 上的信息素浓度,是启发式信息(通常是路径的倒数), 和 分别是信息素和启发式信息的相对重要性参数。

  3. 信息素更新:蚂蚁完成路径后,根据路径长度更新信息素。信息素更新公式为:

    其中, 是信息素挥发系数,是蚂蚁在路径上释放的信息素量,通常与路径长度成反比。

  4. 迭代:重复路径选择和信息素更新步骤,直到满足终止条件(如达到最大迭代次数或路径长度不再显著变化)。

应用场景

蚁群算法具有广泛的应用场景,主要包括但不限于以下领域:

  1. 旅行商问题(TSP):最初被用于解决TSP问题,即在给定一组城市中找到最短的巡回路径。

  1. 物流和交通:用于优化物流配送路径、车辆路径规划和交通信号控制等问题。

  2. 网络路由:在计算机网络和通信网络中,用于动态路由选择以提高网络效率。

  3. 生产调度:在制造业中,用于优化生产计划和调度,减少生产成本和时间。

  4. 图像处理:用于图像分割、边缘检测等图像处理任务。

Python 可视化实现

下面是一个使用Python实现蚁群算法解决旅行商问题并进行可视化的示例:

import numpy as np
import matplotlib.pyplot as plt
import random

# 定义城市坐标
cities = np.array([
    [0, 0], [1, 5], [5, 6], [7, 8], [8, 8], [9, 5],
    [8, 0], [6, 1], [3, 2], [1, 1]
])

# 计算距离矩阵
def calculate_distance_matrix(cities):
    num_cities = len(cities)
    distance_matrix = np.zeros((num_cities, num_cities))
    for i in range(num_cities):
        for j in range(num_cities):
            if i != j:
                distance_matrix[i, j] = np.linalg.norm(cities[i] - cities[j])
    return distance_matrix

# 初始化参数
num_ants = 10
num_iterations = 100
alpha = 1.0  # 信息素重要性
beta = 2.0  # 启发式因子重要性
rho = 0.1  # 信息素挥发系数
Q = 1.0  # 信息素强度

# 初始化信息素矩阵
num_cities = len(cities)
pheromone = np.ones((num_cities, num_cities))

# 路径选择函数
def choose_next_city(pheromone, visibility, current_city, visited):
    probabilities = []
    for i in range(num_cities):
        if i not in visited:
            probabilities.append((pheromone[current_city, i] ** alpha) * (visibility[current_city, i] ** beta))
        else:
            probabilities.append(0)
    probabilities = probabilities / np.sum(probabilities)
    return np.random.choice(range(num_cities), p=probabilities)

# 主循环
distance_matrix = calculate_distance_matrix(cities)
visibility = 1 / (distance_matrix + np.diag([np.inf] * num_cities))

best_path = None
best_distance = np.inf

for iteration in range(num_iterations):
    all_paths = []
    all_distances = []
    for ant in range(num_ants):
        path = [random.randint(0, num_cities - 1)]
        visited = set(path)
        while len(visited) < num_cities:
            next_city = choose_next_city(pheromone, visibility, path[-1], visited)
            path.append(next_city)
            visited.add(next_city)
        distance = np.sum([distance_matrix[path[i], path[i + 1]] for i in range(num_cities - 1)])
        distance += distance_matrix[path[-1], path[0]]  # 回到起点
        all_paths.append(path)
        all_distances.append(distance)
        if distance < best_distance:
            best_path = path
            best_distance = distance

    # 更新信息素
    pheromone = (1 - rho) * pheromone
    for path, distance in zip(all_paths, all_distances):
        for i in range(num_cities - 1):
            pheromone[path[i], path[i + 1]] += Q / distance
        pheromone[path[-1], path[0]] += Q / distance

# 可视化最优路径
plt.figure(figsize=(10, 10))
for i in range(num_cities):
    plt.scatter(cities[i, 0], cities[i, 1], color='red')
    plt.text(cities[i, 0], cities[i, 1], str(i), fontsize=12, color='blue')
for i in range(num_cities - 1):
    plt.plot([cities[best_path[i], 0], cities[best_path[i + 1], 0]],
             [cities[best_path[i], 1], cities[best_path[i + 1], 1]], color='green')
plt.plot([cities[best_path[-1], 0], cities[best_path[0], 0]],
         [cities[best_path[-1], 1], cities[best_path[0], 1]], color='green')
plt.title(f'Best Path: {best_path}\nDistance: {best_distance:.2f}')
plt.xlabel('X Coordinate')
plt.ylabel('Y Coordinate')
plt.grid(True)
plt.show()

以上代码实现了蚁群算法解决旅行商问题的基本流程,并通过可视化展示了最优路径和总距离。蚂蚁根据路径上的信息素浓度和启发式信息选择下一步城市,通过不断迭代更新信息素,逐步找到最优解。

图着色问题要求用最少的颜色给图的每个顶点着色,使得相邻顶点颜色不同。

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import random

# 图着色问题的蚁群算法实现
class AntColonyOptimizationForGraphColoring:
    def __init__(self, graph, num_colors, num_ants, num_iterations, alpha=1.0, beta=2.0, evaporation_rate=0.5, pheromone_init=0.1):
        self.graph = graph
        self.num_colors = num_colors
        self.num_ants = num_ants
        self.num_iterations = num_iterations
        self.alpha = alpha
        self.beta = beta
        self.evaporation_rate = evaporation_rate
        self.pheromone = pheromone_init * np.ones((len(graph.nodes), num_colors))
        self.best_coloring = None
        self.best_score = float('inf')

    def solve(self):
        for iteration in range(self.num_iterations):
            all_colorings = []
            for _ in range(self.num_ants):
                coloring = self.construct_solution()
                all_colorings.append(coloring)
                score = self.evaluate_coloring(coloring)
                if score < self.best_score:
                    self.best_score = score
                    self.best_coloring = coloring
            self.update_pheromone(all_colorings)
            print(f"Iteration {iteration+1}/{self.num_iterations}, Best Score: {self.best_score}")

        return self.best_coloring

    def construct_solution(self):
        coloring = [-1] * len(self.graph.nodes)
        for node in self.graph.nodes:
            probabilities = self.compute_probabilities(node, coloring)
            if np.isnan(probabilities).any():
                probabilities = np.ones(self.num_colors) / self.num_colors
            color = np.random.choice(range(self.num_colors), p=probabilities)
            coloring[node] = color
        return coloring

    def compute_probabilities(self, node, coloring):
        pheromone = self.pheromone[node]
        heuristic = np.ones(self.num_colors)
        for neighbor in self.graph.neighbors(node):
            if coloring[neighbor] != -1:
                heuristic[coloring[neighbor]] = 0
        probabilities = (pheromone ** self.alpha) * (heuristic ** self.beta)
        if probabilities.sum() == 0:
            probabilities = np.ones(self.num_colors)
        return probabilities / probabilities.sum()

    def evaluate_coloring(self, coloring):
        conflicts = 0
        for edge in self.graph.edges:
            if coloring[edge[0]] == coloring[edge[1]]:
                conflicts += 1
        return conflicts

    def update_pheromone(self, all_colorings):
        self.pheromone *= (1 - self.evaporation_rate)
        for coloring in all_colorings:
            score = self.evaluate_coloring(coloring)
            for node, color in enumerate(coloring):
                self.pheromone[node][color] += 1 / (1 + score)

# 生成随机图
def generate_random_graph(num_nodes, edge_prob):
    graph = nx.gnp_random_graph(num_nodes, edge_prob)
    return graph

# 可视化图结构
def visualize_graph_structure(graph, title):
    pos = nx.spring_layout(graph)
    nx.draw(graph, pos, with_labels=True, node_size=500, node_color='lightblue', edge_color='gray')
    plt.title(title)
    plt.show()

# 可视化着色结果
def visualize_graph_coloring(graph, coloring, title):
    pos = nx.spring_layout(graph)
    colors = [coloring[node] for node in graph.nodes]
    nx.draw(graph, pos, node_color=colors, with_labels=True, node_size=500, cmap=plt.cm.rainbow)
    plt.title(title)
    plt.show()

# 参数设置
num_nodes = 10
edge_prob = 0.3
num_colors = 3
num_ants = 10
num_iterations = 100

# 生成随机图
graph = generate_random_graph(num_nodes, edge_prob)

# 可视化原始图结构
visualize_graph_structure(graph, "Original Graph Structure")

# 蚁群算法求解图着色问题
aco = AntColonyOptimizationForGraphColoring(graph, num_colors, num_ants, num_iterations)
best_coloring = aco.solve()

# 可视化着色结果
visualize_graph_coloring(graph, best_coloring, f'Graph Coloring with Ant Colony Optimization (Conflicts: {aco.best_score})')

原始图结构:

图着色问题结果:

以上内容总结自网络,如有帮助欢迎转发,我们下次再见!

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

基于stm32+小程序开发智能家居门禁系统-硬件-软件实现

视频演示&#xff1a; 基于stm32智能家居门禁系统小程序开发项目 视频还有添加删除卡号&#xff0c;添加删除指纹&#xff0c;关闭继电器电源等没有演示。 代码Git&#xff1a; https://github.com/Abear6666/stm32lock 总体功能&#xff1a; 本门禁系统主要解锁功能分别为卡…

一文彻底学会Vue3路由:全面讲解路由流程、路由模式、传参等——全栈开发之路--前端篇(7)路由详解

全栈开发一条龙——前端篇 第一篇&#xff1a;框架确定、ide设置与项目创建 第二篇&#xff1a;介绍项目文件意义、组件结构与导入以及setup的引入。 第三篇&#xff1a;setup语法&#xff0c;设置响应式数据。 第四篇&#xff1a;数据绑定、计算属性和watch监视 第五篇 : 组件…

离线 VisualStudio2022 安装包在无互联网的环境下安装

文章目录 下载 Visual Studio 引导程序以创建布局离线安装包将离线包更新为产品的最新版本将布局更新为产品的特定版本 下载 Visual Studio 引导程序以创建布局 https://learn.microsoft.com/zh-cn/visualstudio/install/create-a-network-installation-of-visual-studio?vie…

Golang | Leetcode Golang题解之第223题矩形面积

题目&#xff1a; 题解&#xff1a; func computeArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 int) int {area1 : (ax2 - ax1) * (ay2 - ay1)area2 : (bx2 - bx1) * (by2 - by1)overlapWidth : min(ax2, bx2) - max(ax1, bx1)overlapHeight : min(ay2, by2) - max(ay1, by1)…

浅谈后置处理器之JSON提取器

浅谈后置处理器之JSON提取器 JMeter 的 JSON 提取器&#xff08;JSON Extractor&#xff09;是一个强大的后置处理器&#xff0c;它允许用户从HTTP响应、数据库查询或其他类型的响应中提取JSON数据&#xff0c;并将这些数据存储为变量&#xff0c;以便在后续的请求中重用。这对…

从数据仓库到数据湖(上):数据湖导论

文章目录 一、什么是数据湖&#xff1f;起源数据湖的特征 二、为什么要用数据湖&#xff1f;三、数据湖与数据仓库的区别数据仓库和数据湖的对比 四、数据湖本质数据存储架构数据处理工具&#xff1a;三类第一类工具第二类工具第三类工具 小结 五、总结六、参考资料 一、什么是…

Spring Boot中@Async注解的使用及原理 + 常见问题及解决方案

&#x1f604; 19年之后由于某些原因断更了三年&#xff0c;23年重新扬帆起航&#xff0c;推出更多优质博文&#xff0c;希望大家多多支持&#xff5e; &#x1f337; 古之立大事者&#xff0c;不惟有超世之才&#xff0c;亦必有坚忍不拔之志 &#x1f390; 个人CSND主页——Mi…

手机怎么用代理ip上网

在数字化时代&#xff0c;网络已经成为我们生活中不可或缺的一部分。然而&#xff0c;有时候出于安全、隐私或访问特定网络资源的需要&#xff0c;我们可能需要使用代理IP来上网。那么&#xff0c;什么是代理IP&#xff1f;如何在手机上设置并使用它呢&#xff1f;本文将为您详…

南通网站制作基本步骤有哪些

南通网站制作是一个非常重要的工作&#xff0c;它可以帮助企业展示产品、服务和品牌形象&#xff0c;吸引更多的客户和创造更多的商机。网站制作的基本步骤包括需求分析、规划设计、页面制作、网站测试和上线等。 首先是需求分析。在南通网站制作的初期阶段&#xff0c;需要和客…

SpringCloud Alibaba Sentinel网关流量控制实践总结

官网地址&#xff1a;https://sentinelguard.io/zh-cn/docs/api-gateway-flow-control.html GitHub地址&#xff1a;GitHub Sentinel 网关限流 【1】概述 Sentinel 支持对 Spring Cloud Gateway、Zuul 等主流的 API Gateway 进行限流。 Sentinel 1.6.0 引入了 Sentinel API …

QFileDialog的简单了解

ps&#xff1a;写了点垃圾&#xff08;哈哈哈&#xff09; 现在感觉Qt库应该是调用了Windows提供的这块的接口了。 它继承自QDialog 这是Windows自己的文件夹 这是两者的对比图&#xff1a; 通过看QFileDialog的源码&#xff0c;来分析它是怎么实现这样的效果的。 源码组成…

探索Java网络编程精髓:UDP与TCP的实战魔法!

Java 中提供了专门的网络编程程序包 java.net&#xff0c;提供了两种通信协议&#xff1a;UDP&#xff08;数据报协议&#xff09;和 TCP&#xff08;传输控制协议&#xff09;&#xff0c;本文对两种通信协议的开发进行详细介绍。 1 UDP 介绍 UDP&#xff1a;User Datagram Pr…

node-gyp 重新安装,解决编译遇到的问题【超详细图解】

一、报错信息 npm ERR! gyp info it worked if it ends with ok npm ERR! gyp info using node-gyp10.0.1 npm ERR! gyp info using node18.19.0 | darwin | arm64 npm ERR! gyp info find Python using Python version 3.12.2 found at "/opt/homebrew/opt/python3.12/…

3D工艺大师快速生成装配动画,驱动汽车工业装配流程革新

在现代制造业的一般生产流程中&#xff0c;车间装配环节是产品由蓝图迈向市场前至关重要的一道工序。随着产品结构的日益复杂化和个性化需求的不断增长&#xff0c;车间装配工作面临着前所未有的挑战。高精密度的装配要求、错综复杂的组件关系以及频繁变更的生产计划&#xff0…

《代理选择与反爬虫策略探究:如何优化网络爬虫效率与稳定性》

代理IP如何选以及常见反爬策略 为什么需要代理&#xff1f; 因为有的网站会封IP&#xff0c;用户如果没有登录&#xff0c;那IP就是身份标识&#xff0c;如果网站发现用户行为异常就非常可能封IP 什么是代理IP 就是让一个人帮你转交请求&#xff0c;帮你转交的人对面不熟&a…

华为OD机试 - 堆内存申请(Java 2024 D卷 100分)

华为OD机试 2024D卷题库疯狂收录中&#xff0c;刷题点这里 专栏导读 本专栏收录于《华为OD机试&#xff08;JAVA&#xff09;真题&#xff08;D卷C卷A卷B卷&#xff09;》。 刷的越多&#xff0c;抽中的概率越大&#xff0c;每一题都有详细的答题思路、详细的代码注释、样例测…

VMware安装Ubuntu以及利用vscode远程Ubuntu

一、VMware安装Ubuntu &#xff08;1&#xff09;VMware安装Ubuntu主要参考此文VMware虚拟机安装Ubuntu22.04图文教程&#xff08;超详细&#xff01;&#xff01;&#xff01;&#xff09;。 &#xff08;2&#xff09;VMware密钥参考此文24年VMware 17密钥(附下载链接&#…

【经典面试题】是否形成有环链表

1.环形链表oj 2. oj解法 利用快慢指针&#xff1a; /*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/typedef struct ListNode ListNode; bool hasCycle(struct ListNode *head) {ListNode* slow head, *fast…

M J更改图像生成方式的参数选项

一个完整的/imagine命令可能包含几个内容,例如图像 URL、图像权重、算法版本和其他开关。 /imagine参数应遵循以下顺序: /imagine prompt: https://example/tulip.jpg a field of tulips in the style of Mary Blair --no farms --iw .5 --ar 3:2 在这种情况下,“开关”是指…

SpringBoot使用Redisson操作Redis及使用场景实战

前言 在SpringBoot使用RedisTemplate、StringRedisTemplate操作Redis中&#xff0c;我们介绍了RedisTemplate以及如何SpringBoot如何通过RedisTemplate、StringRedisTemplate操作Redis。 RedisTemplate的好处就是基于SpringBoot自动装配的原理&#xff0c;使得整合redis时比较…