Transformers 文档

YOLOS

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

YOLOS

PyTorch FlashAttention SDPA

概述

YOLOS 模型由 Yuxin Fang、Bencheng Liao、Xinggang Wang、Jiemin Fang、Jiyang Qi、Rui Wu、Jianwei Niu 和 Wenyu Liu 在论文 You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection 中提出。受 DETR 启发,YOLOS 提出仅利用普通的 Vision Transformer (ViT) 进行目标检测。事实证明,一个基础大小的仅编码器 Transformer 也能在 COCO 数据集上达到 42 AP,与 DETR 以及更复杂的框架(如 Faster R-CNN)性能相当。

论文摘要如下:

摘要:Transformer 能否从纯粹的序列到序列的角度,在对二维空间结构了解最少的情况下,执行二维目标和区域级识别?为了回答这个问题,我们提出了 YOLOS (You Only Look at One Sequence),这是一系列基于原始 Vision Transformer 的目标检测模型,并对目标任务的区域先验和归纳偏置进行了最少的修改。我们发现,仅在中等大小的 ImageNet-1k 数据集上预训练的 YOLOS 已经可以在具有挑战性的 COCO 目标检测基准上取得相当有竞争力的性能,例如,直接从 BERT-Base 架构改编的 YOLOS-Base 可以在 COCO 验证集上获得 42.0 的 box AP。我们还通过 YOLOS 讨论了当前视觉 Transformer 预训练方案和模型缩放策略的影响和局限性。

drawing YOLOS 架构。摘自原始论文

该模型由 nielsr 贡献。原始代码可在此处找到。

使用缩放点积注意力 (SDPA)

PyTorch 包含一个原生的缩放点积注意力(SDPA)算子,作为 torch.nn.functional 的一部分。该函数包含多种实现,可根据输入和使用的硬件进行应用。更多信息请参阅官方文档GPU 推理页面。

当实现可用时,SDPA 默认用于 `torch>=2.1.1`,但你也可以在 `from_pretrained()` 中设置 `attn_implementation="sdpa"` 来明确请求使用 SDPA。

from transformers import AutoModelForObjectDetection
model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-base", attn_implementation="sdpa", torch_dtype=torch.float16)
...

为了获得最佳加速效果,我们建议以半精度(例如 `torch.float16` 或 `torch.bfloat16`)加载模型。

在一个本地基准测试(A100-40GB,PyTorch 2.3.0,操作系统 Ubuntu 22.04)中,使用 float32hustvl/yolos-base 模型,我们在推理过程中观察到以下加速效果。

批次大小 平均推理时间(毫秒),eager 模式 平均推理时间(毫秒),sdpa 模型 加速,Sdpa / Eager (x)
1 106 76 1.39
2 154 90 1.71
4 222 116 1.91
8 368 168 2.19

资源

Hugging Face 官方和社区(由 🌎 标识)提供的资源列表,帮助您开始使用 YOLOS。

物体检测

如果您有兴趣在此处提交资源,请随时开启 Pull Request,我们将对其进行审查!该资源最好能展示一些新内容,而不是重复现有资源。

使用 YolosImageProcessor 为模型准备图像(以及可选的目标)。与 DETR 不同,YOLOS 不需要创建 pixel_mask

YolosConfig

class transformers.YolosConfig

< >

( hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-12 image_size = [512, 864] patch_size = 16 num_channels = 3 qkv_bias = True num_detection_tokens = 100 use_mid_position_embeddings = True auxiliary_loss = False class_cost = 1 bbox_cost = 5 giou_cost = 2 bbox_loss_coefficient = 5 giou_loss_coefficient = 2 eos_coefficient = 0.1 **kwargs )

