Transformers 文档

Deformable DETR

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Deformable DETR

PyTorch

概述

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

该论文的摘要如下:

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

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

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

使用技巧

  • 训练 Deformable DETR 相当于训练原始 DETR 模型。 有关演示 notebook,请参见下面的资源部分。

资源

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

对象检测

如果你有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核! 该资源最好展示一些新的东西,而不是重复现有资源。

DeformableDetrImageProcessor

class transformers.DeformableDetrImageProcessor

< >

( format: typing.Union[str, transformers.image_utils.AnnotationFormat] = <AnnotationFormat.COCO_DETECTION: 'coco_detection'> do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float]] = None image_std: typing.Union[float, typing.List[float]] = None do_convert_annotations: typing.Optional[bool] = None do_pad: bool = True pad_size: typing.Optional[typing.Dict[str, int]] = None **kwargs )

参数

  • format (str, 可选, 默认为 "coco_detection") — 注释的数据格式。 “coco_detection” 或 “coco_panoptic” 之一。
  • do_resize (bool, 可选, 默认为 True) — 控制是否将图像的 (高度,宽度) 尺寸调整为指定的 size。 可以被 preprocess 方法中的 do_resize 参数覆盖。
  • size (Dict[str, int] 可选, 默认为 {"shortest_edge" -- 800, "longest_edge": 1333}): 调整大小后图像的 (height, width) 尺寸大小。 可以被 preprocess 方法中的 size 参数覆盖。 可用选项有:
    • {"height": int, "width": int}: 图像将被调整为精确尺寸 (height, width)。 请勿保持宽高比。
    • {"shortest_edge": int, "longest_edge": int}: 图像将被调整为最大尺寸,同时保持宽高比,并保持最短边小于或等于 shortest_edge,最长边小于或等于 longest_edge
    • {"max_height": int, "max_width": int}: 图像将被调整为最大尺寸,同时保持宽高比,并保持高度小于或等于 max_height,宽度小于或等于 max_width
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BILINEAR) — 如果调整图像大小,则使用的重采样过滤器。
  • do_rescale (bool, 可选, 默认为 True) — 控制是否按指定的比例 rescale_factor 缩放图像。 可以被 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果缩放图像,则使用的缩放因子。 可以被 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize — 控制是否标准化图像。 可以被 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatList[float], 可选, 默认为 IMAGENET_DEFAULT_MEAN) — 标准化图像时使用的均值。 可以是单个值或值列表,每个通道一个值。 可以被 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatList[float], 可选, 默认为 IMAGENET_DEFAULT_STD) — 用于归一化图像的标准差值。可以是单个值或值列表,每个通道一个值。可以被 preprocess 方法中的 image_std 参数覆盖。
  • do_convert_annotations (bool, 可选, 默认为 True) — 控制是否将注释转换为 DETR 模型期望的格式。将边界框转换为 (center_x, center_y, width, height) 格式,并在 [0, 1] 范围内。可以被 preprocess 方法中的 do_convert_annotations 参数覆盖。
  • do_pad (bool, 可选, 默认为 True) — 控制是否填充图像。可以被 preprocess 方法中的 do_pad 参数覆盖。如果为 True,则将在图像的底部和右侧应用零填充。如果提供了 pad_size,图像将被填充到指定的尺寸。否则,图像将被填充到批次中的最大高度和宽度。
  • pad_size (Dict[str, int], 可选) — 将图像填充到的尺寸 {"height": int, "width" int}。必须大于预处理提供的任何图像尺寸。如果未提供 pad_size,则图像将填充到批次中最大的高度和宽度。

