Transformers 文档
可变形 DETR
并获得增强的文档体验
开始使用
该模型于 2020 年 10 月 8 日发表在 HF papers 上,并于 2022 年 9 月 14 日贡献给 Hugging Face Transformers。
Deformable DETR
Deformable DETR 通过使用可变形注意力(deformable attention)模块对原始 DETR 进行了改进。该机制有选择地关注参考点周围的一小部分关键采样点。它提高了训练速度并提升了准确率。
Deformable DETR 架构。摘自原始论文。你可以在 SenseTime 组织下找到所有可用的 Deformable DETR 检查点。
此模型由 nielsr 贡献。
点击右侧侧边栏中的 Deformable DETR 模型,查看更多将 Deformable DETR 应用于不同目标检测和分割任务的示例。
下面的示例演示了如何使用 Pipeline 和 AutoModel 类执行目标检测。
from transformers import pipeline
pipeline = pipeline(
"object-detection",
model="SenseTime/deformable-detr",
device_map=0
)
pipeline("http://images.cocodataset.org/val2017/000000039769.jpg")资源
- 有关在自定义数据集上进行推理和微调 DeformableDetrForObjectDetection 的内容,请参考这套 notebooks。
DeformableDetrImageProcessor
class transformers.DeformableDetrImageProcessor
< 源码 >( **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_deformable_detr.DeformableDetrImageProcessorKwargs] )
参数
- 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参数覆盖。 - ***kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。模型特定的 kwargs 列在上方;请参阅 TypedDict 类以获取支持参数的完整列表。
构建一个 DeformableDetrImageProcessor 图像处理器。
preprocess
< 源码 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = None return_segmentation_masks: bool | None = None masks_path: str | pathlib.Path | None = None **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_deformable_detr.DeformableDetrImageProcessorKwargs] ) → ~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或list[AnnotationType], 可选) — 根据应用于图像的填充进行转换的标注。 - return_segmentation_masks (
bool, 可选, 默认为self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str或pathlib.Path, 可选) — 包含分割掩码的目录路径。 - 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参数覆盖。 - return_tensors (
str或 TensorType, 可选) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - ***kwargs (ImagesKwargs, 可选) — 其他图像预处理选项。模型特定的 kwargs 列在上方;请参阅 TypedDict 类以获取支持参数的完整列表。
返回
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。
post_process_object_detection
< 源码 >( outputs threshold: float = 0.5 target_sizes: transformers.utils.generic.TensorType | list[tuple] = 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 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。仅支持 PyTorch。
DeformableDetrImageProcessorPil
class transformers.DeformableDetrImageProcessorPil
< 源码 >( **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_pil_deformable_detr.DeformableDetrImageProcessorKwargs] )
参数
- 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参数覆盖。 - **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。
构建一个 DeformableDetrImageProcessor 图像处理器。
preprocess
< 源代码 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = None return_segmentation_masks: bool | None = None masks_path: str | pathlib.Path | None = None **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_pil_deformable_detr.DeformableDetrImageProcessorKwargs] ) → ~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或list[AnnotationType], 可选) — 根据应用于图像的填充(padding)进行转换的标注信息。 - return_segmentation_masks (
bool, 可选, 默认为self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str或pathlib.Path, 可选) — 包含分割掩码的目录路径。 - format (
str, kwargs, 可选, 默认为AnnotationFormat.COCO_DETECTION) — 标注数据的格式。可选值为 “coco_detection” 或 “coco_panoptic”。 - do_convert_annotations (
bool, kwargs, 可选, 默认为True) — 控制是否将标注转换为 DEFORMABLE_DETR 模型预期的格式。将边界框转换为(center_x, center_y, width, height)格式且范围在[0, 1]之间。可以通过preprocess方法中的do_convert_annotations参数覆盖。 - return_tensors (
str或 TensorType, 可选) — 如果设置为'pt',则返回堆叠后的张量,否则返回张量列表。 - **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 在上面列出;请参阅 TypedDict 类以获取支持参数的完整列表。
返回
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType], optional) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。
post_process_object_detection
< 源代码 >( outputs threshold: float = 0.5 target_sizes: transformers.utils.generic.TensorType | list[tuple] = 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 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。仅支持 PyTorch。
DeformableDetrConfig
class transformers.DeformableDetrConfig
< 源代码 >( transformers_version: str | None = None architectures: list[str] | None = None output_hidden_states: bool | None = False return_dict: bool | None = True dtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = None chunk_size_feed_forward: int = 0 id2label: dict[int, str] | dict[str, str] | None = None label2id: dict[str, int] | dict[str, str] | None = None problem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = None is_encoder_decoder: bool = True backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None num_channels: int = 3 num_queries: int = 300 max_position_embeddings: int = 1024 encoder_layers: int = 6 encoder_ffn_dim: int = 1024 encoder_attention_heads: int = 8 decoder_layers: int = 6 decoder_ffn_dim: int = 1024 decoder_attention_heads: int = 8 encoder_layerdrop: float | int = 0.0 activation_function: str = 'relu' d_model: int = 256 dropout: float | int = 0.1 attention_dropout: float | int = 0.0 activation_dropout: float | int = 0.0 init_std: float = 0.02 init_xavier_std: float = 1.0 return_intermediate: bool = True auxiliary_loss: bool = False position_embedding_type: str = 'sine' dilation: bool = False num_feature_levels: int = 4 encoder_n_points: int = 4 decoder_n_points: int = 4 two_stage: bool = False two_stage_num_proposals: int = 300 with_box_refine: bool = False class_cost: int = 1 bbox_cost: int = 5 giou_cost: int = 2 mask_loss_coefficient: int = 1 dice_loss_coefficient: int = 1 bbox_loss_coefficient: int = 5 giou_loss_coefficient: int = 2 eos_coefficient: float = 0.1 focal_alpha: float = 0.25 disable_custom_kernels: bool = False tie_word_embeddings: bool = True )
参数
- is_encoder_decoder (
bool, 可选, 默认为True) — 模型是否用作编码器/解码器架构。 - backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig], 可选) — 主干网络(backbone)模型的配置。 - num_channels (
int, 可选, 默认为3) — 输入通道的数量。 - num_queries (
int, 可选, 默认为 300) — 对象查询的数量,即检测槽位。这是 DeformableDetrModel 在单张图像中可以检测到的最大对象数量。如果two_stage设置为True,我们将使用two_stage_num_proposals代替。 - max_position_embeddings (
int, 可选, 默认为1024) — 该模型可能使用的最大序列长度。 - encoder_layers (
int, optional, defaults to6) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - encoder_ffn_dim (
int, optional, defaults to1024) — 编码器中“中间”层(通常称为前馈层)的维度。 - encoder_attention_heads (
int, optional, defaults to8) — Transformer 编码器中每个注意力层的注意力头数量。 - decoder_layers (
int, optional, defaults to6) — Transformer 解码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - decoder_ffn_dim (
int, optional, defaults to1024) — 解码器中“中间”层(通常称为前馈层)的维度。 - decoder_attention_heads (
int, optional, defaults to8) — Transformer 解码器中每个注意力层的注意力头数量。 - encoder_layerdrop (
Union[float, int], optional, defaults to0.0) — 编码器的 LayerDrop 概率。详情请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。 - activation_function (
str, optional, defaults torelu) — 解码器中的非线性激活函数(函数或字符串)。例如:"gelu"、"relu"、"silu"等。 - d_model (
int, optional, defaults to256) — 编码器层和池化层的尺寸大小。 - dropout (
Union[float, int], optional, defaults to0.1) — 所有 dropout 层的比率。 - attention_dropout (
Union[float, int], optional, defaults to0.0) — 注意力概率的 dropout 比率。 - activation_dropout (
Union[float, int], optional, defaults to0.0) — 全连接层内部激活的 dropout 比率。 - init_std (
float, optional, defaults to0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - init_xavier_std (
float, optional, defaults to1.0) — 用于交叉注意力权重 Xavier 初始化的缩放因子。 - return_intermediate (
bool, optional, defaults to True) — 是否返回中间状态。 - auxiliary_loss (
bool, optional, defaults toFalse) — 是否使用辅助解码损失(每个解码器层上的损失)。 - position_embedding_type (
str, optional, defaults to"sine") — 在图像特征之上使用的位置嵌入类型。可选项为"sine"或"learned"。 - dilation (
bool, optional, defaults toFalse) — 是否在最后一个卷积块(DC5)中用空洞卷积(dilation)替换步长(stride)。仅在use_timm_backbone=True时支持。 - num_feature_levels (
int, optional, defaults to 4) — 输入特征的层级数量。 - encoder_n_points (
int, optional, defaults to 4) — 编码器中每个注意力头的每个特征层级采样的键(key)数量。 - decoder_n_points (
int, optional, defaults to 4) — 解码器中每个注意力头的每个特征层级采样的键(key)数量。 - two_stage (
bool, optional, defaults toFalse) — 是否应用两阶段 Deformable DETR,其中区域建议也由 Deformable DETR 的变体生成,并进一步输入到解码器中以进行迭代边界框细化。 - two_stage_num_proposals (
int, optional, defaults to 300) — 在two_stage设置为True的情况下,要生成的区域建议数量。 - with_box_refine (
bool, optional, defaults toFalse) — 是否应用迭代边界框细化,其中每个解码器层根据前一层的预测结果细化边界框。 - class_cost (
int, optional, defaults to1) — 匈牙利匹配代价中分类误差的相对权重。 - bbox_cost (
int, optional, defaults to5) — 匈牙利匹配代价中 L1 边界框误差的相对权重。 - giou_cost (
int, optional, defaults to2) — 匈牙利匹配代价中广义 IoU 损失的相对权重。 - mask_loss_coefficient (
int, optional, defaults to1) — 全景分割损失中 focal loss 的相对权重。 - dice_loss_coefficient (
int, optional, defaults to1) — 全景分割损失中 Dice 损失的相对权重。 - bbox_loss_coefficient (
int, optional, defaults to5) — 全景分割损失中 L1 边界框损失的相对权重。 - giou_loss_coefficient (
int, optional, defaults to2) — 全景分割损失中广义 IoU 损失的相对权重。 - eos_coefficient (
float, 可选, 默认为0.1) — 目标检测损失中“无对象”类别的相对分类权重。 - focal_alpha (
float, 可选, 默认为0.25) — Focal loss 中的 Alpha 参数。 - disable_custom_kernels (
bool, 可选, 默认为False) — 禁用自定义 CUDA 和 CPU 内核。此选项对于 ONNX 导出是必要的,因为 PyTorch ONNX 导出不支持自定义内核。 - tie_word_embeddings (
bool, 可选, 默认为True) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。
这是用于存储 DeformableDetrModel 配置的配置类。它根据指定的参数实例化 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.configDeformableDetrModel
class transformers.DeformableDetrModel
< 源代码 >( config: DeformableDetrConfig )
参数
- config (DeformableDetrConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。请查阅 from_pretrained() 方法以加载模型权重。
原始的 Deformable DETR 模型(由骨干网络和编码器-解码器 Transformer 组成),输出原始隐藏状态,顶部没有任何特定任务的头部。
该模型继承自 PreTrainedModel。请查看超类文档以了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< 源代码 >( pixel_values: FloatTensor pixel_mask: torch.LongTensor | None = None decoder_attention_mask: torch.FloatTensor | None = None encoder_outputs: torch.FloatTensor | None = None inputs_embeds: torch.FloatTensor | None = None decoder_inputs_embeds: torch.FloatTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → DeformableDetrModelOutput 或 tuple(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来处理图像)。 - pixel_mask (
torch.LongTensor,形状为(batch_size, height, width),可选) — 用于避免对填充像素值执行注意力机制的掩码。掩码值在[0, 1]中选择:- 1 表示真实像素(即 未被掩盖),
- 0 表示填充像素(即 被掩盖)。
- decoder_attention_mask (
torch.FloatTensor,形状为(batch_size, num_queries),可选) — 默认情况下未使用。可用于掩盖对象查询(object queries)。 - encoder_outputs (
torch.FloatTensor,可选) — 元组包含 (last_hidden_state, 可选:hidden_states, 可选:attentions)last_hidden_state(形状为(batch_size, sequence_length, hidden_size),可选)是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力机制中。 - inputs_embeds (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,你可以选择直接传递图像的扁平化表示,而不是传递扁平化的特征图(骨干网络+投影层的输出)。 - decoder_inputs_embeds (
torch.FloatTensor,形状为(batch_size, num_queries, hidden_size),可选) — 可选地,你可以选择直接传递嵌入表示,而不是用零张量初始化查询。
返回
DeformableDetrModelOutput 或 tuple(torch.FloatTensor)
一个 DeformableDetrModelOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或者当 config.return_dict=False 时),根据配置(None)和输入包含各种元素。
DeformableDetrModel 的 forward 方法,覆盖了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
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 (
torch.FloatTensorof shape(batch_size, sequence_length, config.num_labels), optional, returned whenconfig.with_box_refine=Trueandconfig.two_stage=True) — 在第一阶段中,预测的边界框分数,其中得分最高的config.two_stage_num_proposals个边界框被选为区域提案。边界框二分类(即前景和背景)的输出。enc_outputs_coord_logits (
torch.FloatTensorof shape(batch_size, sequence_length, 4), optional, returned whenconfig.with_box_refine=Trueandconfig.two_stage=True) — 第一阶段中预测边界框坐标的对数。
示例
>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> 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 Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< 源代码 >( pixel_values: FloatTensor pixel_mask: torch.LongTensor | None = None decoder_attention_mask: torch.FloatTensor | None = None encoder_outputs: torch.FloatTensor | None = None inputs_embeds: torch.FloatTensor | None = None decoder_inputs_embeds: torch.FloatTensor | None = None labels: list[dict] | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → DeformableDetrObjectDetectionOutput 或 tuple(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来处理图像)。 - pixel_mask (
torch.LongTensor,形状为(batch_size, height, width),可选) — 用于避免对填充像素值执行注意力机制的掩码。掩码值在[0, 1]中选择:- 1 表示真实像素(即 未被掩盖),
- 0 表示填充像素(即 被掩盖)。
- decoder_attention_mask (
torch.FloatTensor,形状为(batch_size, num_queries),可选) — 默认情况下未使用。可用于掩盖对象查询(object queries)。 - encoder_outputs (
torch.FloatTensor,可选) — 元组包含 (last_hidden_state, 可选:hidden_states, 可选:attentions)last_hidden_state(形状为(batch_size, sequence_length, hidden_size),可选)是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力机制中。 - inputs_embeds (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,你可以选择直接传递图像的扁平化表示,而不是传递扁平化的特征图(骨干网络+投影层的输出)。 - decoder_inputs_embeds (
torch.FloatTensor,形状为(batch_size, num_queries, hidden_size),可选) — 可选地,你可以选择直接传递嵌入表示,而不是用零张量初始化查询。 - labels (长度为
(batch_size,)的list[Dict],可选) — 用于计算二分匹配损失的标签。由字典组成的列表,每个字典至少包含以下 2 个键:‘class_labels’ 和 ‘boxes’(分别为批次中某张图像的类别标签和边界框)。类别标签本身应当是一个长度为(图像中边界框数量,)的torch.LongTensor,而边界框应当是一个形状为(图像中边界框数量, 4)的torch.FloatTensor。
返回
DeformableDetrObjectDetectionOutput 或 tuple(torch.FloatTensor)
一个 DeformableDetrObjectDetectionOutput 或一个 torch.FloatTensor 元组(如果传入 return_dict=False 或当 config.return_dict=False 时),根据配置(None)和输入包含各种元素。
DeformableDetrForObjectDetection 的 forward 方法,重写了 __call__ 特殊方法。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
loss (
torch.FloatTensorof shape(1,), optional, 当提供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] 范围内。您可以使用~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,可选) — 模型解码器最后一层的输出序列隐藏状态。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 之后,用于计算自注意力头中的加权平均。
init_reference_points (
torch.FloatTensor, 形状为(batch_size, num_queries, 4)) — 通过 Transformer 解码器发送的初始参考点。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)) — 堆叠的中间参考点(解码器每层的参考点)。enc_outputs_class (
torch.FloatTensorof shape(batch_size, sequence_length, config.num_labels), optional, returned whenconfig.with_box_refine=Trueandconfig.two_stage=True) — 在第一阶段中,预测的边界框分数,其中得分最高的config.two_stage_num_proposals个边界框被选为区域提案。边界框二分类(即前景和背景)的输出。enc_outputs_coord_logits (
torch.FloatTensorof shape(batch_size, sequence_length, 4), optional, returned whenconfig.with_box_refine=Trueandconfig.two_stage=True) — 第一阶段中预测边界框坐标的对数。
示例
>>> from transformers import AutoImageProcessor, DeformableDetrForObjectDetection
>>> from PIL import Image
>>> import httpx
>>> from io imoprt BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> 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]