参数

  • hidden_size (int, 可选, 默认为 768) — 编码器层和池化层的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数量。
  • intermediate_size (int, 可选, 默认为 3072) — Transformer 编码器中“中间层”(即前馈层)的维度。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化层中的非线性激活函数(函数或字符串)。如果为字符串,支持 "gelu""relu""selu""gelu_new"
  • hidden_dropout_prob (float, 可选, 默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的丢弃概率。
  • attention_probs_dropout_prob (float, 可选, 默认为 0.0) — 注意力概率的丢弃率。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-12) — 层归一化层使用的 epsilon 值。
  • image_size (list[int], 可选, 默认为 [512, 864]) — 每张图像的大小(分辨率)。
  • patch_size (int, 可选, 默认为 16) — 每个图像块的大小(分辨率)。
  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • qkv_bias (bool, 可选, 默认为 True) — 是否为查询、键和值添加偏置。
  • num_detection_tokens (int, 可选, 默认为 100) — 检测令牌的数量。
  • use_mid_position_embeddings (bool, 可选, 默认为 True) — 是否使用中间层位置编码。
  • auxiliary_loss (bool, 可选, 默认为 False) — 是否使用辅助解码损失(每个解码器层的损失)。
  • class_cost (float, 可选, 默认为 1) — 匈牙利匹配代价中分类错误的相对权重。
  • bbox_cost (float, 可选, 默认为 5) — 匈牙利匹配代价中边界框坐标 L1 错误的相对权重。
  • giou_cost (float, 可选, 默认为 2) — 匈牙利匹配代价中边界框广义 IoU 损失的相对权重。
  • bbox_loss_coefficient (float, 可选, 默认为 5) — 目标检测损失中 L1 边界框损失的相对权重。
  • giou_loss_coefficient (float, 可选, 默认为 2) — 目标检测损失中广义 IoU 损失的相对权重。
  • eos_coefficient (float, 可选, 默认为 0.1) — 目标检测损失中“无目标”类别的相对分类权重。

这是用于存储 YolosModel 配置的配置类。它用于根据指定的参数实例化一个 YOLOS 模型,定义模型架构。使用默认值实例化配置将产生与 YOLOS hustvl/yolos-base 架构类似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。更多信息请阅读 PretrainedConfig 的文档。

示例

>>> from transformers import YolosConfig, YolosModel

>>> # Initializing a YOLOS hustvl/yolos-base style configuration
>>> configuration = YolosConfig()

>>> # Initializing a model (with random weights) from the hustvl/yolos-base style configuration
>>> model = YolosModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

YolosImageProcessor

class transformers.YolosImageProcessor

< >

( format: typing.Union[str, transformers.image_utils.AnnotationFormat] = <AnnotationFormat.COCO_DETECTION: 'coco_detection'> do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_annotations: typing.Optional[bool] = None do_pad: bool = True pad_size: typing.Optional[dict[str, int]] = None **kwargs )

参数

  • format (str, 可选, 默认为 "coco_detection") — 标注的数据格式。可以是 “coco_detection” 或 “coco_panoptic”。
  • do_resize (bool, 可选, 默认为 True) — 控制是否将图像的(高、宽)维度调整为指定的 size。可在 preprocess 方法中通过 do_resize 参数覆盖此设置。
  • size (dict[str, int] 可选, 默认为 {"shortest_edge" -- 800, "longest_edge": 1333}): 调整大小后图像的 (高, 宽) 维度。可在 preprocess 方法中通过 size 参数覆盖此设置。可用选项有:
    • {"height": int, "width": int}: 图像将被调整为精确的 (高, 宽) 尺寸。不保持宽高比。
    • {"shortest_edge": int, "longest_edge": int}: 图像将被调整到最大尺寸,同时保持宽高比,并使最短边小于或等于 shortest_edge,最长边小于或等于 longest_edge
    • {"max_height": int, "max_width": int}: 图像将被调整到最大尺寸,同时保持宽高比,并使高度小于或等于 max_height,宽度小于或等于 max_width
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BILINEAR) — 调整图像大小时使用的重采样滤波器。
  • do_rescale (bool, 可选, 默认为 True) — 控制是否按指定的缩放因子 rescale_factor 缩放图像。可在 preprocess 方法中通过 do_rescale 参数覆盖此设置。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 缩放图像时使用的缩放因子。可在 preprocess 方法中通过 rescale_factor 参数覆盖此设置。
  • do_normalize — 控制是否对图像进行归一化。可在 preprocess 方法中通过 do_normalize 参数覆盖此设置。
  • image_mean (floatlist[float], 可选, 默认为 IMAGENET_DEFAULT_MEAN) — 归一化图像时使用的均值。可以是一个单一值,也可以是一个列表,每个通道一个值。可在 preprocess 方法中通过 image_mean 参数覆盖此设置。
  • image_std (floatlist[float], 可选, 默认为 IMAGENET_DEFAULT_STD) — 归一化图像时使用的标准差值。可以是一个单一值,也可以是一个列表,每个通道一个值。可在 preprocess 方法中通过 image_std 参数覆盖此设置。
  • do_pad (bool, optional, defaults to True) — 控制是否对图像进行填充。可在 `preprocess` 方法中使用 `do_pad` 参数进行覆盖。如果为 `True`,则会在图像的底部和右侧用零进行填充。如果提供了 `pad_size`,图像将被填充到指定尺寸。否则,图像将被填充到批处理中的最大高度和宽度。
  • pad_size (dict[str, int], optional) — 用于填充图像的尺寸 {"height": int, "width" int}。必须大于为预处理提供的任何图像尺寸。如果未提供 `pad_size`,图像将被填充到批处理中的最大高度和宽度。

