欢迎光临
我们一直在努力

Ultralytics:解读C3Ghost模块

Ultralytics:解读C3Ghost模块

  • 前言
  • 相关介绍
    • Ultralytics 简介
  • 前提条件
  • 实验环境
  • C3Ghost(C3 模块 + GhostBottleneck)
      • 代码实现
      • 功能
      • 初始化参数
      • 前向方法
      • 使用示例
      • 流程示意图
      • 代码解读
      • 注意事项
      • 优缺点
        • 优点
        • 缺点
  • 参考文献

在这里插入图片描述

前言

  • 由于本人水平有限,难免出现错漏,敬请批评改正。
  • 更多精彩内容,可点击进入Python日常小操作专栏、OpenCV-Python小应用专栏、YOLO系列专栏、自然语言处理专栏、人工智能混合编程实践专栏或我的个人主页查看
  • YOLOs-CPP:一个免费开源的YOLO全系列C++推理库(以YOLO26为例)
  • PaddleOCR:Win10上安装使用PPOCRLabel标注工具
  • 目标检测:使用自己的数据集微调DEIMv2进行物体检测
  • 图像分割:PyTorch从零开始实现SegFormer语义分割
  • 图像超分:使用自己的数据集微调Real-ESRGAN-x4plus进行超分重建
  • 图像生成:PyTorch从零开始实现一个简单的扩散模型
  • Stable Diffusion:使用自己的数据集微调 Stable Diffusion 3.5 LoRA 文生图模型
  • 图像超分:使用自己的数据集微调Real-ESRGAN-x2plus进行超分重建
  • Anomalib:使用Anomalib 2.1.0训练自己的数据集进行异常检测
  • Anomalib:在Linux服务器上安装使用Anomalib 2.1.0
  • 人工智能混合编程实践:C++调用封装好的DLL进行异常检测推理
  • 人工智能混合编程实践:C++调用封装好的DLL进行FP16图像超分重建(v3.0)
  • 隔离系统Python:源码编译3.11.8到自定义目录(含PGO性能优化)
  • 在线机的Python环境迁移到离线机上
  • Nuitka 将 Python 脚本封装为 .pyd 或 .so 文件
  • Ultralytics:使用 YOLO11 进行速度估计
  • Ultralytics:使用 YOLO11 进行物体追踪
  • Ultralytics:使用 YOLO11 进行物体计数
  • Ultralytics:使用 YOLO11 进行目标打码
  • 人工智能混合编程实践:C++调用Python ONNX进行YOLOv8推理
  • 人工智能混合编程实践:C++调用封装好的DLL进行YOLOv8实例分割
  • 人工智能混合编程实践:C++调用Python ONNX进行图像超分重建
  • 人工智能混合编程实践:C++调用Python AgentOCR进行文本识别
  • 通过计算实例简单地理解PatchCore异常检测
  • Python将YOLO格式实例分割数据集转换为COCO格式实例分割数据集
  • YOLOv8 Ultralytics:使用Ultralytics框架训练RT-DETR实时目标检测模型
  • 基于DETR的人脸伪装检测
  • YOLOv7训练自己的数据集(口罩检测)
  • YOLOv8训练自己的数据集(足球检测)
  • YOLOv5:TensorRT加速YOLOv5模型推理
  • YOLOv5:IoU、GIoU、DIoU、CIoU、EIoU
  • 玩转Jetson Nano(五):TensorRT加速YOLOv5目标检测
  • YOLOv5:添加SE、CBAM、CoordAtt、ECA注意力机制
  • YOLOv5:yolov5s.yaml配置文件解读、增加小目标检测层
  • Python将COCO格式实例分割数据集转换为YOLO格式实例分割数据集
  • YOLOv5:使用7.0版本训练自己的实例分割模型(车辆、行人、路标、车道线等实例分割)
  • 使用Kaggle GPU资源免费体验Stable Diffusion开源项目
  • Stable Diffusion:在服务器上部署使用Stable Diffusion WebUI进行AI绘图(v2.0)
  • Stable Diffusion:使用自己的数据集微调训练LoRA模型(v2.0)

相关介绍

Ultralytics 简介

