可变形DETR
概述
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可以在训练轮次减少10倍的情况下,实现比DETR更好的性能(尤其是在小物体上)。在COCO基准上的大量实验证明了我们方法的有效性。
![drawing](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/deformable_detr_architecture.png)
使用提示
资源
一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用Deformable DETR。
- 关于在自定义数据集上进行推理和微调的演示笔记本,适用于DeformableDetrForObjectDetection,可以在这里找到。
- 用于微调DeformableDetrForObjectDetection的脚本,可以使用Trainer或Accelerate,可以在这里找到。
- 另请参阅:Object detection task guide。
如果您有兴趣提交资源以包含在此处,请随时打开一个 Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
DeformableDetrImageProcessor
类 transformers.DeformableDetrImageProcessor
< source >( format: typing.Union[str, transformers.image_utils.AnnotationFormat] =
参数
- format (
str
, 可选, 默认为"coco_detection"
) — 注释的数据格式。可选值为“coco_detection”或“coco_panoptic”。 - do_resize (
bool
, 可选, 默认为True
) — 控制是否将图像的(高度,宽度)尺寸调整为指定的size
。可以在preprocess
方法中通过do_resize
参数进行覆盖。 - size (
Dict[str, int]
optional, defaults to{"shortest_edge" -- 800, "longest_edge": 1333}
): Size of the image’s(height, width)
dimensions after resizing. Can be overridden by thesize
parameter in thepreprocess
method. Available options are:{"height": int, "width": int}
: The image will be resized to the exact size(height, width)
. Do NOT keep the aspect ratio.{"shortest_edge": int, "longest_edge": int}
: The image will be resized to a maximum size respecting the aspect ratio and keeping the shortest edge less or equal toshortest_edge
and the longest edge less or equal tolongest_edge
.{"max_height": int, "max_width": int}
: The image will be resized to the maximum size respecting the aspect ratio and keeping the height less or equal tomax_height
and the width less or equal tomax_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
,图像将被填充到批次中最大的高度和宽度。
构建一个可变形DETR图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] annotations: typing.Union[typing.Dict[str, typing.Union[int, str, typing.List[typing.Dict]]], typing.List[typing.Dict[str, typing.Union[int, str, typing.List[typing.Dict]]]], NoneType] = None return_segmentation_masks: bool = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None do_resize: typing.Optional[bool] = None size: typing.Optional[typing.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.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] =
参数
- 图像 (
ImageInput
) — 要预处理的图像或图像批次。期望输入单个或批次的图像,像素值范围为0到255。如果传入的图像的像素值在0到1之间,请设置do_rescale=False
. - annotations (
AnnotationType
orList[AnnotationType]
, optional) — List of annotations associated with the image or batch of images. If annotation is for object detection, the annotations should be a dictionary with the following keys:- “image_id” (
int
): The image id. - “annotations” (
List[Dict]
): List of annotations for an image. Each annotation should be a dictionary. An image can have no annotations, in which case the list should be empty. If annotation is for segmentation, the annotations should be a dictionary with the following keys: - “image_id” (
int
): The image id. - “segments_info” (
List[Dict]
): List of segments for an image. Each segment should be a dictionary. An image can have no segments, in which case the list should be empty. - “file_name” (
str
): The file name of the image.
- “image_id” (
- return_segmentation_masks (
bool
, optional, defaults to self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str
orpathlib.Path
, optional) — 包含分割掩码的目录路径。 - do_resize (
bool
, optional, defaults to self.do_resize) — 是否调整图像大小. - size (
Dict[str, int]
, optional, defaults to self.size) — Size of the image’s(height, width)
dimensions after resizing. Available options are:{"height": int, "width": int}
: The image will be resized to the exact size(height, width)
. Do NOT keep the aspect ratio.{"shortest_edge": int, "longest_edge": int}
: The image will be resized to a maximum size respecting the aspect ratio and keeping the shortest edge less or equal toshortest_edge
and the longest edge less or equal tolongest_edge
.{"max_height": int, "max_width": int}
: The image will be resized to the maximum size respecting the aspect ratio and keeping the height less or equal tomax_height
and the width less or equal tomax_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) — 是否对图像进行归一化处理。 - 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
orList[float]
, optional, defaults to 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
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"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
< source >( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple]] = None top_k: int = 100 ) → List[Dict]
参数
- 输出 (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, optional) — 用于保留物体检测预测的分数阈值。 - target_sizes (
torch.Tensor
或List[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
类 transformers.DeformableDetrImageProcessorFast
< source >( format: typing.Union[str, transformers.image_utils.AnnotationFormat] =
参数
- format (
str
, 可选, 默认为AnnotationFormat.COCO_DETECTION
) — 注释的数据格式。可选值为“coco_detection”或“coco_panoptic”。 - do_resize (
bool
, 可选, 默认为True
) — 控制是否将图像的(高度,宽度)尺寸调整为指定的size
。可以在preprocess
方法中通过do_resize
参数进行覆盖。 - size (
Dict[str, int]
optional, defaults to{"shortest_edge" -- 800, "longest_edge": 1333}
): Size of the image’s(height, width)
dimensions after resizing. Can be overridden by thesize
parameter in thepreprocess
method. Available options are:{"height": int, "width": int}
: The image will be resized to the exact size(height, width)
. Do NOT keep the aspect ratio.{"shortest_edge": int, "longest_edge": int}
: The image will be resized to a maximum size respecting the aspect ratio and keeping the shortest edge less or equal toshortest_edge
and the longest edge less or equal tolongest_edge
.{"max_height": int, "max_width": int}
: The image will be resized to the maximum size respecting the aspect ratio and keeping the height less or equal tomax_height
and the width less or equal tomax_width
.
- resample (
PILImageResampling
, optional, defaults toPILImageResampling.BILINEAR
) — 如果调整图像大小,使用的重采样过滤器。 - do_rescale (
bool
, 可选, 默认为True
) — 控制是否通过指定的比例rescale_factor
重新缩放图像。可以在preprocess
方法中通过do_rescale
参数覆盖此设置。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,则使用的缩放因子。可以在preprocess
方法中通过rescale_factor
参数覆盖此值。 - do_normalize (
bool
, 可选, 默认为True
) — 控制是否对图像进行归一化。可以在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图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] annotations: typing.Union[typing.Dict[str, typing.Union[int, str, typing.List[typing.Dict]]], typing.List[typing.Dict[str, typing.Union[int, str, typing.List[typing.Dict]]]], NoneType] = None return_segmentation_masks: bool = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None do_resize: typing.Optional[bool] = None size: typing.Optional[typing.Dict[str, int]] = None resample: typing.Union[PIL.Image.Resampling, ForwardRef('F.InterpolationMode'), NoneType] = 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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.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] =
参数
- 图像 (
ImageInput
) — 要预处理的图像或图像批次。期望输入单个或批次的图像,像素值范围为0到255。如果传入的图像的像素值在0到1之间,请设置do_rescale=False
. - annotations (
AnnotationType
orList[AnnotationType]
, optional) — List of annotations associated with the image or batch of images. If annotation is for object detection, the annotations should be a dictionary with the following keys:- “image_id” (
int
): The image id. - “annotations” (
List[Dict]
): List of annotations for an image. Each annotation should be a dictionary. An image can have no annotations, in which case the list should be empty. If annotation is for segmentation, the annotations should be a dictionary with the following keys: - “image_id” (
int
): The image id. - “segments_info” (
List[Dict]
): List of segments for an image. Each segment should be a dictionary. An image can have no segments, in which case the list should be empty. - “file_name” (
str
): The file name of the image.
- “image_id” (
- return_segmentation_masks (
bool
, optional, defaults to self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str
orpathlib.Path
, optional) — 包含分割掩码的目录路径。 - do_resize (
bool
, optional, defaults to self.do_resize) — 是否调整图像大小. - size (
Dict[str, int]
, optional, defaults to self.size) — Size of the image’s(height, width)
dimensions after resizing. Available options are:{"height": int, "width": int}
: The image will be resized to the exact size(height, width)
. Do NOT keep the aspect ratio.{"shortest_edge": int, "longest_edge": int}
: The image will be resized to a maximum size respecting the aspect ratio and keeping the shortest edge less or equal toshortest_edge
and the longest edge less or equal tolongest_edge
.{"max_height": int, "max_width": int}
: The image will be resized to the maximum size respecting the aspect ratio and keeping the height less or equal tomax_height
and the width less or equal tomax_width
.
- resample (
PILImageResampling
或InterpolationMode
, 可选, 默认为 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) — 是否对图像进行归一化。 - 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
orList[float]
, optional, defaults to 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
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"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
< source >( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple]] = None top_k: int = 100 ) → List[Dict]
参数
- 输出 (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, optional) — 用于保留物体检测预测的分数阈值。 - target_sizes (
torch.Tensor
或List[Tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或包含批次中每个图像目标大小(高度,宽度)的元组列表 (Tuple[int, int]
)。如果留空,预测将不会调整大小。 - top_k (
int
, optional, 默认为 100) — 在通过阈值过滤之前,仅保留前 k 个边界框。
返回
List[Dict]
一个字典列表,每个字典包含模型预测的批次中每张图像的分数、标签和框。
将DeformableDetrForObjectDetection的原始输出转换为最终边界框,格式为(top_left_x, top_left_y, bottom_right_x, bottom_right_y)。仅支持PyTorch。
DeformableDetrFeatureExtractor
预处理一张图像或一批图像。
post_process_object_detection
< source >( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple]] = None top_k: int = 100 ) → List[Dict]
参数
- 输出 (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, optional) — 用于保留物体检测预测的分数阈值。 - target_sizes (
torch.Tensor
或List[Tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或包含批次中每个图像目标大小(高度,宽度)的元组列表 (Tuple[int, int]
)。如果留空,预测将不会调整大小。 - top_k (
int
, optional, defaults to 100) — 在通过阈值过滤之前,仅保留前k个边界框。
返回
List[Dict]
一个字典列表,每个字典包含模型预测的批次中每张图像的分数、标签和框。
将DeformableDetrForObjectDetection的原始输出转换为最终边界框,格式为(top_left_x, top_left_y, bottom_right_x, bottom_right_y)。仅支持PyTorch。
DeformableDetrConfig
类 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
, optional, 默认为 3) — 输入通道的数量。 - num_queries (
int
, 可选, 默认为 300) — 对象查询的数量,即检测槽。这是 DeformableDetrModel 在单张图片中可以检测到的最大对象数量。如果two_stage
设置为True
,我们则使用two_stage_num_proposals
代替。 - d_model (
int
, optional, defaults to 256) — 层的维度. - encoder_layers (
int
, optional, defaults to 6) — 编码器层数. - decoder_layers (
int
, optional, defaults to 6) — 解码器层数. - encoder_attention_heads (
int
, optional, 默认为 8) — Transformer 编码器中每个注意力层的注意力头数。 - decoder_attention_heads (
int
, optional, defaults to 8) — Transformer解码器中每个注意力层的注意力头数。 - decoder_ffn_dim (
int
, optional, defaults to 1024) — 解码器中“中间”(通常称为前馈)层的维度。 - encoder_ffn_dim (
int
, optional, defaults to 1024) — 解码器中“中间”(通常称为前馈)层的维度。 - activation_function (
str
或function
, 可选, 默认为"relu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - dropout (
float
, optional, defaults to 0.1) — 嵌入层、编码器和池化器中所有全连接层的dropout概率。 - attention_dropout (
float
, optional, defaults to 0.0) — 注意力概率的dropout比率. - activation_dropout (
float
, optional, defaults to 0.0) — 全连接层内激活函数的丢弃比例。 - init_std (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - init_xavier_std (
float
, optional, defaults to 1) — 用于HM注意力图模块中Xavier初始化增益的缩放因子。 - encoder_layerdrop (
float
, optional, 默认为 0.0) — 编码器的LayerDrop概率。有关更多详细信息,请参阅[LayerDrop论文](see https://arxiv.org/abs/1909.11556)。 - auxiliary_loss (
bool
, 可选, 默认为False
) — 是否使用辅助解码损失(每个解码器层的损失)。 - position_embedding_type (
str
, optional, defaults to"sine"
) — 用于图像特征之上的位置嵌入类型。可选值为"sine"
或"learned"
. - backbone (
str
, optional, 默认为"resnet50"
) — 当backbone_config
为None
时使用的骨干网络名称。如果use_pretrained_backbone
为True
,这将从 timm 或 transformers 库加载相应的预训练权重。如果use_pretrained_backbone
为False
,这将加载骨干网络的配置并使用该配置初始化具有随机权重的骨干网络。 - use_pretrained_backbone (
bool
, optional, defaults toTrue
) — 是否使用预训练的权重作为骨干网络。 - backbone_kwargs (
dict
, 可选) — 从检查点加载时传递给AutoBackbone的关键字参数 例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定此参数。 - dilation (
bool
, 可选, 默认为False
) — 是否在最后一个卷积块(DC5)中用扩张替换步幅。仅在use_timm_backbone
=True
时支持。 - class_cost (
float
, optional, 默认为 1) — 匈牙利匹配成本中分类错误的相对权重。 - bbox_cost (
float
, optional, defaults to 5) — 匈牙利匹配成本中边界框坐标的L1误差的相对权重。 - giou_cost (
float
, optional, 默认为 2) — 在匈牙利匹配成本中,边界框的广义 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, 默认为 2) — 在目标检测损失中,广义 IoU 损失的相对权重。 - eos_coefficient (
float
, optional, defaults to 0.1) — 在目标检测损失中,‘无对象’类别的相对分类权重。 - num_feature_levels (
int
, 可选, 默认为 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
, 可选, 默认为 300) — 在two_stage
设置为True
的情况下,生成的区域建议数量。 - with_box_refine (
bool
, 可选, 默认为False
) — 是否应用迭代边界框细化,其中每个解码器层根据前一层的预测细化边界框。 - focal_alpha (
float
, optional, 默认为 0.25) — 焦点损失中的 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
类 transformers.DeformableDetrModel
< source >( config: DeformableDetrConfig )
参数
- config (DeformableDetrConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的Deformable DETR模型(由骨干网络和编码器-解码器Transformer组成)输出原始隐藏状态,顶部没有任何特定的头部。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( 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.DeformableDetrModelOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — Pixel values. Padding will be ignored by default should you provide it.可以使用AutoImageProcessor获取像素值。详情请参见DeformableDetrImageProcessor.call()。
- pixel_mask (
torch.LongTensor
of shape(batch_size, height, width)
, optional) — Mask to avoid performing attention on padding pixel values. Mask values selected in[0, 1]
:- 1 for pixels that are real (i.e. not masked),
- 0 for pixels that are padding (i.e. masked).
- decoder_attention_mask (
torch.FloatTensor
of shape(batch_size, num_queries)
, optional) — 默认不使用。可用于屏蔽对象查询。 - encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — 元组由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
)last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
, 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力机制中。 - 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
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个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 (
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, num_queries, hidden_size)
。解码器每层输出的隐藏状态加上初始嵌入输出。 - decoder_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, num_queries, num_queries)
。解码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。 - cross_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_queries, num_heads, 4, 4)
。解码器交叉注意力层的注意力权重,经过注意力 softmax 后,用于计算交叉注意力头中的加权平均值。 - encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 模型编码器最后一层输出的隐藏状态序列。 - 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_queries, num_heads, 4, 4)
。编码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。 - enc_outputs_class (
torch.FloatTensor
形状为(batch_size, sequence_length, config.num_labels)
, 可选, 当config.with_box_refine=True
和config.two_stage=True
时返回) — 预测的边界框分数,其中前config.two_stage_num_proposals
个得分最高的边界框在第一阶段被选为区域提议。边界框二元分类的输出(即前景和背景)。 - enc_outputs_coord_logits (
torch.FloatTensor
形状为(batch_size, sequence_length, 4)
, 可选, 当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
类 transformers.DeformableDetrForObjectDetection
< source >( config: DeformableDetrConfig )
参数
- config (DeformableDetrConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
可变形DETR模型(由骨干网络和编码器-解码器Transformer组成),顶部带有目标检测头,适用于COCO检测等任务。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( 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[typing.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.DeformableDetrObjectDetectionOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — Pixel values. Padding will be ignored by default should you provide it.可以使用AutoImageProcessor获取像素值。详情请参见DeformableDetrImageProcessor.call()。
- pixel_mask (
torch.LongTensor
of shape(batch_size, height, width)
, optional) — Mask to avoid performing attention on padding pixel values. Mask values selected in[0, 1]
:- 1 for pixels that are real (i.e. not masked),
- 0 for pixels that are padding (i.e. masked).
- decoder_attention_mask (
torch.FloatTensor
of shape(batch_size, num_queries)
, optional) — 默认不使用。可用于屏蔽对象查询。 - encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — 元组由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
) 组成last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
, 可选) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。 - 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
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
List[Dict]
长度为(batch_size,)
, 可选) — 用于计算二分匹配损失的标签。字典列表,每个字典至少包含以下两个键:'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 (
torch.FloatTensor
形状为(1,)
, 可选, 当提供labels
时返回) — 总损失,作为类别预测的负对数似然(交叉熵)和 边界框损失的线性组合。后者定义为 L1 损失和广义 尺度不变 IoU 损失的线性组合。 - loss_dict (
Dict
, 可选) — 包含各个损失的字典。用于记录日志。 - logits (
torch.FloatTensor
形状为(batch_size, num_queries, num_classes + 1)
) — 所有查询的分类 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]
, 可选) — 可选,仅在激活辅助损失时返回(即config.auxiliary_loss
设置为True
) 并且提供了标签。它是一个字典列表,包含每个解码器层的上述两个键(logits
和pred_boxes
)。 - last_hidden_state (
torch.FloatTensor
形状为(batch_size, num_queries, hidden_size)
, 可选) — 模型解码器最后一层输出的隐藏状态序列。 - decoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入输出 + 一个用于每层输出)形状为(batch_size, num_queries, hidden_size)
。解码器在每层输出处的隐藏状态 加上初始嵌入输出。 - decoder_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个)形状为(batch_size, num_heads, num_queries, num_queries)
。解码器的注意力权重,在注意力 softmax 之后,用于计算加权 平均在自注意力头中。 - cross_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个)形状为(batch_size, num_queries, num_heads, 4, 4)
。 解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算 加权平均在交叉注意力头中。 - encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 模型编码器最后一层输出的隐藏状态序列。 - 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, sequence_length, num_heads, 4, 4)
。编码器的注意力权重,在注意力 softmax 之后,用于计算加权平均 在自注意力头中。 - 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)
) — 堆叠的中间参考点(解码器每层的参考点)。 - init_reference_points (
torch.FloatTensor
形状为(batch_size, num_queries, 4)
) — 通过 Transformer 解码器发送的初始参考点。 - enc_outputs_class (
torch.FloatTensor
形状为(batch_size, sequence_length, config.num_labels)
, 可选, 当config.with_box_refine=True
和config.two_stage=True
时返回) — 预测的边界框分数,其中前config.two_stage_num_proposals
个得分最高的边界框被 选为第一阶段的区域提议。边界框二元分类的输出(即 前景和背景)。 - enc_outputs_coord_logits (
torch.FloatTensor
形状为(batch_size, sequence_length, 4)
, 可选, 当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]