构建一个 Detr 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: typing.Union[dict[str, typing.Union[int, str, list[dict]]], list[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None return_segmentation_masks: typing.Optional[bool] = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Union[int, float, NoneType] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_annotations: typing.Optional[bool] = None do_pad: typing.Optional[bool] = None format: typing.Union[str, transformers.image_utils.AnnotationFormat, NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None pad_size: typing.Optional[dict[str, int]] = None **kwargs )

参数

  • images (ImageInput) — 要预处理的图像或一批图像。期望是单个或一批像素值范围在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间,请设置 `do_rescale=False`。
  • annotations (AnnotationType or list[AnnotationType], optional) — 与图像或图像批次相关联的标注列表。如果标注用于目标检测,标注应为包含以下键的字典:
    • “image_id” (int): 图像 ID。
    • “annotations” (list[Dict]): 图像的标注列表。每个标注都应为一个字典。一张图像可以没有标注,此时列表应为空。如果标注用于分割,标注应为包含以下键的字典:
    • “image_id” (int): 图像 ID。
    • “segments_info” (list[Dict]): 图像的分割信息列表。每个分割信息都应为一个字典。一张图像可以没有分割信息,此时列表应为空。
    • “file_name” (str): 图像的文件名。
  • return_segmentation_masks (bool, optional, defaults to self.return_segmentation_masks) — 是否返回分割掩码。
  • masks_path (str or pathlib.Path, optional) — 包含分割掩码的目录路径。
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], optional, defaults to self.size) — 调整大小后图像的 `(height, width)` 尺寸。可用选项包括:
    • {"height": int, "width": int}: 图像将被调整为精确的 `(height, width)` 尺寸。不保持宽高比。
    • {"shortest_edge": int, "longest_edge": int}: 图像将被调整到最大尺寸,同时保持宽高比,并使最短边小于或等于 `shortest_edge`,最长边小于或等于 `longest_edge`。
    • {"max_height": int, "max_width": int}: 图像将被调整到最大尺寸,同时保持宽高比,并使高度小于或等于 `max_height`,宽度小于或等于 `max_width`。
  • resample (PILImageResampling, optional, defaults to self.resample) — 调整图像大小时使用的重采样滤波器。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否对图像进行缩放。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 对图像进行缩放时使用的缩放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化。
  • image_mean (float or list[float], optional, defaults to self.image_mean) — 归一化图像时使用的均值。
  • image_std (float or list[float], optional, defaults to self.image_std) — 归一化图像时使用的标准差。
  • do_convert_annotations (bool, optional, defaults to self.do_convert_annotations) — 是否将标注转换为模型期望的格式。将边界框从 `(top_left_x, top_left_y, width, height)` 格式转换为 `(center_x, center_y, width, height)` 格式,并使用相对坐标。
  • do_pad (bool, optional, defaults to self.do_pad) — 是否对图像进行填充。如果为 `True`,则会在图像的底部和右侧用零进行填充。如果提供了 `pad_size`,图像将被填充到指定尺寸。否则,图像将被填充到批处理中的最大高度和宽度。
  • format (str or AnnotationFormat, optional, defaults to self.format) — 标注的格式。
  • return_tensors (str or TensorType, optional, defaults to self.return_tensors) — 返回张量的类型。如果为 `None`,将返回图像列表。
  • data_format (str or ChannelDimension, optional, defaults to self.data_format) — 图像的通道维度格式。如果未提供,将与输入图像相同。
  • input_data_format (ChannelDimension or str, optional) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。
  • pad_size (dict[str, int], optional) — 用于填充图像的尺寸 {"height": int, "width" int}。必须大于为预处理提供的任何图像尺寸。如果未提供 `pad_size`,图像将被填充到批处理中的最大高度和宽度。