Ultralytics 基于多年的计算机视觉和人工智能基础研究,创建了最先进的 (SOTA) YOLO 模型。我们的模型不断更新性能和灵活性,快速、准确且易于使用。他们擅长对象检测、跟踪、实例分割、语义分割、图像分类和姿势估计任务。

  • 官方文档:https://docs.ultralytics.com/
  • 官方代码:https://github.com/ultralytics/ultralytics.git

前提条件

  • 熟悉Python、Pytorch

实验环境

Package Version
———————— ————
Python 3.11.8
absl-py 2.4.0
accelerate 1.13.0
annotated-doc 0.0.4
anyio 4.13.0
calflops 0.3.2
certifi 2026.4.22
charset-normalizer 3.4.7
click 8.3.3
colorama 0.4.6
contourpy 1.3.3
cycler 0.12.1
filelock 3.29.0
flatbuffers 25.12.19
fonttools 4.62.1
fsspec 2026.4.0
grpcio 1.80.0
h11 0.16.0
hf-xet 1.5.0
httpcore 1.0.9
httpx 0.28.1
huggingface_hub 1.14.0
idna 3.15
Jinja2 3.1.6
kiwisolver 1.5.0
Markdown 3.10.2
markdown-it-py 4.2.0
MarkupSafe 3.0.3
matplotlib 3.10.9
mdurl 0.1.2
ml_dtypes 0.5.0
mpmath 1.3.0
networkx 3.6.1
numpy 1.26.4
nvidia-cublas-cu12 12.8.3.14
nvidia-cuda-cupti-cu12 12.8.57
nvidia-cuda-nvrtc-cu12 12.8.61
nvidia-cuda-runtime-cu12 12.8.57
nvidia-cudnn-cu12 9.7.1.26
nvidia-cufft-cu12 11.3.3.41
nvidia-cufile-cu12 1.13.0.11
nvidia-curand-cu12 10.3.9.55
nvidia-cusolver-cu12 11.7.2.55
nvidia-cusparse-cu12 12.5.7.53
nvidia-cusparselt-cu12 0.6.3
nvidia-nccl-cu12 2.26.2
nvidia-nvjitlink-cu12 12.8.61
nvidia-nvtx-cu12 12.8.55
onnx 1.19.0
onnxruntime-gpu 1.26.0
onnxslim 0.1.94
opencv-python 4.6.0.66
packaging 26.2
pillow 12.2.0
pip 24.0
polars 1.40.1
polars-runtime-32 1.40.1
protobuf 7.34.1
psutil 7.2.2
pycocotools 2.0.11
Pygments 2.20.0
pyparsing 3.3.2
python-dateutil 2.9.0.post0
PyYAML 6.0.3
regex 2026.5.9
requests 2.34.1
rich 15.0.0
safetensors 0.7.0
scipy 1.16.0
setuptools 65.5.0
shellingham 1.5.4
six 1.17.0
sympy 1.14.0
tabulate 0.10.0
tensorboard 2.20.0
tensorboard-data-server 0.7.2
tokenizers 0.22.2
torch 2.7.1+cu128
torchaudio 2.7.1+cu128
torchvision 0.22.1+cu128
tqdm 4.67.3
transformers 5.8.1
triton 3.3.1
typer 0.25.1
typing_extensions 4.15.0
ultralytics 8.4.58
ultralytics-thop 2.0.19
urllib3 2.7.0
Werkzeug 3.1.8

C3Ghost(C3 模块 + GhostBottleneck)

C3Ghost 是 C3 模块的轻量化变体,它将内部的 Bottleneck 块替换为 GhostBottleneck,从而在保持 CSP 结构的同时,利用 Ghost 模块和深度卷积大幅降低参数量和计算量。该模块适用于移动端或边缘设备上的目标检测网络(如 YOLOv5‑Ghost),在精度和速度之间取得了良好的平衡。


代码实现

import cv2
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt

def autopad(k, p=None, d=1): # kernel, padding, dilation
"""Pad to 'same' shape outputs."""
if d > 1:
k = d * (k 1) + 1 if isinstance(k, int) else [d * (x 1) + 1 for x in k] # actual kernel-size
if p is None:
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
return p