构建 Deformable DETR 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: typing.Union[dict[str, typing.Union[int, str, list[dict]]], typing.List[dict[str, typing.Union[int, str, list[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] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None pad_size: typing.Optional[typing.Dict[str, int]] = None **kwargs )

参数

  • images (ImageInput) — 要预处理的图像或一批图像。 期望像素值范围为 0 到 255 的单个或一批图像。如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • annotations (AnnotationTypeList[AnnotationType], 可选) — 与图像或一批图像关联的注释列表。如果注释用于目标检测,则注释应为包含以下键的字典:
    • “image_id” (int): 图像 ID。
    • “annotations” (List[Dict]): 图像的注释列表。每个注释都应是一个字典。图像可以没有注释,在这种情况下,列表应为空。如果注释用于分割,则注释应为包含以下键的字典:
    • “image_id” (int): 图像 ID。
    • “segments_info” (List[Dict]): 图像的分割列表。每个分割都应是一个字典。图像可以没有分割,在这种情况下,列表应为空。
    • “file_name” (str): 图像的文件名。
  • return_segmentation_masks (bool, 可选, 默认为 self.return_segmentation_masks) — 是否返回分割掩码。
  • masks_path (strpathlib.Path, 可选) — 包含分割掩码的目录路径。
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], 可选, 默认为 self.size) — 调整大小后图像的 (height, width) 尺寸大小。可用选项包括:
    • {"height": int, "width": int}: 图像将被调整为精确尺寸 (height, width)。不保持宽高比。
    • {"shortest_edge": int, "longest_edge": int}: 图像将被调整为最大尺寸,同时保持宽高比,并保持最短边小于或等于 shortest_edge,最长边小于或等于 longest_edge
    • {"max_height": int, "max_width": int}: 图像将被调整为最大尺寸,同时保持宽高比,并保持高度小于或等于 max_height,宽度小于或等于 max_width
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 调整图像大小时要使用的重采样滤波器。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否缩放图像。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 缩放图像时要使用的缩放因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否归一化图像。
  • do_convert_annotations (bool, 可选, 默认为 self.do_convert_annotations) — 是否将注释转换为模型期望的格式。将边界框从 (top_left_x, top_left_y, width, height) 格式转换为 (center_x, center_y, width, height) 格式,并使用相对坐标。
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 归一化图像时要使用的均值。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 归一化图像时要使用的标准差。
  • do_pad (bool, 可选, 默认为 self.do_pad) — 是否填充图像。如果为 True,则将在图像的底部和右侧应用零填充。如果提供了 pad_size,图像将被填充到指定的尺寸。否则,图像将被填充到批次中的最大高度和宽度。
  • format (strAnnotationFormat, 可选, 默认为 self.format) — 注释的格式。
  • return_tensors (strTensorType, 可选, 默认为 self.return_tensors) — 要返回的张量类型。如果为 None,将返回图像列表。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。 可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: (num_channels, height, width) 格式的图像。
    • "channels_last"ChannelDimension.LAST: (height, width, num_channels) 格式的图像。
    • Unset: 使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。 如果未设置,则通道维度格式将从输入图像推断。 可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: (num_channels, height, width) 格式的图像。
    • "channels_last"ChannelDimension.LAST: (height, width, num_channels) 格式的图像。
    • "none"ChannelDimension.NONE: (height, width) 格式的图像。
  • pad_size (Dict[str, int], 可选) — 将图像填充到的尺寸 {"height": int, "width" int}。必须大于预处理提供的任何图像尺寸。如果未提供 pad_size,则图像将填充到批次中最大的高度和宽度。

预处理图像或一批图像,使其可以被模型使用。

post_process_object_detection

< >

( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple]] = None top_k: int = 100 ) List[Dict]

参数

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

返回值

List[Dict]

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

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

DeformableDetrImageProcessorFast

class transformers.DeformableDetrImageProcessorFast

< >

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

