Transformers documentation
Deformable DETR
该模型于 2020-10-08 在 HF papers 上发布,并于 2022-09-14 贡献至 Hugging Face Transformers。
Deformable DETR
Deformable DETR 通过引入可变形注意力模块,对原始的 DETR 进行了改进。该机制选择性地关注参考点周围的一小组关键采样点。它提升了训练速度并提高了精度。
Deformable DETR architecture. Taken from the original paper. 您可以在 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")import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForObjectDetection
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 = AutoModelForObjectDetection.from_pretrained("SenseTime/deformable-detr", device_map="auto")
# prepare image for the model
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([image.size[::-1]]), threshold=0.3)
for result in results:
for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
score, label = score.item(), label_id.item()
box = [round(i, 2) for i in box.tolist()]
print(f"{model.config.id2label[label]}: {score:.2f} {box}")资源
- 请参阅这组notebooks,了解如何在自定义数据集上对DeformableDetrForObjectDetection进行推理和微调。
DeformableDetrImageProcessor
class transformers.DeformableDetrImageProcessor
< source >( **kwargs: *<class 'transformers.models.deformable_detr.image_processing_deformable_detr.DeformableDetrImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'shortest_edge' -- 800, 'longest_edge': 1333}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool,kwargs,可选,默认为True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - format (
str, kwargs, optional, 默认为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参数进行覆盖。
构建 DeformableDetrImageProcessor 图像处理器。
预处理
< source >( 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 = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class '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,可选) — 包含分割掩码的目录路径。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - format (
str, kwargs, optional, 默认为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参数进行覆盖。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_object_detection
< source >( outputsthreshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] = Nonetop_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
< source >( **kwargs: *<class 'transformers.models.deformable_detr.image_processing_pil_deformable_detr.DeformableDetrImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'shortest_edge' -- 800, 'longest_edge': 1333}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool,kwargs,可选,默认为True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - format (
str, kwargs, optional, 默认为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参数进行覆盖。
构建 DeformableDetrImageProcessor 图像处理器。
预处理
< source >( 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 = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class '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],可选)— 根据应用于图像的填充进行转换的注释。 - return_segmentation_masks (
bool,可选,默认为self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str或pathlib.Path,可选) — 包含分割掩码的目录路径。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - format (
str, kwargs, optional, 默认为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参数进行覆盖。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_object_detection
< source >( outputsthreshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] = Nonetop_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
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneis_encoder_decoder: bool = Truebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonenum_channels: int = 3num_queries: int = 300max_position_embeddings: int = 1024encoder_layers: int = 6encoder_ffn_dim: int = 1024encoder_attention_heads: int = 8decoder_layers: int = 6decoder_ffn_dim: int = 1024decoder_attention_heads: int = 8encoder_layerdrop: float | int = 0.0activation_function: str = 'relu'd_model: int = 256dropout: float | int = 0.1attention_dropout: float | int = 0.0activation_dropout: float | int = 0.0init_std: float = 0.02init_xavier_std: float = 1.0return_intermediate: bool = Trueauxiliary_loss: bool = Falseposition_embedding_type: str = 'sine'dilation: bool = Falsenum_feature_levels: int = 4encoder_n_points: int = 4decoder_n_points: int = 4two_stage: bool = Falsetwo_stage_num_proposals: int = 300with_box_refine: bool = Falseclass_cost: int = 1bbox_cost: int = 5giou_cost: int = 2mask_loss_coefficient: int = 1dice_loss_coefficient: int = 1bbox_loss_coefficient: int = 5giou_loss_coefficient: int = 2eos_coefficient: float = 0.1focal_alpha: float = 0.25disable_custom_kernels: bool = Falsetie_word_embeddings: bool = True )
参数
- is_encoder_decoder (
bool,可选,默认为True) — 指示该模型是否用作编码器/解码器。 - backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - num_queries (
int, 可选,默认为 300) — 对象查询的数量,即检测槽位。这是 DeformableDetrModel 在单张图像中可检测到的最大对象数量。如果two_stage设置为True,则使用two_stage_num_proposals。 - max_position_embeddings (
int,可选,默认为1024) — 该模型可能使用的最大序列长度。 - encoder_layers (
int,可选,默认为6) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - encoder_ffn_dim (
int,可选,默认为1024) — 编码器中“中间”(通常称为前馈)层的维度。 - encoder_attention_heads (
int,可选,默认为8) — Transformer 编码器中每个注意力层的注意力头数量。 - decoder_layers (
int, 可选,默认为6) — Transformer 解码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - decoder_ffn_dim (
int,可选,默认为1024) — 解码器中“中间”(通常称为前馈)层的维度。 - decoder_attention_heads (
int,可选,默认为8) — Transformer 解码器中每个注意力层的注意力头数量。 - encoder_layerdrop (
Union[float, int],可选,默认值为0.0) — 编码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](参见 https://huggingface.co/papers/1909.11556)。 - activation_function (
str,可选,默认为relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - d_model (
int,可选,默认为256) — 编码器层和池化层的维度大小。 - dropout (
Union[float, int],可选,默认为0.1) — 所有 dropout 层的比率。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - activation_dropout (
Union[float, int],可选,默认为0.0) — 全连接层中激活值的 dropout 比率。 - init_std (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - init_xavier_std (
float,可选,默认为1.0) — 用于交叉注意力权重 Xavier 初始化的缩放因子。 - return_intermediate (
bool,可选,默认为 True) — 是否返回中间状态 - auxiliary_loss (
bool,可选,默认为False) — 是否使用辅助解码损失(即每个解码器层的损失)。 - position_embedding_type (
str,可选,默认为"sine") — 用于叠加在图像特征之上的位置嵌入类型。取值为"sine"或"learned"之一。 - dilation (
bool,可选,默认为False) — 是否将最后一个卷积块(DC5)中的 stride 替换为 dilation。仅在use_timm_backbone=True时支持。 - 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) — 是否应用迭代式边界框细化,即每个解码器层基于上一层的预测结果来细化边界框。 - class_cost (
int,可选,默认为1) — 匈牙利匹配代价中分类误差的相对权重。 - bbox_cost (
int,可选,默认为5) — 匈牙利匹配代价中 L1 边界框误差的相对权重。 - giou_cost (
int,可选,默认为2) — 匈牙利匹配代价中广义 IoU 损失的相对权重。 - mask_loss_coefficient (
int,可选,默认为1) — 全景分割损失中焦点损失的相对权重。 - dice_loss_coefficient (
int,可选,默认为1) — 在全景分割损失中,Dice 损失的相对权重。 - bbox_loss_coefficient (
int,可选,默认为5) — 全景分割损失中 L1 边界框损失的相对权重。 - giou_loss_coefficient (
int,可选,默认值为2) — 全景分割损失中广义 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
< source >( config: DeformableDetrConfig )
参数
- config (DeformableDetrConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
原始的 Deformable DETR 模型(由骨干网络和编码器-解码器 Transformer 组成),输出原始的 hidden-states,顶部未添加任何特定的 head。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: FloatTensorpixel_mask: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.FloatTensor] = Noneencoder_outputs: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DeformableDetrModelOutput or 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),可选) — 可选地,除了传入展平的特征图(backbone + 投影层的输出)之外,你还可以选择直接传入图像的展平表示。 - 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__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
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],可选,在传入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,可选)— 模型编码器最后一层输出的隐藏状态序列。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.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(形状为
(batch_size, sequence_length, 4)的torch.FloatTensor,可选,当config.with_box_refine=True且config.two_stage=True时返回) — 第一阶段中预测的边界框坐标的 logits。
示例:
>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> from PIL import Image
>>> from huggingface_hub.utils 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
类 transformers.DeformableDetrForObjectDetection
< source >( config: DeformableDetrConfig )
参数
- config (DeformableDetrConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Deformable DETR 模型(由骨干网络和编码器-解码器 Transformer 组成),顶部带有目标检测头,用于 COCO 检测等任务。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: FloatTensorpixel_mask: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.FloatTensor] = Noneencoder_outputs: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonedecoder_inputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DeformableDetrObjectDetectionOutput or 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),可选) — 可选地,除了传入展平的特征图(backbone + 投影层的输出)之外,你还可以选择直接传入图像的展平表示。 - decoder_inputs_embeds (
torch.FloatTensor,形状为(batch_size, num_queries, hidden_size),可选) — 可选地,你可以选择直接传入嵌入表示,而不是用零张量来初始化查询。 - labels (
list[Dict],长度为(batch_size,),可选) — 用于计算二部图匹配损失的标签。一个字典列表,每个字典至少包含以下 2 个键:‘class_labels’ 和 ‘boxes’(分别对应批次中某张图像的分类标签和边界框)。分类标签本身应是一个长度为(number of bounding boxes in the image,)的torch.LongTensor,边界框应是一个形状为(number of bounding boxes in the image, 4)的torch.FloatTensor。
返回值
DeformableDetrObjectDetectionOutput 或 tuple(torch.FloatTensor)
DeformableDetrObjectDetectionOutput 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。
DeformableDetrForObjectDetection 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.FloatTensor,形状为(1,),可选,在提供labels时返回)) — 总损失,是类别预测的负对数似然(交叉熵)与边界框损失的线性组合。后者定义为 L1 损失与广义尺度不变 IoU 损失的线性组合。loss_dict (
Dict,可选) — 包含各项单独损失的字典。适用于日志记录。logits(形状为
(batch_size, num_queries, num_classes + 1)的torch.FloatTensor)— 所有查询的分类 logits(包含 no-object)。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)且提供了标签时返回。它是一个字典列表,包含每个解码器层的上述两个键(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,可选)— 模型编码器最后一层输出的隐藏状态序列。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(形状为
(batch_size, num_queries, 4)的torch.FloatTensor)— 通过 Transformer 解码器传递的初始参考点。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)— 堆叠的中间参考点(解码器每一层的参考点)。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(形状为
(batch_size, sequence_length, 4)的torch.FloatTensor,可选,当config.with_box_refine=True且config.two_stage=True时返回) — 第一阶段中预测的边界框坐标的 logits。
示例:
>>> from transformers import AutoImageProcessor, DeformableDetrForObjectDetection
>>> from PIL import Image
>>> from huggingface_hub.utils 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 = 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]