Transformers 文档

可变形 DETR

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Deformable DETR

PyTorch

概述

Deformable DETR 模型由 Xizhou Zhu、Weijie Su、Lewei Lu、Bin Li、Xiaogang Wang 和 Jifeng Dai 在 Deformable DETR: Deformable Transformers for End-to-End Object Detection 中提出。Deformable DETR 通过利用新的可变形注意力模块,仅关注参考点周围的一小部分关键采样点,从而缓解了原始 DETR 收敛缓慢和特征空间分辨率有限的问题。

论文摘要如下:

DETR 最近被提出,旨在消除目标检测中许多手动设计组件的需求,同时表现出良好的性能。然而,由于 Transformer 注意力模块在处理图像特征图方面的限制,它存在收敛缓慢和特征空间分辨率有限的问题。为了缓解这些问题,我们提出了 Deformable DETR,其注意力模块只关注参考点周围的一小部分关键采样点。Deformable DETR 在训练 epoch 减少 10 倍的情况下,可以比 DETR 获得更好的性能(尤其是在小目标上)。在 COCO 基准上的大量实验证明了我们方法的有效性。

drawing Deformable DETR 架构。摘自原始论文

此模型由 nielsr 贡献。原始代码可以在这里找到。

使用技巧

  • 训练 Deformable DETR 等同于训练原始 DETR 模型。请参见下面的资源部分,了解演示笔记本。

资源

Hugging Face 官方和社区(🌎 表示)资源列表,助您开始使用 Deformable DETR。

物体检测

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

DeformableDetrImageProcessor

class transformers.DeformableDetrImageProcessor

< >

( 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, optional, 默认为 "coco_detection") — 注释的数据格式。可以是 "coco_detection" 或 "coco_panoptic" 之一。
  • do_resize (bool, optional, 默认为 True) — 控制是否将图像的(高,宽)维度调整为指定的 size。可以通过 preprocess 方法中的 do_resize 参数覆盖。
  • size (dict[str, int] 可选, 默认为 {"shortest_edge" -- 800, "longest_edge": 1333}): 调整大小后图像的 (height, width) 维度大小。可以通过 preprocess 方法中的 size 参数覆盖。可用选项包括:
    • {"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, 可选, 默认为 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_convert_annotations (bool, 可选, 默认为 True) — 控制是否将注释转换为 DETR 模型期望的格式。将边界框转换为 (center_x, center_y, width, height) 格式和 [0, 1] 范围。可以通过 preprocess 方法中的 do_convert_annotations 参数覆盖。
  • do_pad (bool, 可选, 默认为 True) — 控制是否填充图像。如果为 True,将用零填充图像的底部和右侧。如果提供了 pad_size,图像将填充到指定的尺寸。否则,图像将填充到批次中的最大高度和宽度。
  • pad_size (dict[str, int], 可选) — 填充图像的尺寸 {"height": int, "width" int}。必须大于任何为预处理提供的图像尺寸。如果未提供 pad_size,图像将填充到批次中的最大高度和宽度。

构造一个 Deformable 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 do_convert_annotations: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = 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 (AnnotationTypelist[AnnotationType], 可选) — 与图像或图像批次关联的注释列表。如果注释用于目标检测,则注释应是一个字典,包含以下键:
    • “image_id” (int): 图像 ID。
    • “annotations” (list[Dict]): 图像的注释列表。每个注释应是一个字典。图像可以没有注释,在这种情况下,列表应为空。如果注释用于分割,则注释应是一个字典,包含以下键:
    • “image_id” (int): 图像 ID。
    • “segments_info” (list[Dict]): 图像的分割列表。每个分割应是一个字典。图像可以没有分割,在这种情况下,列表应为空。
    • “file_name” (str): 图像的文件名。
  • return_segmentation_masks (bool, 可选, 默认为 self.return_segmentation_masks) — 是否返回分割掩码。
  • masks_path (strpathlib.Path, 可选) — 包含分割掩码的目录路径。
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 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, 可选, 默认为 self.resample) — 调整图像大小时使用的重采样过滤器。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否重新缩放图像。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 重新缩放图像时使用的比例因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化。
  • do_convert_annotations (bool, 可选, 默认为 self.do_convert_annotations) — 是否将注释转换为模型期望的格式。将边界框从 (top_left_x, top_left_y, width, height) 格式转换为 (center_x, center_y, width, height) 格式并转换为相对坐标。
  • image_mean (floatlist[float], 可选, 默认为 self.image_mean) — 图像归一化时使用的平均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 图像归一化时使用的标准差。
  • do_pad (bool, 可选, 默认为 self.do_pad) — 是否填充图像。如果为 True,将用零填充图像的底部和右侧。如果提供了 pad_size,图像将填充到指定的尺寸。否则,图像将填充到批次中的最大高度和宽度。
  • format (strAnnotationFormat, 可选, 默认为 self.format) — 注释的格式。
  • return_tensors (strTensorType, 可选, 默认为 self.return_tensors) — 要返回的张量类型。如果为 None,将返回图像列表。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • 未设置: 使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "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], 可选) — 填充图像的尺寸 {"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 top_k: int = 100 ) list[Dict]