参数

  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。可以被 preprocess 方法中的 do_resize 参数覆盖。
  • size (dict, 可选, 默认为 self.size) — 调整大小后输出图像的大小。可以被 preprocess 方法中的 size 参数覆盖。
  • default_to_square (bool, 可选, 默认为 self.default_to_square) — 当调整大小时,如果 size 是整数,是否默认为正方形图像。
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样过滤器。仅当 do_resize 设置为 True 时才有效。可以被 preprocess 方法中的 resample 参数覆盖。
  • do_center_crop (bool, 可选, 默认为 self.do_center_crop) — 是否将图像中心裁剪为指定的 crop_size。可以被 preprocess 方法中的 do_center_crop 覆盖。
  • crop_size (Dict[str, int] 可选, 默认为 self.crop_size) — 应用 center_crop 后输出图像的大小。可以被 preprocess 方法中的 crop_size 覆盖。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否按指定的比例因子 rescale_factor 重新缩放图像。可以被 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 self.rescale_factor) — 如果重新缩放图像,则使用的比例因子。仅当 do_rescale 设置为 True 时才有效。可以被 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否标准化图像。可以被 preprocess 方法中的 do_normalize 参数覆盖。 可以被 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 如果标准化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度为图像中通道的数量。可以被 preprocess 方法中的 image_mean 参数覆盖。 可以被 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 如果标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度为图像中通道的数量。可以被 preprocess 方法中的 image_std 参数覆盖。 可以被 preprocess 方法中的 image_std 参数覆盖。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • return_tensors (strTensorType, 可选, 默认为 self.return_tensors) — 如果设置为 pt,则返回堆叠张量,否则返回张量列表。
  • data_format (ChannelDimensionstr, 可选, 默认为 self.data_format) — 仅支持 ChannelDimension.FIRST。为与慢速处理器兼容而添加。
  • input_data_format (ChannelDimensionstr, 可选, 默认为 self.input_data_format) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为(num_channels,height,width)。
    • "channels_last"ChannelDimension.LAST:图像格式为(height,width,num_channels)。
    • "none"ChannelDimension.NONE:图像格式为(height,width)。
  • device (torch.device, 可选, 默认为 self.device) — 处理图像的设备。如果未设置,则设备从输入图像推断。
  • format (str, 可选, 默认为 AnnotationFormat.COCO_DETECTION) — 注释的数据格式。为 “coco_detection” 或 “coco_panoptic” 之一。
  • do_convert_annotations (bool, 可选, 默认为 True) — 控制是否将注释转换为 DEFORMABLE_DETR 模型期望的格式。将边界框转换为 (center_x, center_y, width, height) 格式,并在 [0, 1] 范围内。可以被 preprocess 方法中的 do_convert_annotations 参数覆盖。
  • do_pad (bool, optional, defaults to True) — 控制是否填充图像。可以被 preprocess 方法中的 do_pad 参数覆盖。如果为 True,则将在图像的底部和右侧应用零填充。如果提供了 pad_size,则图像将被填充到指定的尺寸。否则,图像将被填充到批次中最大高度和宽度。
  • pad_size (Dict[str, int], optional) — 要将图像填充到的尺寸 {"height": int, "width" int}。必须大于预处理提供的任何图像尺寸。如果未提供 pad_size,则图像将填充到批次中最大的高度和宽度。
  • return_segmentation_masks (bool, optional, defaults to False) — 是否返回分割掩码。

构建一个快速的 DeformableDetr 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: typing.Union[dict[str, typing.Union[int, str, list[dict]]], typing.List[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_deformable_detr_fast.DeformableDetrFastImageProcessorKwargs] )