预处理图像或图像批次,以便模型可以使用。

YolosImageProcessorFast

class transformers.YolosImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.yolos.image_processing_yolos_fast.YolosFastImageProcessorKwargs] )

构建一个快速 Yolos 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: typing.Union[dict[str, typing.Union[int, str, list[dict]]], list[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None **kwargs: typing_extensions.Unpack[transformers.models.yolos.image_processing_yolos_fast.YolosFastImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]) — 要预处理的图像。期望是单个或一批像素值范围在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间,请设置 `do_rescale=False`。
  • annotations (AnnotationType or list[AnnotationType], optional) — 与图像或图像批次相关联的标注列表。如果标注用于目标检测,标注应为包含以下键的字典:
    • “image_id” (int): 图像 ID。
    • “annotations” (list[Dict]): 图像的标注列表。每个标注都应为一个字典。一张图像可以没有标注,此时列表应为空。如果标注用于分割,标注应为包含以下键的字典:
    • “image_id” (int): 图像 ID。
    • “segments_info” (list[Dict]): 图像的分割信息列表。每个分割信息都应为一个字典。一张图像可以没有分割信息,此时列表应为空。
    • “file_name” (str): 图像的文件名。
  • masks_path (str or pathlib.Path, optional) — 包含分割掩码的目录路径。
  • do_resize (bool, optional) — 是否调整图像大小。
  • size (dict[str, int], optional) — 描述模型的最大输入尺寸。
  • default_to_square (bool, optional) — 在调整大小时,如果 size 是一个整数,是否默认调整为方形图像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果要调整图像大小,使用的重采样滤波器。这可以是 `PILImageResampling` 枚举之一。仅当 `do_resize` 设置为 `True` 时有效。
  • do_center_crop (bool, optional) — 是否对图像进行中心裁剪。
  • crop_size (dict[str, int], optional) — 应用 `center_crop` 后输出图像的尺寸。
  • do_rescale (bool, optional) — 是否对图像进行缩放。
  • rescale_factor (Union[int, float, NoneType]) — 如果 `do_rescale` 设置为 `True`,用于缩放图像的缩放因子。
  • do_normalize (bool, optional) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], NoneType]) — 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时有效。
  • image_std (Union[float, list[float], NoneType]) — 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时有效。
  • do_convert_rgb (bool, optional) — 是否将图像转换为 RGB 格式。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。
  • data_format (~image_utils.ChannelDimension, optional) — 仅支持 `ChannelDimension.FIRST`。为与慢速处理器兼容而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension, NoneType]) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。
  • device (torch.device, optional) — 处理图像的设备。如果未设置,将从输入图像中推断设备。
  • disable_grouping (bool, optional) — 是否禁用按尺寸对图像进行分组,以便单独处理而不是分批处理。如果为 None,则在图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见:https://github.com/huggingface/transformers/pull/38157
  • format (str, optional, defaults to AnnotationFormat.COCO_DETECTION) — 标注的数据格式。可以是 “coco_detection” 或 “coco_panoptic” 之一。
  • do_convert_annotations (bool, optional, defaults to True) — 控制是否将标注转换为 YOLOS 模型期望的格式。将边界框转换为 `(center_x, center_y, width, height)` 格式,并且范围在 `[0, 1]` 之间。可在 `preprocess` 方法中使用 `do_convert_annotations` 参数进行覆盖。
  • do_pad (bool, 可选, 默认为 True) — 控制是否对图像进行填充。此参数可被 preprocess 方法中的 do_pad 参数覆盖。如果为 True,将使用零值对图像的底部和右侧进行填充。如果提供了 pad_size,图像将被填充到指定尺寸。否则,图像将被填充到批处理中的最大高度和宽度。
  • pad_size (dict[str, int], 可选) — 图像填充的目标尺寸,格式为 {"height": int, "width" int}。必须大于任何待预处理图像的尺寸。如果未提供 pad_size,图像将被填充到批处理中的最大高度和宽度。
  • return_segmentation_masks (bool, 可选, 默认为 False) — 是否返回分割掩码。

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

pad

< >

( image: Tensor padded_size: tuple annotation: typing.Optional[dict[str, typing.Any]] = None update_bboxes: bool = True fill: int = 0 )

post_process_object_detection

< >

( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple]] = None top_k: int = 100 ) list[Dict]

