Deformable DETR
概述
Deformable DETR 模型在 Deformable DETR: Deformable Transformers for End-to-End Object Detection 中被提出,作者是 Xizhou Zhu, Weijie Su, Lewei Lu, Bin Li, Xiaogang Wang, Jifeng Dai。Deformable DETR 通过利用一种新的可变形注意力模块,缓解了原始 DETR 的收敛速度慢和特征空间分辨率有限的问题,该模块仅关注参考点周围的一小组关键采样点。
以下是论文的摘要
最近提出了 DETR,以消除目标检测中对许多手工设计的组件的需求,同时展示出良好的性能。然而,由于 Transformer 注意力模块在处理图像特征图方面的局限性,它存在收敛速度慢和特征空间分辨率有限的问题。为了缓解这些问题,我们提出了 Deformable DETR,其注意力模块仅关注参考点周围的一小组关键采样点。Deformable DETR 可以比 DETR 获得更好的性能(尤其是在小物体上),而训练 epoch 次数减少了 10 倍。在 COCO 基准上的大量实验证明了我们方法的有效性。

使用技巧
资源
以下是官方 Hugging Face 和社区(🌎 表示)资源的列表,可帮助您开始使用 Deformable DETR。
- 有关 DeformableDetrForObjectDetection 在自定义数据集上进行推理 + 微调的演示 notebook 可以在这里找到。
- 使用 Trainer 或 Accelerate 微调 DeformableDetrForObjectDetection 的脚本可以在这里找到。
- 另请参阅:目标检测任务指南。
如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核!该资源应理想地展示一些新的东西,而不是复制现有资源。
DeformableDetrImageProcessor
class transformers.DeformableDetrImageProcessor
< source >( format: Union = <AnnotationFormat.COCO_DETECTION: 'coco_detection'> do_resize: bool = True size: Dict = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: Union = 0.00392156862745098 do_normalize: bool = True image_mean: Union = None image_std: Union = None do_convert_annotations: Optional = None do_pad: bool = True pad_size: Optional = 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}
): 调整大小后图像的(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 (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,则使用的缩放因子。可以被preprocess
方法中的rescale_factor
参数覆盖。 do_normalize — 控制是否对图像进行归一化。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为IMAGENET_DEFAULT_MEAN
) — 归一化图像时使用的均值。可以是单个值或值列表,每个通道一个值。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[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
) — 控制是否填充图像。可以被preprocess
方法中的do_pad
参数覆盖。如果为True
,则将在图像的底部和右侧填充零。如果提供了pad_size
,则图像将被填充到指定的尺寸。否则,图像将被填充到批次的最大高度和宽度。 - pad_size (
Dict[str, int]
, 可选) — 将图像填充到的尺寸{"height": int, "width" int}
。必须大于预处理提供的任何图像尺寸。如果未提供pad_size
,则图像将填充到批次中最大的高度和宽度。
构建 Deformable DETR 图像处理器。
preprocess
< source >( images: Union annotations: Union = None return_segmentation_masks: bool = None masks_path: Union = None do_resize: Optional = None size: Optional = None resample = None do_rescale: Optional = None rescale_factor: Union = None do_normalize: Optional = None do_convert_annotations: Optional = None image_mean: Union = None image_std: Union = None do_pad: Optional = None format: Union = None return_tensors: Union = None data_format: Union = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None pad_size: Optional = None **kwargs )
参数
- images (
ImageInput
) — 要预处理的图像或批量图像。期望像素值范围为 0 到 255 的单个或批量图像。如果传入的图像的像素值介于 0 和 1 之间,请设置do_rescale=False
。 - annotations (
AnnotationType
或List[AnnotationType]
, 可选) — 与图像或批量图像关联的注释列表。如果注释用于目标检测,则注释应为包含以下键的字典:- “image_id” (
int
):图像 ID。 - “annotations” (
List[Dict]
):图像的注释列表。每个注释都应该是字典。图像可以没有注释,在这种情况下,列表应为空。如果注释用于分割,则注释应为包含以下键的字典: - “image_id” (
int
):图像 ID。 - “segments_info” (
List[Dict]
):图像的分割列表。每个分割都应该是字典。图像可以没有分割,在这种情况下,列表应为空。 - “file_name” (
str
):图像的文件名。
- “image_id” (
- return_segmentation_masks (
bool
, 可选, 默认为 self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str
或pathlib.Path
, 可选) — 包含分割掩码的目录路径。 - do_resize (
bool
, 可选, 默认为 self.do_resize) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为 self.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
, 可选, 默认为 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 (
float
或List[float]
, 可选, 默认为 self.image_mean) — 归一化图像时使用的均值。 - image_std (
float
或List[float]
, 可选, 默认为 self.image_std) — 归一化图像时使用的标准差。 - do_pad (
bool
, 可选, 默认为 self.do_pad) — 是否填充图像。如果为True
,则将使用零填充图像的底部和右侧。如果提供了pad_size
,则图像将被填充到指定的尺寸。否则,图像将被填充到批次中的最大高度和宽度。 - format (
str
或AnnotationFormat
, 可选, 默认为 self.format) — 注释的格式。 - return_tensors (
str
或TensorType
, 可选, 默认为 self.return_tensors) — 返回的张量类型。如果为None
,将返回图像列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: `(通道数, 高度, 宽度)` 格式的图像。"channels_last"
或ChannelDimension.LAST
: `(高度, 宽度, 通道数)` 格式的图像。- Unset: 使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: `(通道数, 高度, 宽度)` 格式的图像。"channels_last"
或ChannelDimension.LAST
: `(高度, 宽度, 通道数)` 格式的图像。"none"
或ChannelDimension.NONE
: `(高度, 宽度)` 格式的图像。
- pad_size (
Dict[str, int]
, 可选) — 要将图像填充到的尺寸{"height": int, "width" int}
。必须大于预处理提供的任何图像尺寸。如果未提供pad_size
,则图像将被填充到批次中的最大高度和宽度。
预处理单个图像或一批图像,以便模型可以使用它们。
post_process_object_detection
< source >( outputs threshold: float = 0.5 target_sizes: Union = None top_k: int = 100 ) → List[Dict]
参数
- outputs (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, 可选) — 保留物体检测预测的分数阈值。 - target_sizes (
torch.Tensor
或List[Tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或元组列表 (Tuple[int, int]
),包含批次中每个图像的目标尺寸(高度,宽度)。如果留空为None
,则预测不会被调整大小。 - top_k (
int
, 可选, 默认为 100) — 在通过阈值过滤之前,仅保留前 k 个边界框。
返回
List[Dict]
字典列表,每个字典包含模型预测的批次中图像的分数、标签和框。
将 DeformableDetrForObjectDetection 的原始输出转换为 (左上角 x, 左上角 y, 右下角 x, 右下角 y)
格式的最终边界框。仅支持 PyTorch。
DeformableDetrFeatureExtractor
预处理单个图像或一批图像。
post_process_object_detection
< source >( outputs threshold: float = 0.5 target_sizes: Union = None top_k: int = 100 ) → List[Dict]
参数
- outputs (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, 可选) — 保留物体检测预测的分数阈值。 - target_sizes (
torch.Tensor
或List[Tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或元组列表 (Tuple[int, int]
),包含批次中每张图像的目标大小(高度,宽度)。如果保留为 None,则预测不会被调整大小。 - top_k (
int
, 可选, 默认为 100) — 在通过阈值过滤之前,仅保留前 k 个边界框。
返回
List[Dict]
字典列表,每个字典包含模型预测的批次中图像的分数、标签和框。
将 DeformableDetrForObjectDetection 的原始输出转换为 (左上角 x, 左上角 y, 右下角 x, 右下角 y)
格式的最终边界框。仅支持 PyTorch。
DeformableDetrConfig
class transformers.DeformableDetrConfig
< source >( 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 (
PretrainedConfig
或dict
, 可选) — 骨干模型的配置。仅在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 (
str
或function
, 可选, 默认为"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) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - init_xavier_std (
float
, 可选, 默认为 1) — 用于 HM Attention map 模块中 Xavier 初始化增益的缩放因子。 - encoder_layerdrop (
float
, 可选, 默认为 0.0) — 编码器的 LayerDrop 概率。有关更多详细信息,请参见 [LayerDrop 论文](see https://arxiv.org/abs/1909.11556)。 - auxiliary_loss (
bool
, 可选, 默认为False
) — 是否使用辅助解码损失(每个解码器层的损失)。 - position_embedding_type (
str
, 可选, 默认为"sine"
) — 要在图像特征之上使用的位置嵌入类型。可以是"sine"
或"learned"
之一。 - backbone (
str
, 可选, 默认为"resnet50"
) — 当backbone_config
为None
时要使用的骨干网络名称。如果use_pretrained_backbone
为True
,这将从 timm 或 transformers 库加载相应的预训练权重。如果use_pretrained_backbone
为False
,这将加载骨干网络的配置,并使用该配置以随机权重初始化骨干网络。 - use_pretrained_backbone (
bool
, 可选, 默认为True
) — 是否为骨干网络使用预训练权重。 - backbone_kwargs (
dict
, optional) — 从检查点加载时,要传递给 AutoBackbone 的关键字参数,例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定此项。 - dilation (
bool
, optional, defaults toFalse
) — 是否在最后一个卷积块 (DC5) 中用空洞卷积替换步幅。仅当use_timm_backbone
=True
时才支持。 - class_cost (
float
, optional, defaults to 1) — 在 Hungarian 匹配成本中,分类错误的相对权重。 - bbox_cost (
float
, optional, defaults to 5) — 在 Hungarian 匹配成本中,边界框坐标的 L1 误差的相对权重。 - giou_cost (
float
, optional, defaults to 2) — 在 Hungarian 匹配成本中,边界框的广义 IoU 损失的相对权重。 - mask_loss_coefficient (
float
, optional, defaults to 1) — 在全景分割损失中,Focal 损失的相对权重。 - dice_loss_coefficient (
float
, optional, defaults to 1) — 在全景分割损失中,DICE/F-1 损失的相对权重。 - bbox_loss_coefficient (
float
, optional, defaults to 5) — 在对象检测损失中,L1 边界框损失的相对权重。 - giou_loss_coefficient (
float
, optional, defaults to 2) — 在对象检测损失中,广义 IoU 损失的相对权重。 - eos_coefficient (
float
, optional, defaults to 0.1) — 在对象检测损失中,“无对象”类别的相对分类权重。 - num_feature_levels (
int
, optional, defaults to 4) — 输入特征级别的数量。 - encoder_n_points (
int
, optional, defaults to 4) — 编码器中每个注意力头的每个特征级别中采样的键的数量。 - decoder_n_points (
int
, optional, defaults to 4) — 解码器中每个注意力头的每个特征级别中采样的键的数量。 - two_stage (
bool
, optional, defaults toFalse
) — 是否应用两阶段可变形 DETR,其中区域提议也由可变形 DETR 的变体生成,这些提议进一步馈送到解码器以进行迭代边界框细化。 - two_stage_num_proposals (
int
, optional, defaults to 300) — 要生成的区域提议的数量,如果two_stage
设置为True
。 - with_box_refine (
bool
, optional, defaults toFalse
) — 是否应用迭代边界框细化,其中每个解码器层都根据上一层的预测来细化边界框。 - focal_alpha (
float
, optional, defaults to 0.25) — focal loss 中的 Alpha 参数。 - disable_custom_kernels (
bool
, optional, defaults toFalse
) — 禁用自定义 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
< source >( config: DeformableDetrConfig )
参数
- config (DeformableDetrConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
裸 Deformable DETR 模型(由骨干网络和编码器-解码器 Transformer 组成),输出原始隐藏状态,顶部没有任何特定的头部。
此模型继承自 PreTrainedModel。查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( pixel_values: FloatTensor pixel_mask: Optional = None decoder_attention_mask: Optional = None encoder_outputs: Optional = None inputs_embeds: Optional = None decoder_inputs_embeds: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutput
or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。如果您提供填充,默认情况下会忽略填充。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 DeformableDetrImageProcessor.call()。
- pixel_mask (
torch.LongTensor
of shape(batch_size, height, width)
, optional) — 用于避免对填充像素值执行注意力的掩码。在[0, 1]
中选择的掩码值:- 1 代表真实像素(即未掩码),
- 0 代表填充像素(即已掩码)。
- decoder_attention_mask (
torch.FloatTensor
of shape(batch_size, num_queries)
, optional) — 默认情况下不使用。可用于掩码对象查询。 - encoder_outputs (
tuple(tuple(torch.FloatTensor)
, optional) — 元组由 (last_hidden_state
, optional:hidden_states
, optional:attentions
) 组成last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
,optional) 是编码器最后一层输出的隐藏状态序列。在解码器的交叉注意力中使用。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 或者,您可以选择直接传递图像的扁平化表示,而不是传递扁平化的特征图(骨干网络 + 投影层的输出)。 - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, num_queries, hidden_size)
, optional) — 或者,您可以选择直接传递嵌入表示,而不是使用零张量初始化查询。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。 更多细节请参阅返回张量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是一个普通的元组。
返回
transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutput
或 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DeformableDetrConfig) 和输入。
- init_reference_points (形状为
(batch_size, num_queries, 4)
的torch.FloatTensor
) — 通过 Transformer 解码器发送的初始参考点。 - last_hidden_state (形状为
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
) — 模型解码器最后一层的输出处的隐藏状态序列。 - intermediate_hidden_states (形状为
(batch_size, config.decoder_layers, num_queries, hidden_size)
的torch.FloatTensor
) — 堆叠的中间隐藏状态(解码器每一层的输出)。 - intermediate_reference_points (形状为
(batch_size, config.decoder_layers, num_queries, 4)
的torch.FloatTensor
) — 堆叠的中间参考点(解码器每一层的参考点)。 - decoder_hidden_states (
tuple(torch.FloatTensor)
, optional, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组 (每个解码器层的输出以及初始嵌入输出各一个),形状为(batch_size, num_queries, hidden_size)
。 解码器在每一层输出以及初始嵌入输出处的隐藏状态。 - decoder_attentions (
tuple(torch.FloatTensor)
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_heads, num_queries, num_queries)
。 解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。 - cross_attentions (
tuple(torch.FloatTensor)
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_queries, num_heads, 4, 4)
。 解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。 - encoder_last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, optional) — 模型编码器最后一层的输出处的隐藏状态序列。 - encoder_hidden_states (
tuple(torch.FloatTensor)
, optional, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组 (每个编码器层的输出以及初始嵌入输出各一个),形状为(batch_size, sequence_length, hidden_size)
。 编码器在每一层输出以及初始嵌入输出处的隐藏状态。 - encoder_attentions (
tuple(torch.FloatTensor)
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_queries, num_heads, 4, 4)
。 编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。 - enc_outputs_class (形状为
(batch_size, sequence_length, config.num_labels)
的torch.FloatTensor
, optional, 当config.with_box_refine=True
和config.two_stage=True
时返回) — 预测的边界框分数,其中前config.two_stage_num_proposals
个评分边界框在第一阶段被选为区域提议。 边界框二元分类(即前景和背景)的输出。 - enc_outputs_coord_logits (形状为
(batch_size, sequence_length, 4)
的torch.FloatTensor
, optional, 当config.with_box_refine=True
和config.two_stage=True
时返回) — 第一阶段中预测的边界框坐标的 logits。
DeformableDetrModel 前向方法,覆盖了 __call__
特殊方法。
尽管前向传递的配方需要在该函数内定义,但应在此之后调用 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: Optional = None decoder_attention_mask: Optional = None encoder_outputs: Optional = None inputs_embeds: Optional = None decoder_inputs_embeds: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 像素值。 默认情况下,如果您提供填充,则会忽略填充。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 DeformableDetrImageProcessor.call()。
- pixel_mask (形状为
(batch_size, height, width)
的torch.LongTensor
, optional) — 用于避免对填充像素值执行注意力的掩码。 在[0, 1]
中选择的掩码值:- 1 表示真实的像素(即未被掩码),
- 0 表示填充像素(即被掩码)。
- decoder_attention_mask (形状为
(batch_size, num_queries)
的torch.FloatTensor
, optional) — 默认情况下不使用。 可用于掩码对象查询。 - encoder_outputs (
tuple(tuple(torch.FloatTensor)
, optional) — 元组由 (last_hidden_state
, optional:hidden_states
, optional:attentions
) 组成,形状为(batch_size, sequence_length, hidden_size)
的last_hidden_state
, optional) 是编码器最后一层输出处的隐藏状态序列。 用于解码器的交叉注意力。 - inputs_embeds (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, optional) — 可选地,您可以选择直接传递图像的展平表示,而不是传递展平的特征图(骨干网络 + 投影层的输出)。 - decoder_inputs_embeds (形状为
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是使用零张量初始化查询。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。 更多细节请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。 更多细节请参阅返回张量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是一个普通的元组。 - labels (长度为
(batch_size,)
的List[Dict]
, optional) — 用于计算二分匹配损失的标签。 字典列表,每个字典至少包含以下 2 个键:“class_labels”和“boxes”(分别是批次中图像的类别标签和边界框)。 类别标签本身应为长度为(图像中边界框的数量,)
的torch.LongTensor
,而框应为形状为(图像中边界框的数量, 4)
的torch.FloatTensor
。
返回
transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutput
或 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DeformableDetrConfig) 和输入。
- loss (形状为
(1,)
的torch.FloatTensor
, optional, 当提供labels
时返回) — 总损失,作为类别预测的负对数似然(交叉熵)和边界框损失的线性组合。 后者定义为 L1 损失和广义尺度不变 IoU 损失的线性组合。 - loss_dict (
Dict
, optional) — 包含各个损失的字典。 用于记录日志。 - 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]
, optional) — 可选,仅当辅助损失被激活时返回(即config.auxiliary_loss
设置为True
)并且提供了标签。 它是字典列表,其中包含每个解码器层的上述两个键(logits
和pred_boxes
)。 - last_hidden_state (形状为
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
, optional) — 模型解码器最后一层的输出处的隐藏状态序列。 - decoder_hidden_states (
tuple(torch.FloatTensor)
, optional, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组 (每个解码器层的输出以及初始嵌入输出各一个),形状为(batch_size, num_queries, hidden_size)
。 解码器在每一层输出以及初始嵌入输出处的隐藏状态。 - decoder_attentions (
tuple(torch.FloatTensor)
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_heads, num_queries, num_queries)
。 解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。 - cross_attentions (
tuple(torch.FloatTensor)
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_queries, num_heads, 4, 4)
。 解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。 - encoder_last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, optional) — 模型编码器最后一层的输出处的隐藏状态序列。 - encoder_hidden_states (
tuple(torch.FloatTensor)
, optional, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组 (每个编码器层的输出以及初始嵌入输出各一个),形状为(batch_size, sequence_length, hidden_size)
。 编码器在每一层输出以及初始嵌入输出处的隐藏状态。 - encoder_attentions (
tuple(torch.FloatTensor)
, optional, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, sequence_length, num_heads, 4, 4)
。 编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。 - intermediate_hidden_states (形状为
(batch_size, config.decoder_layers, num_queries, hidden_size)
的torch.FloatTensor
) — 堆叠的中间隐藏状态(解码器每一层的输出)。 - intermediate_reference_points (形状为
(batch_size, config.decoder_layers, num_queries, 4)
的torch.FloatTensor
) — 堆叠的中间参考点(解码器每一层的参考点)。 - init_reference_points (形状为
(batch_size, num_queries, 4)
的torch.FloatTensor
) — 通过 Transformer 解码器发送的初始参考点。 - enc_outputs_class (形状为
(batch_size, sequence_length, config.num_labels)
的torch.FloatTensor
, optional, 当config.with_box_refine=True
和config.two_stage=True
时返回) — 预测的边界框分数,其中前config.two_stage_num_proposals
个评分边界框在第一阶段被选为区域提议。 边界框二元分类(即前景和背景)的输出。 - enc_outputs_coord_logits (形状为
(batch_size, sequence_length, 4)
的torch.FloatTensor
, optional, 当config.with_box_refine=True
和config.two_stage=True
时返回) — 第一阶段中预测的边界框坐标的 logits。
DeformableDetrForObjectDetection 前向方法,覆盖了 __call__
特殊方法。
尽管前向传递的配方需要在该函数内定义,但应在此之后调用 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]