参数

  • images (ImageInput) — 要预处理的图像。 期望是像素值范围为 0 到 255 的单张或批量图像。 如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (Dict[str, int], optional, defaults to self.size) — 描述模型接受的最大输入尺寸。
  • resample (PILImageResampling or InterpolationMode, optional, defaults to self.resample) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 之一。 仅在 do_resize 设置为 True 时有效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否对图像进行中心裁剪。
  • crop_size (Dict[str, int], optional, defaults to self.crop_size) — 应用 center_crop 后输出图像的尺寸。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否重新缩放图像。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的重新缩放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化。
  • image_mean (float or List[float], optional, defaults to self.image_mean) — 用于归一化的图像均值。 仅在 do_normalize 设置为 True 时有效。
  • image_std (float or List[float], optional, defaults to self.image_std) — 用于归一化的图像标准差。 仅在 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, optional, defaults to self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • return_tensors (str or TensorType, optional, defaults to self.return_tensors) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。
  • data_format (ChannelDimension or str, optional, defaults to self.data_format) — 仅支持 ChannelDimension.FIRST。 添加此项是为了与慢速处理器兼容。
  • input_data_format (ChannelDimension or str, optional, defaults to self.input_data_format) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像中推断。 可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。
  • device (torch.device, optional, defaults to self.device) — 用于处理图像的设备。 如果未设置,则设备从输入图像中推断。
  • annotations (AnnotationType or List[AnnotationType], optional) — 与图像或批量图像关联的标注列表。如果标注用于目标检测,则标注应为包含以下键的字典:
    • “image_id” (int):图像 ID。
    • “annotations” (List[Dict]):图像标注列表。每个标注都应是一个字典。图像可以没有标注,在这种情况下,列表应为空。如果标注用于分割,则标注应为包含以下键的字典:
    • “image_id” (int):图像 ID。
    • “segments_info” (List[Dict]):图像分割列表。每个分割都应是一个字典。图像可以没有分割,在这种情况下,列表应为空。
    • “file_name” (str):图像的文件名。
  • format (str, optional, defaults to AnnotationFormat.COCO_DETECTION) — 标注的数据格式。 “coco_detection” 或 “coco_panoptic” 之一。
  • do_convert_annotations (bool, optional, defaults to True) — 控制是否将标注转换为 DEFORMABLE_DETR 模型期望的格式。 将边界框转换为 (center_x, center_y, width, height) 格式,并在 [0, 1] 范围内。 可以被 preprocess 方法中的 do_convert_annotations 参数覆盖。
  • do_pad (bool, optional, defaults to True) — 控制是否填充图像。可以被 preprocess 方法中的 do_pad 参数覆盖。如果为 True,则将在图像的底部和右侧应用零填充。如果提供了 pad_size,则图像将被填充到指定的尺寸。否则,图像将被填充到批次中最大高度和宽度。
  • pad_size (Dict[str, int], optional) — 要将图像填充到的尺寸 {"height": int, "width" int}。必须大于预处理提供的任何图像尺寸。如果未提供 pad_size,则图像将填充到批次中最大的高度和宽度。
  • return_segmentation_masks (bool, optional, defaults to False) — 是否返回分割掩码。
  • masks_path (str or pathlib.Path, optional) — 包含分割掩码的目录路径。

预处理图像或批量图像。

post_process_object_detection

< >

( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple]] = None top_k: int = 100 ) List[Dict]

参数

  • outputs (DetrObjectDetectionOutput) — Raw outputs of the model.
  • threshold (float, optional) — Score threshold to keep object detection predictions.
  • target_sizes (torch.Tensor or List[Tuple[int, int]], optional) — Tensor of shape (batch_size, 2) or list of tuples (Tuple[int, int]) containing the target size (height, width) of each image in the batch. If left to None, predictions will not be resized.
  • top_k (int, optional, defaults to 100) — Keep only top k bounding boxes before filtering by thresholding.

返回值

List[Dict]

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

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

DeformableDetrFeatureExtractor

class transformers.DeformableDetrFeatureExtractor

源文件

( *args **kwargs )

__call__

源文件

( images **kwargs )

预处理单张图像或一批图像。

post_process_object_detection

源文件

( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple]] = None top_k: int = 100 ) List[Dict]

参数

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

返回值

List[Dict]

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

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

DeformableDetrConfig

class transformers.DeformableDetrConfig

源文件

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