参数

  • outputs (YolosObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选) — 用于保留目标检测预测结果的分数阈值。
  • target_sizes (torch.Tensorlist[tuple[int, int]], 可选) — 形状为 (batch_size, 2) 的张量或包含批处理中每张图像目标尺寸(高度,宽度)的元组列表 (tuple[int, int])。如果留空为 None,则不会调整预测结果的大小。
  • top_k (int, 可选, 默认为 100) — 在通过阈值过滤之前,仅保留前 k 个边界框。

返回

list[Dict]

一个字典列表,每个字典包含模型预测的批处理中每张图像的分数、标签和框。

YolosForObjectDetection 的原始输出转换为最终的边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。仅支持 PyTorch。

YolosFeatureExtractor

class transformers.YolosFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

预处理单张或批量图像。

pad

< >

( images: list annotations: typing.Optional[list[dict[str, typing.Any]]] = None constant_values: typing.Union[float, collections.abc.Iterable[float]] = 0 return_pixel_mask: bool = False return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None update_bboxes: bool = True pad_size: typing.Optional[dict[str, int]] = None )

参数

  • image (np.ndarray) — 待填充的图像。
  • annotations (list[dict[str, any]], 可选) — 随图像一同填充的标注。如果提供此参数,边界框将被更新以匹配填充后的图像。
  • constant_values (floatIterable[float], 可选) — 当 `mode` 为 `"constant"` 时用于填充的值。
  • return_pixel_mask (bool, 可选, 默认为 True) — 是否返回像素掩码。
  • return_tensors (strTensorType, 可选) — 返回张量的类型。可以是以下之一:
    • 未设置:返回 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回类型为 tf.Tensor 的批处理。
    • TensorType.PYTORCH'pt':返回类型为 torch.Tensor 的批处理。
    • TensorType.NUMPY'np':返回类型为 np.ndarray 的批处理。
    • TensorType.JAX'jax':返回类型为 jax.numpy.ndarray 的批处理。
  • data_format (strChannelDimension, 可选) — 图像的通道维度格式。如果未提供,将与输入图像的格式相同。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未提供,将自动推断。
  • update_bboxes (bool, 可选, 默认为 True) — 是否更新标注中的边界框以匹配填充后的图像。如果边界框尚未转换为相对坐标和 `(centre_x, centre_y, width, height)` 格式,则不会更新边界框。
  • pad_size (dict[str, int], 可选) — 图像填充的目标尺寸,格式为 {"height": int, "width" int}。必须大于任何待预处理图像的尺寸。如果未提供 pad_size,图像将被填充到批处理中的最大高度和宽度。

将一批图像的底部和右侧用零值填充,使其达到批处理中最大高度和宽度的尺寸,并可选择性地返回其对应的像素掩码。

post_process_object_detection

< >

( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple]] = None ) list[Dict]

参数

  • outputs (YolosObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选) — 用于保留目标检测预测结果的分数阈值。
  • target_sizes (torch.Tensorlist[tuple[int, int]], 可选) — 形状为 (batch_size, 2) 的张量或包含批处理中每张图像目标尺寸 (height, width) 的元组列表 (tuple[int, int])。如果未设置,则不会调整预测结果的大小。

返回

list[Dict]

一个字典列表,每个字典包含模型预测的批处理中每张图像的分数、标签和框。

YolosForObjectDetection 的原始输出转换为最终的边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。仅支持 PyTorch。

YolosModel

class transformers.YolosModel

< >

( config: YolosConfig add_pooling_layer: bool = True )