class Conv(nn.Module):
"""Standard convolution module with batch normalization and activation.

Attributes:
conv (nn.Conv2d): Convolutional layer.
bn (nn.BatchNorm2d): Batch normalization layer.
act (nn.Module): Activation function layer.
default_act (nn.Module): Default activation function (SiLU).
"""

default_act = nn.SiLU() # default activation

def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):
"""Initialize Conv layer with given parameters.

Args:
c1 (int): Number of input channels.
c2 (int): Number of output channels.
k (int): Kernel size.
s (int): Stride.
p (int, optional): Padding.
g (int): Groups.
d (int): Dilation.
act (bool | nn.Module): Activation function.
"""
super().__init__()
self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)
self.bn = nn.BatchNorm2d(c2)
self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()

def forward(self, x):
"""Apply convolution, batch normalization and activation to input tensor.

Args:
x (torch.Tensor): Input tensor.

Returns:
(torch.Tensor): Output tensor.
"""
return self.act(self.bn(self.conv(x)))

def forward_fuse(self, x):
"""Apply convolution and activation without batch normalization.

Args:
x (torch.Tensor): Input tensor.

Returns:
(torch.Tensor): Output tensor.
"""
return self.act(self.conv(x))

class GhostConv(nn.Module):
"""Ghost Convolution module.

Generates more features with fewer parameters by using cheap operations.

Attributes:
cv1 (Conv): Primary convolution.
cv2 (Conv): Cheap operation convolution.

References:
https://github.com/huawei-noah/Efficient-AI-Backbones
"""

def __init__(self, c1, c2, k=1, s=1, g=1, act=True):
"""Initialize Ghost Convolution module with given parameters.

Args:
c1 (int): Number of input channels.
c2 (int): Number of output channels.
k (int): Kernel size.
s (int): Stride.
g (int): Groups.
act (bool | nn.Module): Activation function.
"""
super().__init__()
c_ = c2 // 2 # hidden channels
self.cv1 = Conv(c1, c_, k, s, None, g, act=act)
self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)

def forward(self, x):
"""Apply Ghost Convolution to input tensor.

Args:
x (torch.Tensor): Input tensor.

Returns:
(torch.Tensor): Output tensor with concatenated features.
"""
y = self.cv1(x)
return torch.cat((y, self.cv2(y)), 1)

class DWConv(Conv):
"""Depth-wise convolution module."""

def __init__(self, c1, c2, k=1, s=1, d=1, act=True):
"""Initialize depth-wise convolution with given parameters.

Args:
c1 (int): Number of input channels.
c2 (int): Number of output channels.
k (int): Kernel size.
s (int): Stride.
d (int): Dilation.
act (bool | nn.Module): Activation function.
"""
super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)

class GhostBottleneck(nn.Module):
"""Ghost Bottleneck https://github.com/huawei-noah/Efficient-AI-Backbones."""

def __init__(self, c1: int, c2: int, k: int = 3, s: int = 1):
"""Initialize Ghost Bottleneck module.

Args:
c1 (int): Input channels.
c2 (int): Output channels.
k (int): Kernel size.
s (int): Stride.
"""
super().__init__()
c_ = c2 // 2
self.conv = nn.Sequential(
GhostConv(c1, c_, 1, 1), # pw
DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
GhostConv(c_, c2, 1, 1, act=False), # pw-linear
)
self.shortcut = (
nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
)

def forward(self, x: torch.Tensor) > torch.Tensor:
"""Apply skip connection and addition to input tensor."""
return self.conv(x) + self.shortcut(x)

class Bottleneck(nn.Module):
"""Standard bottleneck."""

def __init__(
self, c1: int, c2: int, shortcut: bool = True, g: int = 1, k: tuple[int, int] = (3, 3), e: float = 0.5
):
"""Initialize a standard bottleneck module.

Args:
c1 (int): Input channels.
c2 (int): Output channels.
shortcut (bool): Whether to use shortcut connection.
g (int): Groups for convolutions.
k (tuple): Kernel sizes for convolutions.
e (float): Expansion ratio.
"""
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, k[0], 1)
self.cv2 = Conv(c_, c2, k[1], 1, g=g)
self.add = shortcut and c1 == c2