参数

  • use_timm_backbone (bool, 可选, 默认为 True) — 是否使用 timm 库作为骨干网络。如果设置为 False,将使用 AutoBackbone API。
  • backbone_config (PretrainedConfigdict, 可选) — 骨干模型的配置。仅在 use_timm_backbone 设置为 False 时使用,在这种情况下,它将默认为 ResNetConfig()
  • num_channels (int, 可选, 默认为 3) — 输入通道的数量。
  • num_queries (int, 可选, 默认为 300) — 对象查询的数量,即检测槽的数量。这是 DeformableDetrModel 在单张图像中可以检测到的最大对象数量。如果 two_stage 设置为 True,我们将使用 two_stage_num_proposals 代替。
  • d_model (int, 可选, 默认为 256) — 层的维度。
  • encoder_layers (int, 可选, 默认为 6) — 编码器层数。
  • decoder_layers (int, 可选, 默认为 6) — 解码器层数。
  • encoder_attention_heads (int, 可选, 默认为 8) — Transformer 编码器中每个注意力层的注意力头数。
  • decoder_attention_heads (int, optional, defaults to 8) — Transformer 解码器中每个注意力层的注意力头数。
  • decoder_ffn_dim (int, optional, defaults to 1024) — 解码器中“中间”层(通常称为前馈层)的维度。
  • encoder_ffn_dim (int, optional, defaults to 1024) — 解码器中“中间”层(通常称为前馈层)的维度。
  • activation_function (str or function, optional, defaults to "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) — 全连接层内部激活值的 dropout 比率。
  • init_std (float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • init_xavier_std (float, optional, defaults to 1) — 用于 HM Attention map 模块中 Xavier 初始化增益的缩放因子。
  • encoder_layerdrop (float, optional, defaults to 0.0) — 编码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](see https://arxiv.org/abs/1909.11556)。
  • auxiliary_loss (bool, optional, defaults to False) — 是否使用辅助解码损失(每个解码器层的损失)。
  • position_embedding_type (str, optional, defaults to "sine") — 要在图像特征之上使用的位置嵌入类型。可以是 "sine""learned" 之一。
  • backbone (str, optional, defaults to "resnet50") — 当 backbone_configNone 时,要使用的骨干网络的名称。如果 use_pretrained_backboneTrue,这将从 timm 或 transformers 库加载相应的预训练权重。如果 use_pretrained_backboneFalse,这将加载骨干网络的配置,并使用该配置以随机权重初始化骨干网络。
  • use_pretrained_backbone (bool, optional, defaults to True) — 是否对骨干网络使用预训练权重。
  • backbone_kwargs (dict, optional) — 从检查点加载时要传递给 AutoBackbone 的关键字参数,例如 {'out_indices': (0, 1, 2, 3)}。如果设置了 backbone_config,则不能指定此参数。
  • dilation (bool, optional, defaults to False) — 是否用空洞卷积替换最后一个卷积块 (DC5) 中的步幅。仅当 use_timm_backbone = True 时才支持。
  • class_cost (float, optional, defaults to 1) — 匈牙利匹配成本中分类错误的相对权重。
  • bbox_cost (float, optional, defaults to 5) — 匈牙利匹配成本中边界框坐标 L1 误差的相对权重。
  • giou_cost (float, optional, defaults to 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, defaults to 2) — 对象检测损失中广义 IoU 损失的相对权重。
  • eos_coefficient (float, optional, defaults to 0.1) — 对象检测损失中 ‘no-object’ 类的相对分类权重。
  • num_feature_levels (int, optional, defaults to 4) — 输入特征层级的数量。
  • encoder_n_points (int, optional, defaults to 4) — 编码器中每个注意力头的每个特征层级中采样的键的数量。
  • decoder_n_points (int, optional, defaults to 4) — 解码器中每个注意力头的每个特征层级中采样的键的数量。
  • two_stage (bool, optional, defaults to False) — 是否应用两阶段可变形 DETR,其中区域提议也由可变形 DETR 的变体生成,这些变体进一步馈送到解码器以进行迭代边界框细化。
  • two_stage_num_proposals (int, optional, defaults to 300) — 要生成的区域提议的数量,如果 two_stage 设置为 True
  • with_box_refine (bool, optional, defaults to False) — 是否应用迭代边界框细化,其中每个解码器层都基于前一层的预测来细化边界框。
  • focal_alpha (float, optional, defaults to 0.25) — Focal loss 中的 Alpha 参数。
  • disable_custom_kernels (bool, optional, defaults to False) — 禁用自定义 CUDA 和 CPU 内核的使用。此选项对于 ONNX 导出是必要的,因为 PyTorch ONNX 导出不支持自定义内核。

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

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

示例

>>> from transformers import DeformableDetrConfig, DeformableDetrModel

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

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

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

DeformableDetrModel

class transformers.DeformableDetrModel

< >

( config: DeformableDetrConfig )

参数

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

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

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

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

forward

< >

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

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。 如果您提供填充,默认情况下将忽略填充。

    像素值可以使用 AutoImageProcessor 获取。 有关详细信息,请参阅 DeformableDetrImageProcessor.call()

  • pixel_mask (torch.LongTensor,形状为 (batch_size, height, width)可选) — 用于避免对填充像素值执行注意力的掩码。 在 [0, 1] 中选择的掩码值:

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

    什么是注意力掩码?

  • decoder_attention_mask (torch.FloatTensor,形状为 (batch_size, num_queries)可选) — 默认情况下不使用。 可用于掩码对象查询。
  • 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,形状为 (batch_size, sequence_length, hidden_size)可选) — 可选地,您可以选择直接传递图像的扁平化表示,而不是传递扁平化的特征图(骨干网络 + 投影层的输出)。
  • decoder_inputs_embeds (torch.FloatTensor,形状为 (batch_size, num_queries, hidden_size)可选) — 可选地,您可以选择直接传递嵌入表示,而不是使用零张量初始化查询。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

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

一个 transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutputtorch.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 元组(embeddings 输出一个,每一层输出一个),形状为 (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 元组(embeddings 输出一个,每一层输出一个),形状为 (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=Trueconfig.two_stage=True 时返回) — 预测的边界框分数,其中前 config.two_stage_num_proposals 个评分边界框在第一阶段被选为区域提议。 边界框二元分类(即前景和背景)的输出。
  • enc_outputs_coord_logits (torch.FloatTensor,形状为 (batch_size, sequence_length, 4), 可选, 当 config.with_box_refine=Trueconfig.two_stage=True 时返回) — 第一阶段中预测的边界框坐标的 Logits。

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

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

示例

>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
>>> model = DeformableDetrModel.from_pretrained("SenseTime/deformable-detr")

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

>>> outputs = model(**inputs)

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

DeformableDetrForObjectDetection

class transformers.DeformableDetrForObjectDetection

< >

( config: DeformableDetrConfig )

参数

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

Deformable DETR 模型(由骨干网络和编码器-解码器 Transformer 组成),顶部带有对象检测 head,用于诸如 COCO 检测之类的任务。

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

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

forward

< >

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

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。 如果您提供填充,默认情况下将忽略填充。

    像素值可以使用 AutoImageProcessor 获取。 有关详细信息,请参阅 DeformableDetrImageProcessor.call()

  • pixel_mask (torch.LongTensor,形状为 (batch_size, height, width)可选) — 用于避免对填充像素值执行注意力的掩码。掩码值选自 [0, 1]

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

    什么是注意力掩码?

  • decoder_attention_mask (torch.FloatTensor,形状为 (batch_size, num_queries)可选) — 默认情况下不使用。可用于掩码对象查询。
  • 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,形状为 (batch_size, sequence_length, hidden_size)可选) — 可选地,您可以选择直接传递图像的扁平化表示,而不是传递扁平化的特征图(主干网络 + 投影层)的输出。
  • decoder_inputs_embeds (torch.FloatTensor,形状为 (batch_size, num_queries, hidden_size)可选) — 可选地,您可以选择直接传递嵌入表示,而不是使用零张量初始化查询。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。详见返回张量下的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。详见返回张量下的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是普通元组。
  • labels (List[Dict],长度为 (batch_size,)可选) — 用于计算二分图匹配损失的标签。字典列表,每个字典至少包含以下 2 个键:“class_labels”和“boxes”(分别表示批次中图像的类别标签和边界框)。类别标签本身应为长度为 (图像中边界框的数量,)torch.LongTensor,而 boxes 的形状为 (图像中边界框的数量, 4)torch.FloatTensor

返回值

transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutputtuple(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)并且提供了标签。它是字典列表,其中包含每个解码器层的上述两个键(logitspred_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 元组(embeddings 输出一个,每一层输出一个),形状为 (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 元组(embeddings 输出一个,每一层输出一个),形状为 (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=Trueconfig.two_stage=True 时返回) — 预测的边界框分数,其中前 config.two_stage_num_proposals 个评分边界框在第一阶段被选为区域提议。 边界框二元分类(即前景和背景)的输出。
  • enc_outputs_coord_logits (torch.FloatTensor,形状为 (batch_size, sequence_length, 4), 可选, 当 config.with_box_refine=Trueconfig.two_stage=True 时返回) — 第一阶段中预测的边界框坐标的 Logits。

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

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

示例

>>> from transformers import AutoImageProcessor, DeformableDetrForObjectDetection
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("SenseTime/deformable-detr")
>>> model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr")

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

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
...     0
... ]
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
...     box = [round(i, 2) for i in box.tolist()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected cat with confidence 0.8 at location [16.5, 52.84, 318.25, 470.78]
Detected cat with confidence 0.789 at location [342.19, 24.3, 640.02, 372.25]
Detected remote with confidence 0.633 at location [40.79, 72.78, 176.76, 117.25]
< > 在 GitHub 上更新