RT-DETR
概述
RT-DETR模型由Wenyu Lv、Yian Zhao、Shangliang Xu、Jinman Wei、Guanzhong Wang、Cheng Cui、Yuning Du、Qingqing Dang、Yi Liu在DETRs Beat YOLOs on Real-time Object Detection中提出。
RT-DETR 是一个目标检测模型,全称为“实时检测变换器”。该模型旨在执行目标检测任务,重点在于实现实时性能的同时保持高准确性。RT-DETR 利用在深度学习各个领域中广受欢迎的变换器架构,处理图像以识别和定位其中的多个对象。
论文的摘要如下:
最近,基于端到端变压器的检测器(DETRs)取得了显著的性能。然而,DETRs高计算成本的问题尚未得到有效解决,限制了它们的实际应用,并阻碍了它们充分利用无需后处理(如非极大值抑制(NMS))的优势。在本文中,我们首先分析了现代实时目标检测器中NMS对推理速度的影响,并建立了一个端到端的速度基准。为了避免NMS引起的推理延迟,我们提出了实时检测变压器(RT-DETR),据我们所知,这是第一个实时端到端目标检测器。具体来说,我们设计了一个高效的混合编码器,通过解耦尺度内交互和跨尺度融合来高效处理多尺度特征,并提出了IoU感知查询选择以改进目标查询的初始化。此外,我们提出的检测器支持通过使用不同的解码器层灵活调整推理速度,而无需重新训练,这有助于实时目标检测器的实际应用。我们的RT-DETR-L在COCO val2017上达到了53.0%的AP,在T4 GPU上达到了114 FPS,而RT-DETR-X达到了54.8%的AP和74 FPS,在速度和准确性上都优于所有相同规模的YOLO检测器。此外,我们的RT-DETR-R50达到了53.1%的AP和108 FPS,在准确性上比DINO-Deformable-DETR-R50高出2.2%的AP,在FPS上高出约21倍。
![drawing](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/rt_detr_overview.png)
该模型版本由rafaelpadilla和sangbumchoi贡献。原始代码可以在这里找到。
使用提示
最初,使用预训练的卷积神经网络处理图像,具体来说,是原始代码中引用的Resnet-D变体。该网络从架构的最后三层提取特征。随后,使用混合编码器将多尺度特征转换为图像特征的序列数组。然后,使用配备辅助预测头的解码器来优化对象查询。此过程有助于直接生成边界框,无需任何额外的后处理即可获取边界框的logits和坐标。
>>> import torch
>>> import requests
>>> from PIL import Image
>>> from transformers import RTDetrForObjectDetection, RTDetrImageProcessor
>>> url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
>>> model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([(image.height, image.width)]), 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}")
sofa: 0.97 [0.14, 0.38, 640.13, 476.21]
cat: 0.96 [343.38, 24.28, 640.14, 371.5]
cat: 0.96 [13.23, 54.18, 318.98, 472.22]
remote: 0.95 [40.11, 73.44, 175.96, 118.48]
remote: 0.92 [333.73, 76.58, 369.97, 186.99]
资源
一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用RT-DETR。
- 用于微调 RTDetrForObjectDetection 的脚本,使用 Trainer 或 Accelerate 可以在 这里 找到。
- 另请参阅:Object detection task guide。
- 关于在自定义数据集上进行推理和微调RT-DETR的Notebooks可以在这里找到。🌎
RTDetrConfig
类 transformers.RTDetrConfig
< source >( initializer_range = 0.01 initializer_bias_prior_prob = None layer_norm_eps = 1e-05 batch_norm_eps = 1e-05 backbone_config = None backbone = None use_pretrained_backbone = False use_timm_backbone = False freeze_backbone_batch_norms = True backbone_kwargs = None encoder_hidden_dim = 256 encoder_in_channels = [512, 1024, 2048] feat_strides = [8, 16, 32] encoder_layers = 1 encoder_ffn_dim = 1024 encoder_attention_heads = 8 dropout = 0.0 activation_dropout = 0.0 encode_proj_layers = [2] positional_encoding_temperature = 10000 encoder_activation_function = 'gelu' activation_function = 'silu' eval_size = None normalize_before = False hidden_expansion = 1.0 d_model = 256 num_queries = 300 decoder_in_channels = [256, 256, 256] decoder_ffn_dim = 1024 num_feature_levels = 3 decoder_n_points = 4 decoder_layers = 6 decoder_attention_heads = 8 decoder_activation_function = 'relu' attention_dropout = 0.0 num_denoising = 100 label_noise_ratio = 0.5 box_noise_scale = 1.0 learn_initial_query = False anchor_image_size = None disable_custom_kernels = True with_box_refine = True is_encoder_decoder = True matcher_alpha = 0.25 matcher_gamma = 2.0 matcher_class_cost = 2.0 matcher_bbox_cost = 5.0 matcher_giou_cost = 2.0 use_focal_loss = True auxiliary_loss = True focal_loss_alpha = 0.75 focal_loss_gamma = 2.0 weight_loss_vfl = 1.0 weight_loss_bbox = 5.0 weight_loss_giou = 2.0 eos_coefficient = 0.0001 **kwargs )
参数
- initializer_range (
float
, optional, 默认为 0.01) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - initializer_bias_prior_prob (
float
, optional) — 用于偏置初始化器的先验概率,用于初始化enc_score_head
和class_embed
的偏置。 如果为None
,则在初始化模型权重时,prior_prob
计算为prior_prob = 1 / (num_labels + 1)
。 - layer_norm_eps (
float
, optional, defaults to 1e-05) — 层归一化层使用的epsilon值。 - batch_norm_eps (
float
, optional, defaults to 1e-05) — 批归一化层使用的epsilon值。 - backbone_config (
Dict
, 可选, 默认为RTDetrResNetConfig()
) — 骨干模型的配置。 - backbone (
str
, 可选) — 当backbone_config
为None
时使用的骨干网络名称。如果use_pretrained_backbone
为True
,这将从timm或transformers库加载相应的预训练权重。如果use_pretrained_backbone
为False
,这将加载骨干网络的配置并使用该配置初始化具有随机权重的骨干网络。 - use_pretrained_backbone (
bool
, optional, defaults toFalse
) — 是否使用预训练的权重作为骨干网络。 - use_timm_backbone (
bool
, 可选, 默认为False
) — 是否从 timm 库加载backbone
。如果为False
,则从 transformers 库加载 backbone。 - freeze_backbone_batch_norms (
bool
, optional, defaults toTrue
) — 是否冻结骨干网络中的批量归一化层。 - backbone_kwargs (
dict
, optional) — 从检查点加载时传递给AutoBackbone的关键字参数 例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定此参数。 - encoder_hidden_dim (
int
, optional, defaults to 256) — 混合编码器中层的维度。 - encoder_in_channels (
list
, 可选, 默认为[512, 1024, 2048]
) — 编码器的多级特征输入。 - feat_strides (
List[int]
, 可选, 默认为[8, 16, 32]
) — 每个特征图中使用的步幅. - encoder_layers (
int
, optional, defaults to 1) — 编码器使用的总层数。 - encoder_ffn_dim (
int
, optional, defaults to 1024) — 解码器中“中间”(通常称为前馈)层的维度。 - encoder_attention_heads (
int
, optional, 默认为 8) — Transformer 编码器中每个注意力层的注意力头数。 - dropout (
float
, optional, defaults to 0.0) — 所有 dropout 层的比率。 - activation_dropout (
float
, optional, defaults to 0.0) — 全连接层内部激活的丢弃比例。 - encode_proj_layers (
List[int]
, 可选, 默认为[2]
) — 编码器中要使用的投影层的索引。 - positional_encoding_temperature (
int
, optional, defaults to 10000) — 用于创建位置编码的温度参数。 - encoder_activation_function (
str
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
,"relu"
,"silu"
和"gelu_new"
. - activation_function (
str
, optional, 默认为"silu"
) — 通用层中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - eval_size (
Tuple[int, int]
, 可选) — 用于计算位置嵌入的有效高度和宽度的值,考虑了步幅后。 - normalize_before (
bool
, 可选, 默认为False
) — 确定是否在自注意力和前馈模块之前,在变压器编码器层中应用层归一化。 - hidden_expansion (
float
, optional, 默认为 1.0) — 扩展比率,用于扩大 RepVGGBlock 和 CSPRepLayer 的维度大小。 - d_model (
int
, optional, 默认为 256) — 层的维度不包括混合编码器。 - num_queries (
int
, 可选, 默认为 300) — 对象查询的数量. - decoder_in_channels (
list
, optional, defaults to[256, 256, 256]
) — 解码器的多级特征维度 - decoder_ffn_dim (
int
, optional, defaults to 1024) — 解码器中“中间”(通常称为前馈)层的维度。 - num_feature_levels (
int
, 可选, 默认为 3) — 输入特征级别的数量。 - decoder_n_points (
int
, optional, defaults to 4) — 解码器中每个注意力头的每个特征级别中采样的键的数量。 - decoder_layers (
int
, optional, defaults to 6) — 解码器层数. - decoder_attention_heads (
int
, optional, defaults to 8) — Transformer解码器中每个注意力层的注意力头数量。 - decoder_activation_function (
str
, optional, 默认为"relu"
) — 解码器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
,"relu"
,"silu"
和"gelu_new"
. - attention_dropout (
float
, optional, defaults to 0.0) — 注意力概率的丢弃比率。 - num_denoising (
int
, optional, defaults to 100) — 用于对比去噪的总去噪任务或查询的数量。 - label_noise_ratio (
float
, optional, defaults to 0.5) — 应该添加随机噪声的去噪标签的比例。 - box_noise_scale (
float
, optional, defaults to 1.0) — 添加到边界框的噪声的尺度或大小。 - learn_initial_query (
bool
, optional, defaults toFalse
) — 表示在训练期间是否应学习解码器的初始查询嵌入 - anchor_image_size (
Tuple[int, int]
, optional) — 用于评估期间生成边界框锚点的输入图像的高度和宽度。如果为None,则应用自动生成锚点。 - disable_custom_kernels (
bool
, 可选, 默认为True
) — 是否禁用自定义内核. - with_box_refine (
bool
, 可选, 默认为True
) — 是否应用迭代边界框细化,其中每个解码器层根据前一层的预测结果细化边界框。 - is_encoder_decoder (
bool
, optional, defaults toTrue
) — 架构是否具有编码器解码器结构。 - matcher_alpha (
float
, optional, defaults to 0.25) — 匈牙利匹配器使用的参数alpha。 - matcher_gamma (
float
, optional, 默认值为 2.0) — 匈牙利匹配器使用的参数 gamma. - matcher_class_cost (
float
, optional, defaults to 2.0) — 匈牙利匹配器使用的类别损失的相对权重。 - matcher_bbox_cost (
float
, optional, defaults to 5.0) — 匈牙利匹配器使用的边界框损失的相对权重。 - matcher_giou_cost (
float
, optional, defaults to 2.0) — 匈牙利匹配器使用的giou损失的相对权重。 - use_focal_loss (
bool
, optional, defaults toTrue
) — 参数指示是否应使用焦点损失。 - auxiliary_loss (
bool
, optional, defaults toTrue
) — 是否使用辅助解码损失(每个解码器层的损失)。 - focal_loss_alpha (
float
, optional, defaults to 0.75) — 用于计算焦点损失的参数 alpha。 - focal_loss_gamma (
float
, optional, defaults to 2.0) — 用于计算焦点损失的参数 gamma。 - weight_loss_vfl (
float
, optional, defaults to 1.0) — 在目标检测损失中,varifocal损失的相对权重。 - weight_loss_bbox (
float
, optional, defaults to 5.0) — 在目标检测损失中,L1边界框损失的相对权重。 - weight_loss_giou (
float
, optional, defaults to 2.0) — 广义IoU损失在目标检测损失中的相对权重。 - eos_coefficient (
float
, optional, 默认为 0.0001) — 在目标检测损失中,“无对象”类别的相对分类权重。
这是用于存储RTDetrModel配置的配置类。它用于根据指定的参数实例化RT-DETR模型,定义模型架构。使用默认值实例化配置将产生与RT-DETR checkpoing/todo架构类似的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import RTDetrConfig, RTDetrModel
>>> # Initializing a RT-DETR configuration
>>> configuration = RTDetrConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = RTDetrModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
from_backbone_configs
< source >( backbone_config: PretrainedConfig **kwargs ) → RTDetrConfig
从预训练的主干模型配置和DETR模型配置实例化一个RTDetrConfig(或派生类)。
RTDetrResNetConfig
类 transformers.RTDetrResNetConfig
< source >( num_channels = 3 embedding_size = 64 hidden_sizes = [256, 512, 1024, 2048] depths = [3, 4, 6, 3] layer_type = 'bottleneck' hidden_act = 'relu' downsample_in_first_stage = False downsample_in_bottleneck = False out_features = None out_indices = None **kwargs )
参数
- num_channels (
int
, optional, 默认为 3) — 输入通道的数量。 - embedding_size (
int
, optional, 默认为 64) — 嵌入层的维度(隐藏大小)。 - hidden_sizes (
List[int]
, optional, 默认为[256, 512, 1024, 2048]
) — 每个阶段的维度(隐藏大小)。 - depths (
List[int]
, optional, defaults to[3, 4, 6, 3]
) — 每个阶段的深度(层数)。 - layer_type (
str
, 可选, 默认为"bottleneck"
) — 使用的层类型,可以是"basic"
(用于较小的模型,如 resnet-18 或 resnet-34)或"bottleneck"
(用于较大的模型,如 resnet-50 及以上)。 - hidden_act (
str
, 可选, 默认为"relu"
) — 每个块中的非线性激活函数。如果是字符串,支持"gelu"
,"relu"
,"selu"
和"gelu_new"
。 - downsample_in_first_stage (
bool
, 可选, 默认为False
) — 如果为True
,第一阶段将使用stride
为 2 来下采样输入。 - downsample_in_bottleneck (
bool
, 可选, 默认为False
) — 如果为True
,ResNetBottleNeckLayer 中的第一个 1x1 卷积将使用stride
为 2 来下采样输入。 - out_features (
List[str]
, 可选) — 如果用作骨干网络,输出特征的列表。可以是"stem"
,"stage1"
,"stage2"
等。 (取决于模型有多少个阶段)。如果未设置且out_indices
已设置,将默认为相应的阶段。如果未设置且out_indices
也未设置,将默认为最后一个阶段。必须与stage_names
属性中定义的顺序相同。 - out_indices (
List[int]
, optional) — 如果用作骨干网络,输出特征的索引列表。可以是0、1、2等(取决于模型有多少个阶段)。如果未设置且out_features
已设置,将默认为相应的阶段。如果未设置且out_features
也未设置,将默认为最后一个阶段。必须与stage_names
属性中定义的顺序相同。
这是用于存储RTDetrResnetBackbone
配置的配置类。它用于根据指定的参数实例化一个ResNet模型,定义模型架构。使用默认值实例化配置将产生与ResNet microsoft/resnet-50 架构类似的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import RTDetrResNetConfig, RTDetrResnetBackbone
>>> # Initializing a ResNet resnet-50 style configuration
>>> configuration = RTDetrResNetConfig()
>>> # Initializing a model (with random weights) from the resnet-50 style configuration
>>> model = RTDetrResnetBackbone(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
RTDetrImageProcessor
类 transformers.RTDetrImageProcessor
< 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{"height" -- 640, "width": 640}
): 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
参数覆盖。 控制是否对图像进行归一化。可以在preprocess
方法中通过do_normalize
参数覆盖。 - do_normalize (
bool
, optional, defaults toFalse
) — 是否对图像进行归一化处理。 - 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
, 可选, 默认为False
) — 控制是否对图像进行填充。可以通过preprocess
方法中的do_pad
参数进行覆盖。如果为True
,则会在图像的底部和右侧用零进行填充。 如果提供了pad_size
,图像将被填充到指定的尺寸。 否则,图像将被填充到批次中的最大高度和宽度。 - pad_size (
Dict[str, int]
, 可选) — 图像填充的大小{"height": int, "width" int}
。必须大于预处理中提供的任何图像大小。 如果未提供pad_size
,图像将被填充到批次中最大的高度和宽度。
构建一个RT-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
或pathlib.Path
, 可选) — 包含分割掩码的目录路径。 - 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 use_focal_loss: bool = True ) → List[Dict]
参数
- 输出 (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, optional, 默认为 0.5) — 用于保留对象检测预测的分数阈值。 - target_sizes (
torch.Tensor
或List[Tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或包含批次中每个图像目标大小的元组列表 (Tuple[int, int]
), 目标大小为(height, width)
。如果未设置,预测结果将不会被调整大小。 - use_focal_loss (
bool
默认为True
) — 变量指示是否使用焦点损失来预测输出。如果为True
,则应用 sigmoid 来计算每个检测的分数,否则使用 softmax 函数。
返回
List[Dict]
一个字典列表,每个字典包含模型预测的批次中每张图像的分数、标签和框。
将DetrForObjectDetection的原始输出转换为最终边界框,格式为(左上角x,左上角y,右下角x,右下角y)。仅支持PyTorch。
RTDetrImageProcessorFast
类 transformers.RTDetrImageProcessorFast
< 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
, 可选, 默认为False
) — 控制是否对图像进行归一化。可以在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
, 可选, 默认为False
) — 控制是否对图像进行填充。可以通过preprocess
方法中的do_pad
参数进行覆盖。如果为True
,则会在图像的底部和右侧用零进行填充。 如果提供了pad_size
,图像将被填充到指定的尺寸。 否则,图像将被填充到批次中的最大高度和宽度。 - pad_size (
Dict[str, int]
, 可选) — 图像填充的大小{"height": int, "width" int}
。必须大于预处理中提供的任何图像大小。 如果未提供pad_size
,图像将被填充到批次中最大的高度和宽度。
构建一个快速的RT-DETR 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 use_focal_loss: bool = True ) → List[Dict]
参数
- 输出 (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, optional, 默认为 0.5) — 用于保留目标检测预测的分数阈值. - target_sizes (
torch.Tensor
或List[Tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或包含批次中每个图像目标大小的元组列表 (Tuple[int, int]
)(height, width)
。如果未设置,预测结果将不会调整大小。 - use_focal_loss (
bool
默认为True
) — 变量指示是否使用焦点损失来预测输出。如果为True
,则应用 sigmoid 来计算每个检测的分数,否则使用 softmax 函数。
返回
List[Dict]
一个字典列表,每个字典包含模型预测的批次中每张图像的分数、标签和框。
将DetrForObjectDetection的原始输出转换为最终边界框,格式为(左上角x,左上角y,右下角x,右下角y)。仅支持PyTorch。
RTDetrModel
类 transformers.RTDetrModel
< source >( 配置: RTDetrConfig )
参数
- config (RTDetrConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
RT-DETR模型(由骨干网络和编码器-解码器组成)输出原始隐藏状态,顶部没有任何头部。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: FloatTensor pixel_mask: typing.Optional[torch.LongTensor] = 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.rt_detr.modeling_rt_detr.RTDetrModelOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。默认情况下,如果您提供了填充,它将被忽略。可以使用 AutoImageProcessor获取像素值。详情请参见RTDetrImageProcessor.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).
- 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) — 可选地,您可以选择直接传递一个嵌入表示,而不是用零张量初始化查询。 - labels (
List[Dict]
长度为(batch_size,)
, 可选) — 用于计算二分匹配损失的标签。字典列表,每个字典至少包含以下两个键:'class_labels' 和 'boxes'(分别是批次中图像的类别标签和边界框)。类别标签本身应该是长度为(图像中边界框的数量,)
的torch.LongTensor
,而边界框应该是形状为(图像中边界框的数量, 4)
的torch.FloatTensor
。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.models.rt_detr.modeling_rt_detr.RTDetrModelOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.rt_detr.modeling_rt_detr.RTDetrModelOutput
或一个由 torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置(RTDetrConfig)和输入的各种元素。
- 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_logits (
torch.FloatTensor
形状为(batch_size, config.decoder_layers, sequence_length, config.num_labels)
) — 堆叠的中间 logits(解码器每一层的 logits)。 - 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 后,用于计算自注意力头中的加权平均值。 - init_reference_points (
torch.FloatTensor
形状为(batch_size, num_queries, 4)
) — 通过 Transformer 解码器发送的初始参考点。 - enc_topk_logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.num_labels)
) — 预测的边界框分数,其中得分最高的config.two_stage_num_proposals
个边界框被选为编码器阶段的区域提议。边界框二分类的输出(即前景和背景)。 - enc_topk_bboxes (
torch.FloatTensor
形状为(batch_size, sequence_length, 4)
) — 编码器阶段预测的边界框坐标的 logits。 - 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。 - denoising_meta_values (
dict
) — 用于去噪相关值的额外字典。
RTDetrModel 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoImageProcessor, RTDetrModel
>>> 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("PekingU/rtdetr_r50vd")
>>> model = RTDetrModel.from_pretrained("PekingU/rtdetr_r50vd")
>>> 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]
RTDetrForObjectDetection
类 transformers.RTDetrForObjectDetection
< source >( 配置: RTDetrConfig )
参数
- config (RTDetrConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
RT-DETR 模型(由骨干网络和编码器-解码器组成)输出边界框和逻辑值,这些值将进一步解码为分数和类别。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: FloatTensor pixel_mask: typing.Optional[torch.LongTensor] = 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 **loss_kwargs ) → transformers.models.rt_detr.modeling_rt_detr.RTDetrObjectDetectionOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。默认情况下,如果您提供了填充,它将被忽略。可以使用 AutoImageProcessor获取像素值。详情请参见RTDetrImageProcessor.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).
- 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) — 可选地,您可以选择直接传递一个嵌入表示,而不是用零张量初始化查询。 - labels (
List[Dict]
长度为(batch_size,)
, 可选) — 用于计算二分匹配损失的标签。字典列表,每个字典至少包含以下两个键:'class_labels' 和 'boxes'(分别是批次中图像的类别标签和边界框)。类别标签本身应该是长度为(图像中边界框的数量,)
的torch.LongTensor
,而边界框应该是形状为(图像中边界框的数量, 4)
的torch.FloatTensor
。 - output_attentions (
bool
, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
List[Dict]
长度为(batch_size,)
, 可选) — 用于计算二分匹配损失的标签。字典列表,每个字典至少包含以下两个键:'class_labels' 和 'boxes'(分别是批次中图像的类别标签和边界框)。类别标签本身应该是长度为(图像中边界框的数量,)
的torch.LongTensor
,而边界框应该是形状为(图像中边界框的数量, 4)
的torch.FloatTensor
。
返回
transformers.models.rt_detr.modeling_rt_detr.RTDetrObjectDetectionOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.rt_detr.modeling_rt_detr.RTDetrObjectDetectionOutput
或一个由 torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置(RTDetrConfig)和输入的各种元素。
- 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] 范围内归一化,相对于批次中每个单独图像的大小(忽略可能的填充)。您可以使用 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)
) — 模型解码器最后一层的隐藏状态序列。 - intermediate_hidden_states (
torch.FloatTensor
形状为(batch_size, config.decoder_layers, num_queries, hidden_size)
) — 堆叠的中间隐藏状态(解码器每层的输出)。 - intermediate_logits (
torch.FloatTensor
形状为(batch_size, config.decoder_layers, num_queries, config.num_labels)
) — 堆叠的中间 logits(解码器每层的 logits)。 - 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 之后,用于计算自注意力头中的加权平均值。 - init_reference_points (
torch.FloatTensor
形状为(batch_size, num_queries, 4)
) — 通过 Transformer 解码器发送的初始参考点。 - enc_topk_logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.num_labels)
,可选,当config.with_box_refine=True
和config.two_stage=True
时返回) — 编码器中预测的边界框坐标的 logits。 - enc_topk_bboxes (
torch.FloatTensor
形状为(batch_size, sequence_length, 4)
,可选,当config.with_box_refine=True
和config.two_stage=True
时返回) — 编码器中预测的边界框坐标的 logits。 - 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。 - denoising_meta_values (
dict
) — 用于去噪相关值的额外字典。
RTDetrForObjectDetection 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import RTDetrImageProcessor, RTDetrForObjectDetection
>>> from PIL import Image
>>> import requests
>>> import torch
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
>>> model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd")
>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> # forward pass
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> list(logits.shape)
[1, 300, 80]
>>> boxes = outputs.pred_boxes
>>> list(boxes.shape)
[1, 300, 4]
>>> # 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.9, 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 sofa with confidence 0.97 at location [0.14, 0.38, 640.13, 476.21]
Detected cat with confidence 0.96 at location [343.38, 24.28, 640.14, 371.5]
Detected cat with confidence 0.958 at location [13.23, 54.18, 318.98, 472.22]
Detected remote with confidence 0.951 at location [40.11, 73.44, 175.96, 118.48]
Detected remote with confidence 0.924 at location [333.73, 76.58, 369.97, 186.99]
RTDetrResNetBackbone
类 transformers.RTDetrResNetBackbone
< source >( config )
参数
- config (RTDetrResNetConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
ResNet 骨干网络,用于与 RTDETR 等框架一起使用。
该模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: Tensor output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BackboneOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 RTDetrImageProcessor.call(). - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_outputs.BackboneOutput
或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BackboneOutput
或一个由 torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置(RTDetrResNetConfig)和输入的各种元素。
-
feature_maps (
tuple(torch.FloatTensor)
形状为(batch_size, num_channels, height, width)
) — 各阶段的特征图。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
或(batch_size, num_channels, height, width)
,取决于骨干网络。模型在每个阶段输出时的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。仅当骨干网络使用注意力机制时适用。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
RTDetrResNetBackbone 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import RTDetrResNetConfig, RTDetrResNetBackbone
>>> import torch
>>> config = RTDetrResNetConfig()
>>> model = RTDetrResNetBackbone(config)
>>> pixel_values = torch.randn(1, 3, 224, 224)
>>> with torch.no_grad():
... outputs = model(pixel_values)
>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 2048, 7, 7]