def forward(self, x: torch.Tensor) > torch.Tensor:
"""Apply bottleneck with optional shortcut connection."""
return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))

class C3(nn.Module):
"""CSP Bottleneck with 3 convolutions."""

def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
"""Initialize the CSP Bottleneck with 3 convolutions.

Args:
c1 (int): Input channels.
c2 (int): Output channels.
n (int): Number of Bottleneck blocks.
shortcut (bool): Whether to use shortcut connections.
g (int): Groups for convolutions.
e (float): Expansion ratio.
"""
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = Conv(c1, c_, 1, 1)
self.cv2 = Conv(c1, c_, 1, 1)
self.cv3 = Conv(2 * c_, c2, 1) # optional act=FReLU(c2)
self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))

def forward(self, x: torch.Tensor) > torch.Tensor:
"""Forward pass through the CSP bottleneck with 3 convolutions."""
return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))

class C3Ghost(C3):
"""C3 module with GhostBottleneck()."""

def __init__(self, c1: int, c2: int, n: int = 1, shortcut: bool = True, g: int = 1, e: float = 0.5):
"""Initialize C3 module with GhostBottleneck.

Args:
c1 (int): Input channels.
c2 (int): Output channels.
n (int): Number of Ghost bottleneck blocks.
shortcut (bool): Whether to use shortcut connections.
g (int): Groups for convolutions.
e (float): Expansion ratio.
"""
super().__init__(c1, c2, n, shortcut, g, e)
c_ = int(c2 * e) # hidden channels
self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))


功能

  • CSP 结构:继承自 C3,包含 cv1、cv2 两个并行的 1×1 卷积,一个 cv3 1×1 卷积用于输出压缩,以及一个 m 序列(此处被替换为 GhostBottleneck)。
  • Ghost 瓶颈:每个 GhostBottleneck 内部使用 GhostConv(生成冗余特征)和 DWConv(深度卷积),大幅降低计算量。
  • 通道配置:c_ = int(c2 * e) 决定隐藏通道数,GhostBottleneck 内部要求其输入输出通道相等(此处均为 c_),且 c_ 必须为偶数。

初始化参数

参数类型说明
c1 int 输入通道数
c2 int 输出通道数
n int GhostBottleneck 块的数量(默认 1)
shortcut bool 是否使用残差连接(注意:该参数在 C3Ghost 中实际上不起作用,因为 GhostBottleneck 未使用该参数,仅父类 C3 会用它构造 Bottleneck,但父类的 m 被覆盖)
g int 分组卷积的组数(同样被忽略,因为 GhostBottleneck 内部不使用 g)
e float 扩展比,c_ = int(c2 * e)(默认 0.5)

由于 GhostBottleneck 固定步长 s=1(未提供 s 参数),因此模块不进行下采样,仅做特征变换。


前向方法

  • forward(x):继承自 C3,输入 x,输出 [B, c2, H, W]。