参数

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

返回

list[Dict]

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

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

DeformableDetrImageProcessorFast

class transformers.DeformableDetrImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_deformable_detr_fast.DeformableDetrFastImageProcessorKwargs] )

构建一个快速 Deformable 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 masks_path: typing.Union[str, pathlib.Path, NoneType] = None **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_deformable_detr_fast.DeformableDetrFastImageProcessorKwargs] ) <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 (AnnotationTypelist[AnnotationType], 可选) — 与图像或图像批次关联的标注列表。如果标注用于目标检测,标注应为包含以下键的字典:
    • “image_id” (int):图像 ID。
    • “annotations” (list[Dict]):图像的标注列表。每个标注应为一个字典。图像可以没有标注,在这种情况下列表应为空。如果标注用于分割,标注应为包含以下键的字典:
    • “image_id” (int):图像 ID。
    • “segments_info” (list[Dict]):图像的片段列表。每个片段应为一个字典。图像可以没有片段,在这种情况下列表应为空。
    • “file_name” (str):图像的文件名。
  • masks_path (strpathlib.Path, 可选) — 包含分割掩码的目录路径。
  • do_resize (bool, 可选) — 是否调整图像大小。
  • size (dict[str, int], 可选) — 描述模型的最大输入维度。
  • default_to_square (bool, 可选) — 如果尺寸为整数,是否在调整大小后默认使用方形图像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果调整图像大小,要使用的重采样过滤器。可以是枚举 PILImageResampling 之一。仅在 do_resize 设置为 True 时有效。
  • do_center_crop (bool, 可选) — 是否对图像进行中心裁剪。
  • crop_size (dict[str, int], 可选) — 应用 center_crop 后输出图像的尺寸。
  • do_rescale (bool, 可选) — 是否重新缩放图像。
  • rescale_factor (Union[int, float, NoneType]) — 如果 do_rescale 设置为 True,则按此重新缩放因子调整图像大小。
  • do_normalize (bool, 可选) — 是否归一化图像。
  • image_mean (Union[float, list[float], NoneType]) — 用于归一化的图像均值。仅在 do_normalize 设置为 True 时有效。
  • image_std (Union[float, list[float], NoneType]) — 用于归一化的图像标准差。仅在 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, 可选) — 是否将图像转换为 RGB。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果设置为 `pt`,则返回堆叠张量,否则返回张量列表。
  • data_format (~image_utils.ChannelDimension, 可选) — 仅支持 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, 可选) — 处理图像的设备。如果未设置,则从输入图像推断设备。
  • disable_grouping (bool, 可选) — 是否禁用按大小对图像进行分组以单独而非批处理它们。如果为 None,则如果图像在 CPU 上,则设置为 True,否则设置为 False。此选择基于经验观察,详情请参阅:https://github.com/huggingface/transformers/pull/38157
  • format (str, 可选, 默认为 AnnotationFormat.COCO_DETECTION) — 标注的数据格式。可以是 "coco_detection" 或 "coco_panoptic" 之一。
  • do_convert_annotations (bool, 可选, 默认为 True) — 控制是否将标注转换为 DEFORMABLE_DETR 模型期望的格式。将边界框转换为 (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张量。

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 (DetrObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选) — 保留目标检测预测的得分阈值。
  • target_sizes (torch.Tensorlist[tuple[int, int]], 可选) — 形状为 (batch_size, 2) 的张量,或包含批次中每张图像的目标尺寸(高,宽)的元组列表(tuple[int, int])。如果留空,预测将不会被调整大小。
  • top_k (int, 可选, 默认为 100) — 在阈值过滤之前,只保留前 k 个边界框。

返回

list[Dict]

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

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

DeformableDetrFeatureExtractor

class transformers.DeformableDetrFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

预处理单张或批量图像。

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 (DetrObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选) — 保留目标检测预测的得分阈值。
  • target_sizes (torch.Tensorlist[tuple[int, int]], 可选) — 形状为 (batch_size, 2) 的张量,或包含批次中每张图像的目标尺寸(高,宽)的元组列表(tuple[int, int])。如果留空,预测将不会被调整大小。
  • top_k (int, 可选, 默认为 100) — 在阈值过滤之前,只保留前 k 个边界框。

返回

list[Dict]

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

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

DeformableDetrConfig

class transformers.DeformableDetrConfig

< >

( use_timm_backbone = True backbone_config = None num_channels = 3 num_queries = 300 max_position_embeddings = 1024 encoder_layers = 6 encoder_ffn_dim = 1024 encoder_attention_heads = 8 decoder_layers = 6 decoder_ffn_dim = 1024 decoder_attention_heads = 8 encoder_layerdrop = 0.0 is_encoder_decoder = True activation_function = 'relu' d_model = 256 dropout = 0.1 attention_dropout = 0.0 activation_dropout = 0.0 init_std = 0.02 init_xavier_std = 1.0 return_intermediate = True auxiliary_loss = False position_embedding_type = 'sine' backbone = 'resnet50' use_pretrained_backbone = True backbone_kwargs = None dilation = False num_feature_levels = 4 encoder_n_points = 4 decoder_n_points = 4 two_stage = False two_stage_num_proposals = 300 with_box_refine = False class_cost = 1 bbox_cost = 5 giou_cost = 2 mask_loss_coefficient = 1 dice_loss_coefficient = 1 bbox_loss_coefficient = 5 giou_loss_coefficient = 2 eos_coefficient = 0.1 focal_alpha = 0.25 disable_custom_kernels = False **kwargs )

参数

  • use_timm_backbone (bool, 可选, 默认为 True) — 是否使用 timm 库作为骨干网络。如果设置为 False,将使用 AutoBackbone API。
  • backbone_config (PretrainedConfigdict, 可选) — 骨干模型的配置。仅在 use_timm_backbone 设置为 False 时使用,默认为 ResNetConfig()
  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • num_queries (int, 可选, 默认为 300) — 对象查询的数量,即检测槽。这是 DeformableDetrModel 在单张图像中可以检测到的最大对象数量。如果 two_stage 设置为 True,则使用 two_stage_num_proposals 代替。
  • d_model (int, 可选, 默认为 256) — 层的维度。
  • encoder_layers (int, 可选, 默认为 6) — 编码器层的数量。
  • decoder_layers (int, 可选, 默认为 6) — 解码器层的数量。
  • encoder_attention_heads (int, 可选, 默认为 8) — Transformer 编码器中每个注意力层的注意力头数量。
  • decoder_attention_heads (int, 可选, 默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • decoder_ffn_dim (int, 可选, 默认为 1024) — 解码器中“中间层”(通常称为前馈层)的维度。
  • encoder_ffn_dim (int, 可选, 默认为 1024) — 解码器中“中间层”(通常称为前馈层)的维度。
  • activation_function (strfunction, 可选, 默认为 "relu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu", "relu", "silu""gelu_new"
  • dropout (float, 可选, 默认为 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_dropout (float, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。
  • activation_dropout (float, 可选, 默认为 0.0) — 全连接层内部激活的 dropout 比率。
  • init_std (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • init_xavier_std (float, 可选, 默认为 1) — HM Attention 模块中用于 Xavier 初始化增益的比例因子。
  • encoder_layerdrop (float, 可选, 默认为 0.0) — 编码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。
  • auxiliary_loss (bool, 可选, 默认为 False) — 是否使用辅助解码损失(每个解码器层的损失)。
  • position_embedding_type (str, 可选, 默认为 "sine") — 在图像特征之上使用的位置嵌入类型。可选择 "sine""learned"
  • backbone (str, 可选, 默认为 "resnet50") — 当 backbone_configNone 时使用的骨干网络名称。如果 use_pretrained_backboneTrue,这将从 timm 或 transformers 库加载相应的预训练权重。如果 use_pretrained_backboneFalse,这将加载骨干网络的配置并使用该配置初始化骨干网络,权重随机。
  • use_pretrained_backbone (bool, 可选, 默认为 True) — 是否使用骨干网络的预训练权重。
  • backbone_kwargs (dict, 可选) — 从检查点加载时传递给 AutoBackbone 的关键字参数,例如 {'out_indices': (0, 1, 2, 3)}。如果设置了 backbone_config,则不能指定。
  • dilation (bool, 可选, 默认为 False) — 是否在最后一个卷积块(DC5)中用膨胀代替步幅。仅当 use_timm_backbone = True 时支持。
  • class_cost (float, 可选, 默认为 1) — 匈牙利匹配成本中分类错误的相对权重。
  • bbox_cost (float, 可选, 默认为 5) — 匈牙利匹配成本中边界框坐标 L1 误差的相对权重。
  • giou_cost (float, 可选, 默认为 2) — 匈牙利匹配成本中边界框广义 IoU 损失的相对权重。
  • mask_loss_coefficient (float, 可选, 默认为 1) — 全景分割损失中 Focal 损失的相对权重。
  • dice_loss_coefficient (float, 可选, 默认为 1) — 全景分割损失中 DICE/F-1 损失的相对权重。
  • bbox_loss_coefficient (float, 可选, 默认为 5) — 目标检测损失中 L1 边界框损失的相对权重。
  • giou_loss_coefficient (float, 可选, 默认为 2) — 目标检测损失中广义 IoU 损失的相对权重。
  • eos_coefficient (float, 可选, 默认为 0.1) — 目标检测损失中“无目标”类别的相对分类权重。
  • num_feature_levels (int, 可选, 默认为 4) — 输入特征层的数量。
  • encoder_n_points (int, 可选, 默认为 4) — 编码器中每个注意力头在每个特征层中采样的键点数量。
  • decoder_n_points (int, 可选, 默认为 4) — 解码器中每个注意力头在每个特征层中采样的键点数量。
  • two_stage (bool, 可选, 默认为 False) — 是否应用两阶段可变形 DETR,其中区域提案也由可变形 DETR 的变体生成,然后进一步馈送到解码器进行迭代边界框细化。
  • two_stage_num_proposals (int, 可选, 默认为 300) — 如果 two_stage 设置为 True,则生成的区域提案数量。
  • with_box_refine (bool, 可选, 默认为 False) — 是否应用迭代边界框细化,其中每个解码器层根据前一层预测的边界框进行细化。
  • focal_alpha (float, 可选, 默认为 0.25) — Focal 损失中的 Alpha 参数。
  • disable_custom_kernels (bool, 可选, 默认为 False) — 禁用自定义 CUDA 和 CPU 内核的使用。此选项对于 ONNX 导出是必需的,因为 PyTorch ONNX 导出不支持自定义内核。

这是配置类,用于存储 DeformableDetrModel 的配置。它用于根据指定的参数实例化 Deformable DETR 模型,定义模型架构。使用默认值实例化配置将生成与 Deformable DETR SenseTime/deformable-detr 架构类似的配置。

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

示例

>>> from transformers import DeformableDetrConfig, DeformableDetrModel

>>> # Initializing a Deformable DETR SenseTime/deformable-detr style configuration
>>> configuration = DeformableDetrConfig()

>>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
>>> model = DeformableDetrModel(configuration)

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

DeformableDetrModel

class transformers.DeformableDetrModel

< >

( config: DeformableDetrConfig )

参数

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

裸 Deformable DETR 模型(由骨干网络和编码器-解码器 Transformer 组成),输出原始隐藏状态,不带任何特定头部。

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

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: FloatTensor pixel_mask: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.FloatTensor] = None encoder_outputs: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获得。有关详细信息,请参见 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • pixel_mask (形状为 (batch_size, height, width)torch.LongTensor, 可选) — 避免对填充像素值执行注意力的遮罩。遮罩值选择范围 [0, 1]

    • 1 表示真实像素(即未遮罩),
    • 0 表示填充像素(即已遮罩)。

    什么是注意力遮罩?

  • decoder_attention_mask (形状为 (batch_size, num_queries)torch.FloatTensor, 可选) — 默认情况下不使用。可用于遮罩对象查询。
  • encoder_outputs (torch.FloatTensor, 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成,last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size),是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。
  • inputs_embeds (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可选) — 另外,除了传递展平的特征图(骨干网络 + 投影层的输出)外,您还可以选择直接传递图像的展平表示。
  • decoder_inputs_embeds (形状为 (batch_size, num_queries, hidden_size)torch.FloatTensor, 可选) — 另外,除了用零张量初始化查询外,您还可以选择直接传递嵌入表示。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回

transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutputtuple(torch.FloatTensor)

一个 transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置 (DeformableDetrConfig) 和输入的不同元素。

  • init_reference_points (torch.FloatTensor, 形状为 (batch_size, num_queries, 4)) — 通过 Transformer 解码器发送的初始参考点。

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

  • intermediate_hidden_states (torch.FloatTensor, 形状为 (batch_size, config.decoder_layers, num_queries, hidden_size)) — 堆叠的中间隐藏状态(解码器每层的输出)。

  • intermediate_reference_points (torch.FloatTensor, 形状为 (batch_size, config.decoder_layers, num_queries, 4)) — 堆叠的中间参考点(解码器每层的参考点)。

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

    解码器在每一层输出时的隐藏状态以及初始嵌入输出。

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

    解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。

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

    解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均。

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

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

    编码器在每一层输出时的隐藏状态以及初始嵌入输出。

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

    编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。

  • enc_outputs_class (形状为 (batch_size, sequence_length, config.num_labels)torch.FloatTensor, 可选, 当 config.with_box_refine=Trueconfig.two_stage=True 时返回) — 预测的边界框分数,其中得分最高的 config.two_stage_num_proposals 个边界框在第一阶段被选为区域提案。边界框二元分类(即前景和背景)的输出。

  • enc_outputs_coord_logits (形状为 (batch_size, sequence_length, 4)torch.FloatTensor, 可选, 当 config.with_box_refine=Trueconfig.two_stage=True 时返回) — 第一阶段预测边界框坐标的 logits。

DeformableDetrModel 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward pass 的配方需要在此函数中定义,但之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。

示例

>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> 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("SenseTime/deformable-detr")
>>> model = DeformableDetrModel.from_pretrained("SenseTime/deformable-detr")

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

>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 300, 256]

DeformableDetrForObjectDetection

class transformers.DeformableDetrForObjectDetection

< >

( config: DeformableDetrConfig )

参数

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

Deformable DETR 模型(由骨干网络和编码器-解码器 Transformer 组成),顶部带有目标检测头,用于 COCO 检测等任务。

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

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: FloatTensor pixel_mask: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.FloatTensor] = None encoder_outputs: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None 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.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参见 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • pixel_mask (形状为 (batch_size, height, width)torch.LongTensor可选) — 用于避免对填充像素值执行注意力操作的掩码。掩码值选择在 [0, 1] 之间:

    • 1 表示真实像素(即未被掩盖),
    • 0 表示填充像素(即被掩盖)。

    什么是注意力掩码?

  • decoder_attention_mask (形状为 (batch_size, num_queries)torch.FloatTensor可选) — 默认情况下不使用。可用于掩盖对象查询。
  • encoder_outputs (torch.FloatTensor可选) — 元组,包含(last_hidden_state可选hidden_states可选attentionslast_hidden_state 的形状为 (batch_size, sequence_length, hidden_size)可选)是编码器最后一层输出的隐藏状态序列。在解码器的交叉注意力中用到。
  • inputs_embeds (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor可选) — 可选地,您可以选择直接传递图像的平坦表示,而不是传递平坦的特征图(骨干网络 + 投影层 的输出)。
  • decoder_inputs_embeds (形状为 (batch_size, num_queries, hidden_size)torch.FloatTensor可选) — 可选地,您可以选择直接传递嵌入表示,而不是用零张量初始化查询。
  • labels (长度为 (batch_size,)list[Dict]可选) — 用于计算二分匹配损失的标签。字典列表,每个字典至少包含以下两个键:“class_labels”和“boxes”(分别表示批次中图像的类别标签和边界框)。类别标签本身应为长度为 (图像中边界框的数量,)torch.LongTensor,边界框应为形状为 (图像中边界框的数量, 4)torch.FloatTensor
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。更多详细信息请参见返回张量中的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。更多详细信息请参见返回张量中的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回

transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutputtuple(torch.FloatTensor)

一个 transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutputtorch.FloatTensor 元组(如果传递 return_dict=Falseconfig.return_dict=False),包含根据配置 (DeformableDetrConfig) 和输入的不同元素。

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

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

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

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

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

  • init_reference_points (torch.FloatTensor, 形状为 (batch_size, num_queries, 4)) — 通过 Transformer 解码器发送的初始参考点。

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

  • intermediate_hidden_states (torch.FloatTensor, 形状为 (batch_size, config.decoder_layers, num_queries, hidden_size)) — 堆叠的中间隐藏状态(解码器每层的输出)。

  • intermediate_reference_points (torch.FloatTensor, 形状为 (batch_size, config.decoder_layers, num_queries, 4)) — 堆叠的中间参考点(解码器每层的参考点)。

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

    解码器在每一层输出时的隐藏状态以及初始嵌入输出。

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

    解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。

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

    解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均。

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

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

    编码器在每一层输出时的隐藏状态以及初始嵌入输出。

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

    编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均。

  • enc_outputs_class (形状为 (batch_size, sequence_length, config.num_labels)torch.FloatTensor, 可选, 当 config.with_box_refine=Trueconfig.two_stage=True 时返回) — 预测的边界框分数,其中得分最高的 config.two_stage_num_proposals 个边界框在第一阶段被选为区域提案。边界框二元分类(即前景和背景)的输出。

  • enc_outputs_coord_logits (形状为 (batch_size, sequence_length, 4)torch.FloatTensor, 可选, 当 config.with_box_refine=Trueconfig.two_stage=True 时返回) — 第一阶段预测边界框坐标的 logits。

DeformableDetrForObjectDetection 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward pass 的配方需要在此函数中定义,但之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。

示例

>>> from transformers import AutoImageProcessor, DeformableDetrForObjectDetection
>>> 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("SenseTime/deformable-detr")
>>> model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr")

>>> 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.5, 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 cat with confidence 0.8 at location [16.5, 52.84, 318.25, 470.78]
Detected cat with confidence 0.789 at location [342.19, 24.3, 640.02, 372.25]
Detected remote with confidence 0.633 at location [40.79, 72.78, 176.76, 117.25]
< > 在 GitHub 上更新