参数

  • config (YolosConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型关联的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。
  • add_pooling_layer (bool, 可选, 默认为 True) — 是否添加池化层。

基础的 Yolos 模型,输出原始的隐藏状态,顶部没有任何特定的头。

该模型继承自 PreTrainedModel。查阅超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

该模型也是一个 PyTorch torch.nn.Module 子类。可以像常规 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与通用用法和行为相关的事项。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size), 可选) — 对应于输入图像的张量。像素值可以通过 {image_processor_class} 获得。详情请参阅 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 处理图像)。
  • head_mask (torch.Tensor,形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于使自注意力模块的选定头部无效的掩码。掩码值选自 [0, 1]

    • 1 表示头部未被屏蔽
    • 0 表示头部被屏蔽
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

transformers.modeling_outputs.BaseModelOutputWithPoolingtorch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置(YolosConfig)和输入,包含各种元素。

  • last_hidden_state (torch.FloatTensor, 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

  • pooler_output (torch.FloatTensor,形状为 (batch_size, hidden_size)) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理。例如,对于 BERT 系列模型,这将返回经过线性层和 tanh 激活函数处理后的分类标记。线性层权重是在预训练期间从下一句预测(分类)目标中训练的。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则一个是嵌入层的输出,加上每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

YolosModel 的 forward 方法覆盖了 `__call__` 特殊方法。

虽然前向传播的流程需要在此函数中定义,但之后应该调用 `Module` 实例而不是这个函数,因为前者会处理预处理和后处理步骤,而后者会静默地忽略它们。

示例

YolosForObjectDetection

class transformers.YolosForObjectDetection

< >

( config: YolosConfig )

参数

  • config (YolosConfig) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型关联的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。

YOLOS 模型(由一个 ViT 编码器组成),顶部带有目标检测头,用于如 COCO 检测等任务。

该模型继承自 PreTrainedModel。查阅超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

该模型也是一个 PyTorch torch.nn.Module 子类。可以像常规 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与通用用法和行为相关的事项。

forward

< >

( pixel_values: FloatTensor labels: typing.Optional[list[dict]] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.yolos.modeling_yolos.YolosObjectDetectionOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。像素值可以通过 {image_processor_class} 获得。详情请参阅 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 处理图像)。
  • labels (list[Dict],长度为 (batch_size,), 可选) — 用于计算二分匹配损失的标签。是字典的列表,每个字典至少包含以下 2 个键:'class_labels''boxes'(分别表示批处理中图像的类别标签和边界框)。类别标签本身应为长度为 (图像中边界框的数量,)torch.LongTensor,而边界框应为形状为 (图像中边界框的数量, 4)torch.FloatTensor
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.models.yolos.modeling_yolos.YolosObjectDetectionOutputtuple(torch.FloatTensor)

transformers.models.yolos.modeling_yolos.YolosObjectDetectionOutputtorch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),根据配置(YolosConfig)和输入,包含各种元素。

  • loss (torch.FloatTensor,形状为 (1,), 可选, 当提供了 labels 时返回) — 总损失,是类别预测的负对数似然(交叉熵)和边界框损失的线性组合。后者定义为 L1 损失和广义尺度不变 IoU 损失的线性组合。

  • loss_dict (Dict, 可选) — 包含各个损失的字典。用于日志记录。

  • logits (形状为 (batch_size, num_queries, num_classes + 1)torch.FloatTensor) — 所有查询的分类 logits(包括无对象)。

  • pred_boxes (torch.FloatTensor,形状为 (batch_size, num_queries, 4)) — 所有查询的归一化边界框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批处理中每个单独图像的大小(不考虑可能的填充)。你可以使用 post_process() 来检索未归一化的边界框。

  • auxiliary_outputs (list[Dict], 可选) — 可选,仅在激活辅助损失(即 config.auxiliary_loss 设置为 True)并提供标签时返回。它是一个字典列表,包含每个解码器层的上述两个键(`logits` 和 `pred_boxes`)。

  • last_hidden_state (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor可选) — 模型解码器最后一层输出的隐藏状态序列。

  • hidden_states (tuple[torch.FloatTensor], 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — `torch.FloatTensor` 的元组(如果模型有嵌入层,则一个是嵌入层的输出,加上每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor], 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — `torch.FloatTensor` 的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

YolosForObjectDetection 的 forward 方法覆盖了 `__call__` 特殊方法。

虽然前向传播的流程需要在此函数中定义,但之后应该调用 `Module` 实例而不是这个函数,因为前者会处理预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> import torch
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("hustvl/yolos-tiny")
>>> model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-tiny")

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
...     0
... ]

>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
...     box = [round(i, 2) for i in box.tolist()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected remote with confidence 0.991 at location [46.48, 72.78, 178.98, 119.3]
Detected remote with confidence 0.908 at location [336.48, 79.27, 368.23, 192.36]
Detected cat with confidence 0.934 at location [337.18, 18.06, 638.14, 373.09]
Detected cat with confidence 0.979 at location [10.93, 53.74, 313.41, 470.67]
Detected remote with confidence 0.974 at location [41.63, 72.23, 178.09, 119.99]
< > 在 GitHub 上更新