数据流(与 C3 相同):

  • a = self.cv1(x) → 1×1 卷积,c1 → c_
  • b = self.cv2(x) → 1×1 卷积,c1 → c_
  • a = self.m(a) → 通过 n 个 GhostBottleneck,每个保持通道 c_
  • cat = torch.cat((a, b), dim=1) → [B, 2*c_, H, W]
  • self.cv3(cat) → 1×1 卷积,2*c_ → c2,输出。

  • 使用示例

    在这里插入图片描述

    if __name__ == '__main__':
    # 1. 随机输入
    x = torch.randn(1, 32, 64, 64)

    # 2. 创建 C3Ghost(c2=64,则 c_=32,必须为偶数)
    c3ghost = C3Ghost(c1=32, c2=64, n=2, shortcut=True, g=1, e=0.5)

    # 3. 前向传播
    with torch.no_grad():
    out = c3ghost(x)
    print("输入形状:", x.shape) # [1, 32, 64, 64]
    print("输出形状:", out.shape) # [1, 64, 64, 64]

    # 4. 使用真实图像演示(扩展为多通道)
    img_path = "cat_640x640.png"
    img_bgr = cv2.imread(img_path)
    if img_bgr is not None:
    img_gray = cv2.cvtColor(cv2.resize(img_bgr, (64, 64)), cv2.COLOR_BGR2GRAY)
    img_tensor = torch.from_numpy(img_gray).float().unsqueeze(0).unsqueeze(0) # [1,1,64,64]
    # 扩展通道至 c1=32
    x_img = img_tensor.repeat(1, 32, 1, 1)

    model_img = C3Ghost(c1=32, c2=32, n=1, e=0.5)
    with torch.no_grad():
    out_img = model_img(x_img)

    inp_ch0 = x_img[0, 0].cpu().numpy()
    out_ch0 = out_img[0, 0].cpu().numpy()

    def norm(arr):
    return (arr arr.min()) / (arr.max() arr.min() + 1e-8)

    plt.figure(figsize=(12, 5), constrained_layout=True)
    plt.subplot(1, 3, 1)
    plt.imshow(img_gray, cmap='gray')
    plt.title("Original Gray")
    plt.axis("off")
    plt.subplot(1, 3, 2)
    plt.imshow(norm(inp_ch0), cmap='gray')
    plt.title("Input Ch0")
    plt.axis("off")
    plt.subplot(1, 3, 3)
    plt.imshow(norm(out_ch0), cmap='gray')
    plt.title("C3Ghost Output Ch0")
    plt.axis("off")
    plt.savefig("c3ghost_demo.png", dpi=150)
    print("可视化已保存为 c3ghost_demo.png")

    在这里插入图片描述 输出示例:

    输入形状: torch.Size([1, 32, 64, 64])
    输出形状: torch.Size([1, 64, 64, 64])
    可视化已保存为 c3ghost_demo.png


    流程示意图

    #mermaid-svg-1zrY3YeadsXTjM7x{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-1zrY3YeadsXTjM7x .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-1zrY3YeadsXTjM7x .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-1zrY3YeadsXTjM7x .error-icon{fill:#552222;}#mermaid-svg-1zrY3YeadsXTjM7x .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-1zrY3YeadsXTjM7x .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-1zrY3YeadsXTjM7x .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-1zrY3YeadsXTjM7x .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-1zrY3YeadsXTjM7x .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-1zrY3YeadsXTjM7x .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-1zrY3YeadsXTjM7x .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-1zrY3YeadsXTjM7x .marker{fill:#333333;stroke:#333333;}#mermaid-svg-1zrY3YeadsXTjM7x .marker.cross{stroke:#333333;}#mermaid-svg-1zrY3YeadsXTjM7x svg{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-1zrY3YeadsXTjM7x p{margin:0;}#mermaid-svg-1zrY3YeadsXTjM7x .label{font-family:\”trebuchet ms\”,verdana,arial,sans-serif;color:#333;}#mermaid-svg-1zrY3YeadsXTjM7x .cluster-label text{fill:#333;}#mermaid-svg-1zrY3YeadsXTjM7x .cluster-label span{color:#333;}#mermaid-svg-1zrY3YeadsXTjM7x .cluster-label span p{background-color:transparent;}#mermaid-svg-1zrY3YeadsXTjM7x .label text,#mermaid-svg-1zrY3YeadsXTjM7x span{fill:#333;color:#333;}#mermaid-svg-1zrY3YeadsXTjM7x .node rect,#mermaid-svg-1zrY3YeadsXTjM7x .node circle,#mermaid-svg-1zrY3YeadsXTjM7x .node ellipse,#mermaid-svg-1zrY3YeadsXTjM7x .node polygon,#mermaid-svg-1zrY3YeadsXTjM7x .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-1zrY3YeadsXTjM7x .rough-node .label text,#mermaid-svg-1zrY3YeadsXTjM7x .node .label text,#mermaid-svg-1zrY3YeadsXTjM7x .image-shape .label,#mermaid-svg-1zrY3YeadsXTjM7x .icon-shape .label{text-anchor:middle;}#mermaid-svg-1zrY3YeadsXTjM7x .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-1zrY3YeadsXTjM7x .rough-node .label,#mermaid-svg-1zrY3YeadsXTjM7x .node .label,#mermaid-svg-1zrY3YeadsXTjM7x .image-shape .label,#mermaid-svg-1zrY3YeadsXTjM7x .icon-shape .label{text-align:center;}#mermaid-svg-1zrY3YeadsXTjM7x .node.clickable{cursor:pointer;}#mermaid-svg-1zrY3YeadsXTjM7x .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-1zrY3YeadsXTjM7x .arrowheadPath{fill:#333333;}#mermaid-svg-1zrY3YeadsXTjM7x .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-1zrY3YeadsXTjM7x .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-1zrY3YeadsXTjM7x .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-1zrY3YeadsXTjM7x .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-1zrY3YeadsXTjM7x .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-1zrY3YeadsXTjM7x .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-1zrY3YeadsXTjM7x .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-1zrY3YeadsXTjM7x .cluster text{fill:#333;}#mermaid-svg-1zrY3YeadsXTjM7x .cluster span{color:#333;}#mermaid-svg-1zrY3YeadsXTjM7x div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\”trebuchet ms\”,verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-1zrY3YeadsXTjM7x .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-1zrY3YeadsXTjM7x rect.text{fill:none;stroke-width:0;}#mermaid-svg-1zrY3YeadsXTjM7x .icon-shape,#mermaid-svg-1zrY3YeadsXTjM7x .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-1zrY3YeadsXTjM7x .icon-shape p,#mermaid-svg-1zrY3YeadsXTjM7x .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-1zrY3YeadsXTjM7x .icon-shape .label rect,#mermaid-svg-1zrY3YeadsXTjM7x .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-1zrY3YeadsXTjM7x .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-1zrY3YeadsXTjM7x .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-1zrY3YeadsXTjM7x :root{–mermaid-font-family:\”trebuchet ms\”,verdana,arial,sans-serif;}

    输入 x (B, c1, H, W)

    Conv 1×1: c1 -> c_ (cv1)

    Conv 1×1: c1 -> c_ (cv2)

    n 个 GhostBottleneck(每个保持 c_ 通道)

    处理后 (B, c_, H, W)

    直接传递 (B, c_, H, W)

    拼接: cat -> (B, 2*c_, H, W)

    Conv 1×1: 2*c_ -> c2 (cv3)

    输出 (B, c2, H, W)


    代码解读

    • __init__:
      • 调用父类 C3.__init__,这会创建 cv1、cv2、cv3 以及初始的 self.m(Bottleneck 序列)。
      • 计算 c_ = int(c2 * e)。
      • 覆盖 self.m 为 nn.Sequential,包含 n 个 GhostBottleneck,每个的输入输出通道均为 c_。
    • forward:直接继承自 C3,无需重写。

    注意事项

  • c_ 必须为偶数:因为 GhostBottleneck 内部 c_ = c2 // 2(这里的 c2 指模块的输出通道,即传入的 c_),若 c_ 为奇数,会因 c2//2 截断而导致输出通道不匹配。
  • shortcut 和 g 参数无效:由于 GhostBottleneck 未使用这些参数,它们仅用于父类 C3 的 Bottleneck 构造,但父类的 m 被覆盖,因此这些参数在 C3Ghost 中不起作用。
  • 空间尺寸不变:GhostBottleneck 步长固定为 1,因此模块不进行下采样。
  • 轻量但精度可能略降:Ghost 模块和深度卷积减少了参数,但也可能损失部分表示能力。
  • 与 C3 的兼容性:接口与 C3 一致,可直接替换,但需注意隐藏通道的奇偶性。

  • 优缺点

    优点
  • 计算高效:Ghost 模块和深度卷积大幅降低 FLOPs 和参数量,适合移动端部署。
  • 即插即用:与 C3 接口完全一致,可无缝替换,无需修改网络结构。
  • 可调节性:通过 n 和 e 控制深度和宽度,灵活适应不同资源场景。
  • 缺点
  • 表达能力受限:相比标准 Bottleneck,Ghost 模块可能损失部分特征多样性,在复杂任务上精度略低。
  • 通道约束:要求 int(c2 * e) 为偶数,限制了参数选择。
  • shortcut 失效:传入的 shortcut 参数无法作用于 GhostBottleneck,无法启用残差连接(GhostBottleneck 默认无残差,除非步长为 2)。
  • 无下采样功能:步长固定为 1,若需下采样需额外使用其他模块。

  • 在 YOLOv5‑Ghost 或轻量级网络中,C3Ghost 可作为骨干网络的基本构建块,在保持较高精度的同时极大提升速度。使用时建议根据硬件条件调整 n 和 e,并注意 c_ 必须为偶数。若需下采样,可配合 Conv 层(如步长 2)使用。

    参考文献

    [1] https://docs.ultralytics.com/ [2] https://github.com/ultralytics/ultralytics.git

    • 由于本人水平有限,难免出现错漏,敬请批评改正。
    • 更多精彩内容,可点击进入Python日常小操作专栏、OpenCV-Python小应用专栏、YOLO系列专栏、自然语言处理专栏、人工智能混合编程实践专栏或我的个人主页查看
    • YOLOs-CPP:一个免费开源的YOLO全系列C++推理库(以YOLO26为例)
    • PaddleOCR:Win10上安装使用PPOCRLabel标注工具
    • 目标检测:使用自己的数据集微调DEIMv2进行物体检测
    • 图像分割:PyTorch从零开始实现SegFormer语义分割
    • 图像超分:使用自己的数据集微调Real-ESRGAN-x4plus进行超分重建
    • 图像生成:PyTorch从零开始实现一个简单的扩散模型
    • Stable Diffusion:使用自己的数据集微调 Stable Diffusion 3.5 LoRA 文生图模型
    • 图像超分:使用自己的数据集微调Real-ESRGAN-x2plus进行超分重建
    • Anomalib:使用Anomalib 2.1.0训练自己的数据集进行异常检测
    • Anomalib:在Linux服务器上安装使用Anomalib 2.1.0
    • 人工智能混合编程实践:C++调用封装好的DLL进行异常检测推理
    • 人工智能混合编程实践:C++调用封装好的DLL进行FP16图像超分重建(v3.0)
    • 隔离系统Python:源码编译3.11.8到自定义目录(含PGO性能优化)
    • 在线机的Python环境迁移到离线机上
    • Nuitka 将 Python 脚本封装为 .pyd 或 .so 文件
    • Ultralytics:使用 YOLO11 进行速度估计
    • Ultralytics:使用 YOLO11 进行物体追踪
    • Ultralytics:使用 YOLO11 进行物体计数
    • Ultralytics:使用 YOLO11 进行目标打码
    • 人工智能混合编程实践:C++调用Python ONNX进行YOLOv8推理
    • 人工智能混合编程实践:C++调用封装好的DLL进行YOLOv8实例分割
    • 人工智能混合编程实践:C++调用Python ONNX进行图像超分重建
    • 人工智能混合编程实践:C++调用Python AgentOCR进行文本识别
    • 通过计算实例简单地理解PatchCore异常检测
    • Python将YOLO格式实例分割数据集转换为COCO格式实例分割数据集
    • YOLOv8 Ultralytics:使用Ultralytics框架训练RT-DETR实时目标检测模型
    • 基于DETR的人脸伪装检测
    • YOLOv7训练自己的数据集(口罩检测)
    • YOLOv8训练自己的数据集(足球检测)
    • YOLOv5:TensorRT加速YOLOv5模型推理
    • YOLOv5:IoU、GIoU、DIoU、CIoU、EIoU
    • 玩转Jetson Nano(五):TensorRT加速YOLOv5目标检测
    • YOLOv5:添加SE、CBAM、CoordAtt、ECA注意力机制
    • YOLOv5:yolov5s.yaml配置文件解读、增加小目标检测层
    • Python将COCO格式实例分割数据集转换为YOLO格式实例分割数据集
    • YOLOv5:使用7.0版本训练自己的实例分割模型(车辆、行人、路标、车道线等实例分割)
    • 使用Kaggle GPU资源免费体验Stable Diffusion开源项目
    • Stable Diffusion:在服务器上部署使用Stable Diffusion WebUI进行AI绘图(v2.0)
    • Stable Diffusion:使用自己的数据集微调训练LoRA模型(v2.0)
    赞(0)
    未经允许不得转载:171主机测评 » Ultralytics:解读C3Ghost模块
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址