【光电智造】YOLOv12入门教程

今日光电 2025-03-09 20:08

今日光电


     有人说,20世纪是电的世纪,21世纪是光的世纪;知光解电,再小的个体都可以被赋能。追光逐电,光引未来...欢迎来到今日光电!


----追光逐电 光引未来----

长期以来,增强YOLO框架的网络架构一直至关重要,但一直专注于基于cnn的改进,尽管注意力机制在建模能力方面已被证明具有优越性。这是因为基于注意力的模型无法匹配基于cnn的模型的速度。本文提出了一种以注意力为中心的YOLO框架,即YOLOv12,与之前基于cnn的YOLO框架的速度相匹配,同时利用了注意力机制的性能优势。YOLOv12在精度和速度方面超越了所有流行的实时目标检测器。例如,YOLOv12-N在T4 GPU上以1.64ms的推理延迟实现了40.6% mAP,以相当的速度超过了高级的YOLOv10-N / YOLOv11-N 2.1%/1.2% mAP。这种优势可以扩展到其他模型规模。YOLOv12还超越了改善DETR的端到端实时检测器,如RT-DETR /RT-DETRv2: YOLOv12- s比RT-DETR- r18 / RT-DETRv2-r18运行更快42%,仅使用36%的计算和45%的参数。

总结:作者围提出YOLOv12目标检测模型,测试结果更快、更强,围绕注意力机制进行创新。

一、创新点总结

        作者构建了一个以注意力为核心构建了YOLOv12检测模型,主要创新点创新点如下:

        1、提出一种简单有效的区域注意力机制(area-attention)。

        2、提出一种高效的聚合网络结构R-ELAN。

        作者提出的area-attention代码如下:

class AAttn(nn.Module):    """    Area-attention module with the requirement of flash attention.    Attributes:        dim (int): Number of hidden channels;        num_heads (int): Number of heads into which the attention mechanism is divided;        area (int, optional): Number of areas the feature map is divided. Defaults to 1.    Methods:        forward: Performs a forward process of input tensor and outputs a tensor after the execution of the area attention mechanism.    Examples:        >>> import torch        >>> from ultralytics.nn.modules import AAttn        >>> model = AAttn(dim=64, num_heads=2, area=4)        >>> x = torch.randn(2, 64, 128, 128)        >>> output = model(x)        >>> print(output.shape)
    Notes:         recommend that dim//num_heads be a multiple of 32 or 64.    """
    def __init__(self, dim, num_heads, area=1):        """Initializes the area-attention module, a simple yet efficient attention module for YOLO."""        super().__init__()        self.area = area
        self.num_heads = num_heads        self.head_dim = head_dim = dim // num_heads        all_head_dim = head_dim * self.num_heads
        self.qkv = Conv(dim, all_head_dim * 31, act=False)        self.proj = Conv(all_head_dim, dim, 1, act=False)        self.pe = Conv(all_head_dim, dim, 713, g=dim, act=False)

    def forward(self, x):        """Processes the input tensor 'x' through the area-attention"""        B, C, H, W = x.shape        N = H * W
        qkv = self.qkv(x).flatten(2).transpose(12)        if self.area > 1:            qkv = qkv.reshape(B * self.area, N // self.area, C * 3)            B, N, _ = qkv.shape        q, k, v = qkv.view(B, N, self.num_heads, self.head_dim * 3).split(            [self.head_dim, self.head_dim, self.head_dim], dim=3        )
        # if x.is_cuda:        #     x = flash_attn_func(        #         q.contiguous().half(),        #         k.contiguous().half(),        #         v.contiguous().half()        #     ).to(q.dtype)        # else:        q = q.permute(0231)        k = k.permute(0231)        v = v.permute(0231)        attn = (q.transpose(-2, -1) @ k) * (self.head_dim ** -0.5)        max_attn = attn.max(dim=-1, keepdim=True).values        exp_attn = torch.exp(attn - max_attn)        attn = exp_attn / exp_attn.sum(dim=-1, keepdim=True)        x = (v @ attn.transpose(-2, -1))        x = x.permute(0312)        v = v.permute(0312)
        if self.area > 1:            x = x.reshape(B // self.area, N * self.area, C)            v = v.reshape(B // self.area, N * self.area, C)            B, N, _ = x.shape
        x = x.reshape(B, H, W, C).permute(0312)        v = v.reshape(B, H, W, C).permute(0312)
        x = x + self.pe(v)        x = self.proj(x)        return x


 结构上与YOLOv11里C2PSA中的模式相似,使用了Flash-attn进行运算加速。Flash-attn安装时需要找到与cuda、torch和python解释器对应的版本,Windows用户可用上述代码替换官方代码的AAttn代码,无需安装Flash-attn。

 R-ELAN结构如下图所示:

图片


作者基于该结构构建了A2C2f模块,与C2f/C3K2模块结构类似,代码如下:


class AAttn(nn.Module):    """    Area-attention module with the requirement of flash attention.    Attributes:        dim (int): Number of hidden channels;        num_heads (int): Number of heads into which the attention mechanism is divided;        area (int, optional): Number of areas the feature map is divided. Defaults to 1.    Methods:        forward: Performs a forward process of input tensor and outputs a tensor after the execution of the area attention mechanism.    Examples:        >>> import torch        >>> from ultralytics.nn.modules import AAttn        >>> model = AAttn(dim=64, num_heads=2, area=4)        >>> x = torch.randn(2, 64, 128, 128)        >>> output = model(x)        >>> print(output.shape)
    Notes:         recommend that dim//num_heads be a multiple of 32 or 64.    """
    def __init__(self, dim, num_heads, area=1):        """Initializes the area-attention module, a simple yet efficient attention module for YOLO."""        super().__init__()        self.area = area
        self.num_heads = num_heads        self.head_dim = head_dim = dim // num_heads        all_head_dim = head_dim * self.num_heads
        self.qkv = Conv(dim, all_head_dim * 31, act=False)        self.proj = Conv(all_head_dim, dim, 1, act=False)        self.pe = Conv(all_head_dim, dim, 713, g=dim, act=False)

    def forward(self, x):        """Processes the input tensor 'x' through the area-attention"""        B, C, H, W = x.shape        N = H * W
        qkv = self.qkv(x).flatten(2).transpose(12)        if self.area > 1:            qkv = qkv.reshape(B * self.area, N // self.area, C * 3)            B, N, _ = qkv.shape        q, k, v = qkv.view(B, N, self.num_heads, self.head_dim * 3).split(            [self.head_dim, self.head_dim, self.head_dim], dim=3        )
        # if x.is_cuda:        #     x = flash_attn_func(        #         q.contiguous().half(),        #         k.contiguous().half(),        #         v.contiguous().half()        #     ).to(q.dtype)        # else:        q = q.permute(0231)        k = k.permute(0231)        v = v.permute(0231)        attn = (q.transpose(-2, -1) @ k) * (self.head_dim ** -0.5)        max_attn = attn.max(dim=-1, keepdim=True).values        exp_attn = torch.exp(attn - max_attn)        attn = exp_attn / exp_attn.sum(dim=-1, keepdim=True)        x = (v @ attn.transpose(-2, -1))        x = x.permute(0312)        v = v.permute(0312)
        if self.area > 1:            x = x.reshape(B // self.area, N * self.area, C)            v = v.reshape(B // self.area, N * self.area, C)            B, N, _ = x.shape
        x = x.reshape(B, H, W, C).permute(0312)        v = v.reshape(B, H, W, C).permute(0312)
        x = x + self.pe(v)        x = self.proj(x)        return x

class ABlock(nn.Module):    """    ABlock class implementing a Area-Attention block with effective feature extraction.    This class encapsulates the functionality for applying multi-head attention with feature map are dividing into areas    and feed-forward neural network layers.    Attributes:        dim (int): Number of hidden channels;        num_heads (int): Number of heads into which the attention mechanism is divided;        mlp_ratio (float, optional): MLP expansion ratio (or MLP hidden dimension ratio). Defaults to 1.2;        area (int, optional): Number of areas the feature map is divided.  Defaults to 1.    Methods:        forward: Performs a forward pass through the ABlock, applying area-attention and feed-forward layers.    Examples:        Create a ABlock and perform a forward pass        >>> model = ABlock(dim=64, num_heads=2, mlp_ratio=1.2, area=4)        >>> x = torch.randn(2, 64, 128, 128)        >>> output = model(x)        >>> print(output.shape)
    Notes:         recommend that dim//num_heads be a multiple of 32 or 64.    """
    def __init__(self, dim, num_heads, mlp_ratio=1.2, area=1):        """Initializes the ABlock with area-attention and feed-forward layers for faster feature extraction."""        super().__init__()
        self.attn = AAttn(dim, num_heads=num_heads, area=area)        mlp_hidden_dim = int(dim * mlp_ratio)        self.mlp = nn.Sequential(Conv(dim, mlp_hidden_dim, 1), Conv(mlp_hidden_dim, dim, 1, act=False))
        self.apply(self._init_weights)
    def _init_weights(self, m):        """Initialize weights using a truncated normal distribution."""        if isinstance(m, nn.Conv2d):            trunc_normal_(m.weight, std=.02)            if isinstance(m, nn.Conv2d) and m.bias is not None:                nn.init.constant_(m.bias, 0)
    def forward(self, x):        """Executes a forward pass through ABlock, applying area-attention and feed-forward layers to the input tensor."""        x = x + self.attn(x)        x = x + self.mlp(x)        return x

class A2C2f(nn.Module):      """    A2C2f module with residual enhanced feature extraction using ABlock blocks with area-attention. Also known as R-ELAN    This class extends the C2f module by incorporating ABlock blocks for fast attention mechanisms and feature extraction.    Attributes:        c1 (int): Number of input channels;        c2 (int): Number of output channels;        n (int, optional): Number of 2xABlock modules to stack. Defaults to 1;        a2 (bool, optional): Whether use area-attention. Defaults to True;        area (int, optional): Number of areas the feature map is divided. Defaults to 1;        residual (bool, optional): Whether use the residual (with layer scale). Defaults to False;        mlp_ratio (float, optional): MLP expansion ratio (or MLP hidden dimension ratio). Defaults to 1.2;        e (float, optional): Expansion ratio for R-ELAN modules. Defaults to 0.5.        g (int, optional): Number of groups for grouped convolution. Defaults to 1;        shortcut (bool, optional): Whether to use shortcut connection. Defaults to True;    Methods:        forward: Performs a forward pass through the A2C2f module.    Examples:        >>> import torch        >>> from ultralytics.nn.modules import A2C2f        >>> model = A2C2f(c1=64, c2=64, n=2, a2=True, area=4, residual=True, e=0.5)        >>> x = torch.randn(2, 64, 128, 128)        >>> output = model(x)        >>> print(output.shape)    """
    def __init__(self, c1, c2, n=1, a2=True, area=1, residual=False, mlp_ratio=2.0, e=0.5, g=1, shortcut=True):        super().__init__()        c_ = int(c2 * e)  # hidden channels        assert c_ % 32 == 0"Dimension of ABlock be a multiple of 32."
        # num_heads = c_ // 64 if c_ // 64 >= 2 else c_ // 32        num_heads = c_ // 32
        self.cv1 = Conv(c1, c_, 11)        self.cv2 = Conv((1 + n) * c_, c2, 1)  # optional act=FReLU(c2)
        init_values = 0.01  # or smaller        self.gamma = nn.Parameter(init_values * torch.ones((c2)), requires_grad=Trueif a2 and residual else None
        self.m = nn.ModuleList(            nn.Sequential(*(ABlock(c_, num_heads, mlp_ratio, area) for _ in range(2))) if a2 else C3k(c_, c_, 2, shortcut, g) for _ in range(n)        )
    def forward(self, x):        """Forward pass through R-ELAN layer."""        y = [self.cv1(x)]        y.extend(m(y[-1]) for m in self.m)        if self.gamma is not None:            return x + (self.gamma * self.cv2(torch.cat(y, 1)).permute(0231)).permute(0312)        return self.cv2(torch.cat(y, 1))

模型结构图如下:

图片

二、使用教程

2.1 准备代码

         首先,点击上方链接进入YOLOv12的GitHub仓库,按照图示流程下载打包好的YOLOv12代码与预训练权重文件到本地。

图片

        下载完成后解压, 使用PyCharm(或VsCode等IDE软件)打开,并将下载的预训练权重拷贝到解压的工程目录下,下文以PyCharm为例。

图片


2.2 准备数据集 

        Ultralytics版本的YOLO所需格式的数据集标签为txt格式的文本文件,文本文件中保存的标签信息分别为:类别序号、中心点x/y坐标、标注框的归一化信息,每一行对应一个对象。图像中有几个标注的对象就有几行信息。

图片
自制数据集标注教程可看此篇文章:
https://blog.csdn.net/StopAndGoyyy/article/details/139906637
如果没有自己的数据集,本文提供一个小型数据集(摘自SIMD公共数据集)以供测试代码,包含24张训练集以及20张测试集

下载链接:https://pan.quark.cn/s/f318a977f81c

提取码:LQ68

下载完成后将提供的datasets文件夹解压并复制到工程路径下。
图片

创建 data.yaml文件保存数据集的相关信息,如果使用本文提供的数据集可使用以下代码:

图片

 # dataset pathtrain: ./images/trainval: ./images/testtest: ./images/test
# number of classesnc: 15
# class namesnames: ['car''Truck''Van''Long Vehicle','Bus''Airliner''Propeller Aircraft''Trainer Aircraft''Chartered Aircraft''Fighter Aircraft',\        'Others''Stair Truck''Pushback Truck''Helicopter''Boat']

2.3 模型训练

        创建train.py文件,依次填入以下信息。epochs=2表示只训练两轮,通常设置为100-300之间,此处仅测试两轮。batch=1表示每批次仅训练一张图片,可按显存大小调整batchsize,一般24g卡可设置为16-64。

图片

from ultralytics.models import YOLOimport osos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
if __name__ == '__main__':    model = YOLO(model='ultralytics/cfg/models/11/yolo11.yaml')    # model.load('yolov8n.pt')    model.train(data='./data.yaml', epochs=2, batch=1, device='0', imgsz=640, workers=2, cache=False,                amp=True, mosaic=False, project='runs/train', name='exp')

图片

图片

待软件控制台打印如下信息即为运行成功。如果Flash_attn包报错,可使用本文的A2代码对原文代码进行更改。

图片

         训练完成后在runs/train文件夹下保存有训练好的权重及相关训练信息。 图片

2.4 模型预测

        创建detect.py文件,填入训练好的权重路径及要检测的图片信息。

图片

三、小结

       浅谈一下YOLOv12的感受,相比前几代的YOLO,v12的改动较小,在结构上删除了SPPF模块,设计了A2C2f模块,在模型的几个位置进行了替换。从作者公布的实验数据来看,模型的计算量和参数量都有一定下降,同时检测性能有一定提升。也不得不感慨,YOLO更新换代的速度越来越快了。要说YOLO那个版本强,那当然是最新的最强。

本文仅用于学术分享,如有侵权,请联系后台作删文处理论文链接:https://arxiv.org/abs/2502.12524

代码链接:https://github.com/sunsmarterjie/yolov12
来源:新机器视觉


申明:感谢原创作者的辛勤付出。本号转载的文章均会在文中注明,若遇到版权问题请联系我们处理。



----与智者为伍 为创新赋能----


【说明】欢迎企业和个人洽谈合作,投稿发文。欢迎联系我们
诚招运营合伙人 ,对新媒体感兴趣,对光电产业和行业感兴趣。非常有意者通过以下方式联我们!条件待遇面谈
投稿丨合作丨咨询

联系邮箱:uestcwxd@126.com

QQ:493826566



评论 (0)
  •   定制软件开发公司推荐清单   在企业数字化转型加速的2025年,定制软件开发需求愈发多元复杂。不同行业、技术偏好与服务模式的企业,对开发公司的要求大相径庭。以下从技术赛道、服务模式及行业场景出发,为您提供适配的定制软件开发公司推荐及选择建议。   华盛恒辉科技有限公司:是一家专注于高端软件定制开发服务和高端建设的服务机构,致力于为企业提供全面、系统的开发制作方案。在部队政企开发、建设到运营推广领域拥有丰富经验,在教育,工业,医疗,APP,管理,商城,人工智能,部队软件、工业软件、数字化转
    华盛恒辉l58ll334744 2025-05-12 15:55 328浏览
  •   舰艇电磁兼容分析与整改系统平台解析   北京华盛恒辉舰艇电磁兼容分析与整改系统平台是保障海军装备作战效能的关键技术,旨在确保舰艇电子设备在复杂电磁环境中协同运行。本文从架构、技术、流程、价值及趋势五个维度展开解析。   应用案例   目前,已有多个舰艇电磁兼容分析与整改系统在实际应用中取得了显著成效。例如,北京华盛恒辉和北京五木恒润舰艇电磁兼容分析与整改系统。这些成功案例为舰艇电磁兼容分析与整改系统的推广和应用提供了有力支持。   一、系统架构:模块化智能体系   电磁环境建模:基
    华盛恒辉l58ll334744 2025-05-14 11:22 45浏览
  •   电磁数据管理系统深度解析   北京华盛恒辉电磁数据管理系统作为专业的数据处理平台,旨在提升电磁数据的处理效率、安全性与可靠性。以下从功能架构、核心特性、应用场景及技术实现展开分析:   应用案例   目前,已有多个电磁数据管理系统在实际应用中取得了显著成效。例如,北京华盛恒辉和北京五木恒润电磁数据管理系统。这些成功案例为电磁数据管理系统的推广和应用提供了有力支持。   一、核心功能模块   数据采集与接入:实时接收天线、频谱仪等设备数据,兼容多协议接口,确保数据采集的全面性与实时性
    华盛恒辉l58ll334744 2025-05-13 10:59 266浏览
  • 文/Leon编辑/cc孙聪颖‍2025年1月至今,AI领域最出圈的除了DeepSeek,就是号称首个“通用AI Agent”(智能体)的Manus了,其邀请码一度被炒到8万元。很快,通用Agent就成为互联网大厂、AI独角兽们的新方向,迅速地“卷”了起来。国外市场,Open AI、Claude、微软等迅速推出Agent产品或构建平台,国内企业也在4月迅速跟进。4月,字节跳动、阿里巴巴、百度纷纷入局通用Agent市场,主打复杂的多任务、工作流功能,并对个人用户免费。腾讯则迅速更新腾讯元器的API接
    华尔街科技眼 2025-05-12 22:29 145浏览
  •   电磁数据展示系统平台解析   北京华盛恒辉电磁数据展示系统平台是实现电磁数据高效展示、分析与管理的综合性软件体系,以下从核心功能、技术特性、应用场景及发展趋势展开解读:   应用案例   目前,已有多个电磁数据展示系统在实际应用中取得了显著成效。例如,北京华盛恒辉和北京五木恒润电磁数据展示系统。这些成功案例为电磁数据展示系统的推广和应用提供了有力支持。   一、核心功能模块   数据采集与预处理   智能分析处理   集成频谱分析、时频变换等信号处理算法,自动提取时域频域特征;
    华盛恒辉l58ll334744 2025-05-13 10:20 355浏览
  • 在全球供应链紧张和国产替代需求推动下,国产存储芯片产业快速发展,形成设计到封测一体化的完整生态。北京君正、兆易创新、紫光国芯、东芯股份、普冉股份和佰维存储等六大上市公司在NOR/NAND Flash、DRAM、嵌入式存储等领域布局各具特色,推动国产替代提速。贞光科技代理的品牌紫光国芯,专注DRAM技术,覆盖嵌入式存储与模组解决方案,为多领域客户提供高可靠性产品。随着AI、5G等新兴应用兴起,国产存储厂商有望迎来新一轮增长。存储芯片分类与应用易失性与非易失性存储芯片易失性存储芯片(Volatile
    贞光科技 2025-05-12 16:05 196浏览
  • 在印度与巴基斯坦的军事对峙情境下,歼10C的出色表现如同一颗投入平静湖面的巨石,激起层层涟漪,深刻印证了“质量大于数量”这一铁律。军事领域,技术优势就是决定胜负的关键钥匙。歼10C凭借先进的航电系统、强大的武器挂载能力以及卓越的机动性能,在战场上大放异彩。它能够精准捕捉目标,迅速发动攻击,以一敌多却毫不逊色。与之形成鲜明对比的是,单纯依靠数量堆砌的军事力量,在面对先进技术装备时,往往显得力不从心。这一现象绝非局限于军事范畴,在当今社会的各个领域,“质量大于数量”都已成为不可逆转的趋势。在科技行业
    curton 2025-05-11 19:09 255浏览
  • 在当下竞争激烈的 AI 赛道,企业高层的变动往往牵一发而动全身,零一万物近来就深陷这样的动荡漩涡。近日,零一万物联合创始人、技术副总裁戴宗宏离职创业的消息不胫而走。这位在大模型基础设施领域造诣颇深的专家,此前在华为云、阿里达摩院积累了深厚经验,在零一万物时更是带领团队短期内完成了千卡 GPU 集群等关键设施搭建,其离去无疑是重大损失。而这并非个例,自 2024 年下半年以来,李先刚、黄文灏、潘欣、曹大鹏等一众联创和早期核心成员纷纷出走。
    用户1742991715177 2025-05-13 21:24 97浏览
  • ‌磁光克尔效应(Magneto-Optic Kerr Effect, MOKE)‌ 是指当线偏振光入射到磁性材料表面并反射后,其偏振状态(偏振面旋转角度和椭偏率)因材料的磁化强度或方向发生改变的现象。具体表现为:1、‌偏振面旋转‌:反射光的偏振方向相对于入射光发生偏转(克尔旋转角 θK)。2、‌椭偏率变化‌:反射光由线偏振变为椭圆偏振(克尔椭偏率 εK)。这一效应直接关联材料的磁化状态,是表征磁性材料(如铁磁体、反铁磁体)磁学性质的重要非接触式光学探测手段,广泛用于
    锦正茂科技 2025-05-12 11:02 297浏览
  • 感谢面包板论坛组织的本次测评活动,本次测评的对象是STM32WL Nucleo-64板 (NUCLEO-WL55JC) ,该测试板专为LoRa™应用原型构建,基于STM32WL系列sub-GHz无线微控制器。其性能、功耗及特性组合经过精心挑选,支持通过Arduino® Uno V3连接,并利用ST morpho接头扩展STM32WL Nucleo功能,便于访问多种专用屏蔽。STM32WL Nucleo-64板集成STLINK-V3E调试器与编程器,无需额外探测器。该板配备全面的STM
    无言的朝圣 2025-05-13 09:47 142浏览
  • 在 AI 浪潮席卷下,厨电行业正经历着深刻变革。AWE 2025期间,万得厨对外首次发布了wan AiOS 1.0组织体超智能系统——通过AI技术能够帮助全球家庭实现从健康检测、膳食推荐,到食材即时配送,再到一步烹饪、营养总结的个性化健康膳食管理。这一创新之举并非偶然的个案,而是整个厨电行业大步迈向智能化、数字化转型浪潮的一个关键注脚,折射出全行业对 AI 赋能的热切渴求。前有标兵后有追兵,万得厨面临着高昂的研发成本与技术迭代压力,稍有懈怠便可能被后来者赶
    用户1742991715177 2025-05-11 22:44 177浏览
  •   基于 2025 年行业权威性与时效性,以下梳理国内知名软件定制开发企业,涵盖综合型、垂直领域及特色技术服务商:   华盛恒辉科技有限公司:是一家专注于高端软件定制开发服务和高端建设的服务机构,致力于为企业提供全面、系统的开发制作方案。在部队政企开发、建设到运营推广领域拥有丰富经验,在教育,工业,医疗,APP,管理,商城,人工智能,部队软件、工业软件、数字化转型、新能源软件、光伏软件、汽车软件,ERP,系统二次开发,CRM等领域有很多成功案例。   五木恒润科技有限公司:是一家专业的部队信
    华盛恒辉l58ll334744 2025-05-12 16:13 250浏览
我要评论
0
0
点击右上角,分享到朋友圈 我知道啦
请使用浏览器分享功能 我知道啦