Transformers 文档
RT-DETR
并获得增强的文档体验
开始使用
RT-DETR
概述
RT-DETR 模型在 DETRs Beat YOLOs on Real-time Object Detection 中提出,作者是 Wenyu Lv、Yian Zhao、Shangliang Xu、Jinman Wei、Guanzhong Wang、Cheng Cui、Yuning Du、Qingqing Dang、Yi Liu。
RT-DETR 是一个目标检测模型,代表 “Real-Time DEtection Transformer”(实时检测 Transformer)。该模型旨在执行目标检测任务,重点是在保持高精度的同时实现实时性能。RT-DETR 利用在深度学习的各个领域中广受欢迎的 Transformer 架构,处理图像以识别和定位其中的多个对象。
该论文的摘要如下:
最近,基于端到端 Transformer 的检测器 (DETR) 取得了显著的性能。然而,DETR 计算成本高的问题尚未得到有效解决,限制了它们的实际应用,并阻止它们充分利用无后处理的优势,例如非极大值抑制 (NMS)。在本文中,我们首先分析了 NMS 在现代实时目标检测器中对推理速度的影响,并建立了一个端到端速度基准。为了避免 NMS 引起的推理延迟,我们提出了一个实时检测 Transformer (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 倍。

该模型版本由 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。
- 用于使用 Trainer 或 Accelerate 微调 RTDetrForObjectDetection 的脚本可以在这里找到。
- 另请参阅:目标检测任务指南。
- 关于在自定义数据集上进行 RT-DETR 推理和微调的 Notebooks 可以在这里找到。 🌎
RTDetrConfig
类 transformers.RTDetrConfig
< 源代码 >( 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
,可选的 , 默认为 0.01) — 用于初始化所有权重矩阵的截断正态分布初始化器的标准差。 - initializer_bias_prior_prob (
float
,可选的 ) — 偏置初始化器用于初始化enc_score_head
和class_embed
偏置的先验概率。如果为None
,则在初始化模型权重时,prior_prob
计算为prior_prob = 1 / (num_labels + 1)
。 - layer_norm_eps (
float
,可选的 , 默认为 1e-05) — 层归一化层使用的 epsilon 值。 - batch_norm_eps (
float
,可选的 , 默认为 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
,可选的 , 默认为False
) — 是否对主干网络使用预训练权重。 - use_timm_backbone (
bool
,可选的 , 默认为False
) — 是否从 timm 库加载backbone
。如果为False
,则从 transformers 库加载主干网络。 - freeze_backbone_batch_norms (
bool
,可选的 , 默认为True
) — 是否冻结主干网络中的批归一化层。 - backbone_kwargs (
dict
,可选的 ) — 从检查点加载时传递给 AutoBackbone 的关键字参数,例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定此参数。 - encoder_hidden_dim (
int
,可选的 , 默认为 256) — 混合编码器中层的维度。 - encoder_in_channels (
list
,可选的 , 默认为[512, 1024, 2048]
) — 编码器的多层级特征输入。 - feat_strides (
List[int]
,可选的 , 默认为[8, 16, 32]
) — 每个特征图中使用步幅。 - encoder_layers (
int
,可选的 , 默认为 1) — 编码器要使用的总层数。 - encoder_ffn_dim (
int
,可选的 , 默认为 1024) — 解码器中 “中间”(通常称为前馈)层的维度。 - encoder_attention_heads (
int
,可选的 , 默认为 8) — Transformer 编码器中每个注意力层的注意力头数。 - dropout (
float
,可选的 , 默认为 0.0) — 所有 dropout 层的比率。 - activation_dropout (
float
,可选的 , 默认为 0.0) — 完全连接层内部激活的 dropout 比率。 - encode_proj_layers (
List[int]
,可选的 , 默认为[2]
) — 编码器中要使用的投影层索引。 - positional_encoding_temperature (
int
,可选的 , 默认为 10000) — 用于创建位置编码的温度参数。 - encoder_activation_function (
str
,可选的 , 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
,"relu"
,"silu"
和"gelu_new"
。 - activation_function (
str
,可选的 , 默认为"silu"
) — 通用层中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
,"relu"
,"silu"
和"gelu_new"
。 - eval_size (
Tuple[int, int]
, 可选) — 用于计算位置嵌入的有效高度和宽度的图像高度和宽度,计算时考虑了步幅。 - normalize_before (
bool
, 可选, 默认为False
) — 确定是否在 Transformer 编码器层中的自注意力模块和前馈模块之前应用层归一化。 - hidden_expansion (
float
, 可选, 默认为 1.0) — 用于扩大 RepVGGBlock 和 CSPRepLayer 维度大小的扩展比率。 - d_model (
int
, 可选, 默认为 256) — 混合编码器以外的层维度。 - num_queries (
int
, 可选, 默认为 300) — 对象查询的数量。 - decoder_in_channels (
list
, 可选, 默认为[256, 256, 256]
) — 解码器的多层特征维度。 - decoder_ffn_dim (
int
, 可选, 默认为 1024) — 解码器中 “中间” 层(通常称为前馈层)的维度。 - num_feature_levels (
int
, 可选, 默认为 3) — 输入特征层级的数量。 - decoder_n_points (
int
, 可选, 默认为 4) — 解码器中每个注意力头的每个特征层级中采样的键的数量。 - decoder_layers (
int
, 可选, 默认为 6) — 解码器层数。 - decoder_attention_heads (
int
, 可选, 默认为 8) — Transformer 解码器中每个注意力层的注意力头数。 - decoder_activation_function (
str
, 可选, 默认为"relu"
) — 解码器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - attention_dropout (
float
, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。 - num_denoising (
int
, 可选, 默认为 100) — 用于对比去噪的总去噪任务或查询的数量。 - label_noise_ratio (
float
, 可选, 默认为 0.5) — 应该向其添加随机噪声的去噪标签的比例。 - box_noise_scale (
float
, 可选, 默认为 1.0) — 要添加到边界框的噪声的尺度或幅度。 - learn_initial_query (
bool
, 可选, 默认为False
) — 指示是否应在训练期间学习解码器的初始查询嵌入。 - anchor_image_size (
Tuple[int, int]
, 可选) — 评估期间用于生成边界框锚点的输入图像的高度和宽度。如果为 None,则应用自动生成锚点。 - disable_custom_kernels (
bool
, 可选, 默认为True
) — 是否禁用自定义内核。 - with_box_refine (
bool
, 可选, 默认为True
) — 是否应用迭代边界框细化,其中每个解码器层都基于前一层的预测来细化边界框。 - is_encoder_decoder (
bool
, 可选, 默认为True
) — 架构是否具有编码器-解码器结构。 - matcher_alpha (
float
, 可选, 默认为 0.25) — Hungarian Matcher 使用的参数 alpha。 - matcher_gamma (
float
, 可选, 默认为 2.0) — Hungarian Matcher 使用的参数 gamma。 - matcher_class_cost (
float
, 可选, 默认为 2.0) — Hungarian Matcher 使用的类别损失的相对权重。 - matcher_bbox_cost (
float
, 可选, 默认为 5.0) — Hungarian Matcher 使用的边界框损失的相对权重。 - matcher_giou_cost (
float
, 可选, 默认为 2.0) — Hungarian Matcher 使用的 giou 损失的相对权重。 - use_focal_loss (
bool
, 可选, 默认为True
) — 指示是否应使用 Focal Loss 的参数。 - auxiliary_loss (
bool
, 可选, 默认为True
) — 是否使用辅助解码损失(每个解码器层的损失)。 - focal_loss_alpha (
float
, 可选, 默认为 0.75) — 用于计算 Focal Loss 的参数 alpha。 - focal_loss_gamma (
float
, 可选, 默认为 2.0) — 用于计算 focal loss 的参数 gamma。 - weight_loss_vfl (
float
, 可选, 默认为 1.0) — 目标检测损失中 varifocal loss 的相对权重。 - weight_loss_bbox (
float
, 可选, 默认为 5.0) — 目标检测损失中 L1 边界框损失的相对权重。 - weight_loss_giou (
float
, 可选, 默认为 2.0) — 目标检测损失中 generalized IoU loss 的相对权重。 - eos_coefficient (
float
, 可选, 默认为 0.0001) — 目标检测损失中 ‘no-object’ 类的相对分类权重。
这是用于存储 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
class 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
, 可选, 默认为 3) — 输入通道数。 - embedding_size (
int
, 可选, 默认为 64) — 嵌入层 的维度(隐藏大小)。 - hidden_sizes (
List[int]
, 可选, 默认为[256, 512, 1024, 2048]
) — 每个阶段的维度(隐藏大小)。 - depths (
List[int]
, 可选, 默认为[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
,则第一阶段将使用 2 的stride
对输入进行下采样。 - downsample_in_bottleneck (
bool
, 可选, 默认为False
) — 如果为True
,则 ResNetBottleNeckLayer 中的第一个 conv 1x1 将使用 2 的stride
对输入进行下采样。 - out_features (
List[str]
, 可选) — 如果用作主干网络,则要输出的特征列表。 可以是"stem"
、"stage1"
、"stage2"
等中的任何一个(取决于模型有多少个阶段)。 如果未设置且设置了out_indices
,则默认为相应的阶段。 如果未设置且out_indices
也未设置,则默认为最后一个阶段。 必须与stage_names
属性中定义的顺序相同。 - out_indices (
List[int]
, 可选) — 如果用作主干网络,则要输出的特征索引列表。 可以是 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
class transformers.RTDetrImageProcessor
< source >( 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 = False image_mean: typing.Union[float, typing.List[float]] = None image_std: typing.Union[float, typing.List[float]] = None do_convert_annotations: bool = True do_pad: bool = False pad_size: typing.Optional[typing.Dict[str, int]] = None **kwargs )
参数
- format (
str
, 可选, 默认为AnnotationFormat.COCO_DETECTION
) — 注释的数据格式。 “coco_detection” 或 “coco_panoptic” 之一。 - do_resize (
bool
, optional, defaults toTrue
) — 控制是否将图像的 (height, width) 尺寸调整为指定的size
。可以被preprocess
方法中的do_resize
参数覆盖。 - size (
Dict[str, int]
optional, defaults to{"height" -- 640, "width": 640}
): 调整大小后图像的(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
, optional, defaults toPILImageResampling.BILINEAR
) — 如果调整图像大小,则使用的重采样过滤器。 - do_rescale (
bool
, optional, defaults toTrue
) — 控制是否按指定的比例rescale_factor
缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
orfloat
, optional, defaults to1/255
) — 如果缩放图像,则使用的缩放因子。可以被preprocess
方法中的rescale_factor
参数覆盖。控制是否标准化图像。可以被preprocess
方法中的do_normalize
参数覆盖。 - do_normalize (
bool
, optional, defaults toFalse
) — 是否标准化图像。 - image_mean (
float
orList[float]
, optional, defaults toIMAGENET_DEFAULT_MEAN
) — 标准化图像时使用的均值。可以是单个值或值列表,每个通道一个值。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
orList[float]
, optional, defaults toIMAGENET_DEFAULT_STD
) — 标准化图像时使用的标准差值。可以是单个值或值列表,每个通道一个值。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_annotations (
bool
, optional, defaults toTrue
) — 控制是否将注释转换为 DETR 模型期望的格式。将边界框转换为(center_x, center_y, width, height)
格式,并在[0, 1]
范围内。可以被preprocess
方法中的do_convert_annotations
参数覆盖。 - do_pad (
bool
, optional, defaults toFalse
) — 控制是否填充图像。可以被preprocess
方法中的do_pad
参数覆盖。如果为True
,则会在图像的底部和右侧填充零。如果提供了pad_size
,则图像将被填充到指定的尺寸。否则,图像将被填充到批次中的最大高度和宽度。 - pad_size (
Dict[str, int]
, optional) — 要将图像填充到的尺寸{"height": int, "width" int}
。必须大于任何提供的用于预处理的图像尺寸。如果未提供pad_size
,则图像将被填充到批次中最大的高度和宽度。
构建 RT-DETR 图像处理器。
preprocess
< source >( 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[str, transformers.image_utils.ChannelDimension, NoneType] = None pad_size: typing.Optional[typing.Dict[str, int]] = None )
参数
- images (
ImageInput
) — 要预处理的图像或一批图像。期望输入像素值范围为 0 到 255 的单个或一批图像。如果传入像素值在 0 到 1 之间的图像,请设置do_rescale=False
。 - annotations (
AnnotationType
orList[AnnotationType]
, optional) — 与图像或一批图像关联的注释列表。如果注释用于对象检测,则注释应为包含以下键的字典:- “image_id” (
int
): 图像 id。 - “annotations” (
List[Dict]
): 图像的注释列表。每个注释都应是一个字典。图像可以没有注释,在这种情况下,列表应为空。如果注释用于分割,则注释应为包含以下键的字典: - “image_id” (
int
): 图像 id。 - “segments_info” (
List[Dict]
): 图像的分割列表。每个分割都应是一个字典。图像可以没有分割,在这种情况下,列表应为空。 - “file_name” (
str
): 图像的文件名。
- “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) — 调整大小后图像的(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
, 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
, optional, defaults to 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
或List[float]
, 可选, 默认为 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
: 图像格式为 (通道数, 高度, 宽度)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (高度, 宽度, 通道数)。- 未设置: 使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,通道维度格式将从输入图像中推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (通道数, 高度, 宽度)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (高度, 宽度, 通道数)。"none"
或ChannelDimension.NONE
: 图像格式为 (高度, 宽度)。
- 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]
参数
- outputs (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, 可选, 默认为 0.5) — 保留物体检测预测的分数阈值。 - target_sizes (
torch.Tensor
或List[Tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或元组列表 (Tuple[int, int]
),其中包含批次中每个图像的目标尺寸 (高度, 宽度)。如果未设置,则不会调整预测大小。 - use_focal_loss (
bool
, 默认为True
) — 变量,指示是否使用 focal loss 来预测输出。如果为True
,则应用 sigmoid 函数来计算每个检测的分数;否则,使用 softmax 函数。
返回值
List[Dict]
字典列表,每个字典包含模型预测的批次中一个图像的分数、标签和边界框。
将 DetrForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。仅支持 PyTorch。
RTDetrImageProcessorFast
class transformers.RTDetrImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.rt_detr.image_processing_rt_detr_fast.RTDetrFastImageProcessorKwargs] )
参数
- 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
是 int,调整大小时是否默认使用正方形图像。 - 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 (
int
或float
, 可选, 默认为self.rescale_factor
) — 如果缩放图像,则使用的缩放因子。仅当do_rescale
设置为True
时才有效。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否归一化图像。可以被preprocess
方法中的do_normalize
参数覆盖。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 如果归一化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度为图像中通道的数量。可以被preprocess
方法中的image_mean
参数覆盖。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 如果要对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_std
参数覆盖。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, 可选, 默认为self.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为self.data_format
) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, 可选, 默认为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
) — 控制是否将注释转换为 RT_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
,则图像将被填充到批次中最大的高度和宽度。 - return_segmentation_masks (
bool
, 可选, 默认为False
) — 是否返回分割掩码。
构建一个快速的 RTDetr 图像处理器。
preprocess
< source >( 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.rt_detr.image_processing_rt_detr_fast.RTDetrFastImageProcessorKwargs] )
参数
- images (
ImageInput
) — 要预处理的图像。期望是像素值范围为 0 到 255 的单个或一批图像。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 描述模型的最大输入尺寸。 - resample (
PILImageResampling
或InterpolationMode
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样过滤器。可以是枚举PILImageResampling
之一。仅当do_resize
设置为True
时才有效。 - do_center_crop (
bool
, 可选, 默认为self.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 应用center_crop
后输出图像的大小。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否缩放图像。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于缩放图像的缩放因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。仅当do_normalize
设置为True
时才有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅当do_normalize
设置为True
时才有效。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, 可选, 默认为self.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为self.data_format
) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, 可选, 默认为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
) — 用于处理图像的设备。如果未设置,则设备从输入图像推断。 - annotations (
AnnotationType
或List[AnnotationType]
, 可选) — 与图像或图像批次关联的注释列表。如果注释用于目标检测,则注释应为包含以下键的字典:- “image_id” (
int
): 图像 ID。 - “annotations” (
List[Dict]
): 图像注释列表。每个注释应为一个字典。图像可以没有注释,在这种情况下,列表应为空。如果注释用于分割,则注释应为包含以下键的字典: - “image_id” (
int
): 图像 ID。 - “segments_info” (
List[Dict]
): 图像分割列表。每个分割应为一个字典。图像可以没有分割,在这种情况下,列表应为空。 - “file_name” (
str
): 图像的文件名。
- “image_id” (
- format (
str
, 可选, 默认为AnnotationFormat.COCO_DETECTION
) — 注释的数据格式。可选值为 “coco_detection” 或 “coco_panoptic”。 - 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
,则图像将填充到批次中的最大高度和宽度。 - return_segmentation_masks (
bool
, 可选, 默认为False
) — 是否返回分割掩码。 - masks_path (
str
或pathlib.Path
, 可选) — 包含分割掩码的目录路径。
预处理图像或图像批次。
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]
参数
- outputs (
DetrObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, 可选, 默认为 0.5) — 保留目标检测预测的分数阈值。 - target_sizes (
torch.Tensor
或List[Tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或元组列表 (Tuple[int, int]
),其中包含批次中每个图像的目标尺寸(height, width)
。 如果未设置,则不会调整预测大小。 - use_focal_loss (
bool
默认为True
) — 变量,指示是否使用 focal loss 来预测输出。 如果为True
,则应用 sigmoid 函数来计算每个检测的分数;否则,使用 softmax 函数。
返回值
List[Dict]
字典列表,每个字典包含模型预测的批次中一个图像的分数、标签和边界框。
将 DetrForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。仅支持 PyTorch。
RTDetrModel
class transformers.RTDetrModel
< source >( config: RTDetrConfig )
参数
- config (RTDetrConfig) — 具有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
RT-DETR 模型(由骨干网络和编码器-解码器组成),输出原始隐藏状态,顶部没有任何头部。
此模型继承自 PreTrainedModel。 查看超类文档以获取库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。
此模型也是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与常规用法和行为相关的事项。
forward
< 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 (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 像素值。 默认情况下,如果您提供填充,则会忽略填充。 像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 RTDetrImageProcessor.call()。 - pixel_mask (形状为
(batch_size, height, width)
的torch.LongTensor
, 可选) — 用于避免对填充像素值执行注意力的掩码。 掩码值在[0, 1]
中选择:- 1 表示真实像素(即未掩码),
- 0 表示填充像素(即已掩码)。
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — 元组由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
) 组成。 形状为(batch_size, sequence_length, hidden_size)
的last_hidden_state
, 可选) 是编码器最后一层输出端的隐藏状态序列。 用于解码器的交叉注意力机制。 - inputs_embeds (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, 可选) — (可选)您可以选择直接传递图像的扁平化表示,而不是传递扁平化的特征图(骨干网络 + 投影层的输出)。 - decoder_inputs_embeds (形状为
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
, 可选) — (可选)您可以选择直接传递嵌入表示,而不是使用零张量初始化查询。 - labels (长度为
(batch_size,)
的List[Dict]
, 可选) — 用于计算二分图匹配损失的标签。 字典列表,每个字典至少包含以下 2 个键:“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 (形状为
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
) — 模型解码器最后一层的输出的隐藏状态序列。 - intermediate_hidden_states (形状为
(batch_size, config.decoder_layers, num_queries, hidden_size)
的torch.FloatTensor
) — 堆叠的中间隐藏状态(解码器每一层的输出)。 - intermediate_logits (形状为
(batch_size, config.decoder_layers, sequence_length, config.num_labels)
的torch.FloatTensor
) — 堆叠的中间 logits(解码器每一层的 logits)。 - 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, 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)
。解码器的注意力权重,在 attention softmax 之后,用于计算自注意力头中的加权平均值。 - cross_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组(每层一个),形状为(batch_size, num_queries, num_heads, 4, 4)
。解码器的交叉注意力层的注意力权重,在 attention 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_queries, num_heads, 4, 4)
。编码器的注意力权重,在 attention softmax 之后,用于计算自注意力头中的加权平均值。 - init_reference_points (形状为
(batch_size, num_queries, 4)
的torch.FloatTensor
) — 通过 Transformer 解码器发送的初始参考点。 - enc_topk_logits (形状为
(batch_size, sequence_length, config.num_labels)
的torch.FloatTensor
) — 预测的边界框分数,其中在编码器阶段选择 topconfig.two_stage_num_proposals
个评分最高的边界框作为区域提议。边界框二元分类(即前景和背景)的输出。 - enc_topk_bboxes (形状为
(batch_size, sequence_length, 4)
的torch.FloatTensor
) — 编码器阶段中预测的边界框坐标的 logits。 - enc_outputs_class (形状为
(batch_size, sequence_length, config.num_labels)
的torch.FloatTensor
, 可选, 当config.with_box_refine=True
且config.two_stage=True
时返回) — 预测的边界框分数,其中在第一阶段选择 topconfig.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。 - denoising_meta_values (
dict
) — 用于去噪相关值的额外字典
RTDetrModel 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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
class transformers.RTDetrForObjectDetection
< source >( config: RTDetrConfig )
参数
- config (RTDetrConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
RT-DETR 模型(由骨干网络和编码器-解码器组成)输出边界框和 logits,以便进一步解码为分数和类别。
此模型继承自 PreTrainedModel。 查看超类文档以获取库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。
此模型也是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与常规用法和行为相关的事项。
forward
< 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 (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 像素值。默认情况下,如果您提供 padding,则会忽略 padding。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 RTDetrImageProcessor.call()。 - pixel_mask (形状为
(batch_size, height, width)
的torch.LongTensor
, 可选) — 用于避免对 padding 像素值执行 attention 的掩码。在[0, 1]
中选择的掩码值:- 1 代表真实像素(即未被掩码),
- 0 代表 padding 像素(即被掩码)。
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — 元组由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
) 组成,last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
,可选) 是编码器最后一层输出的隐藏状态序列。在解码器的交叉注意力中使用。 - inputs_embeds (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, 可选) — 可选地,您可以选择直接传递图像的展平表示,而不是传递展平的特征图(骨干网络 + 投影层的输出)。 - decoder_inputs_embeds (形状为
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是使用零张量初始化 queries。 - labels (长度为
(batch_size,)
的List[Dict]
, 可选) — 用于计算二分图匹配损失的标签。字典列表,每个字典至少包含以下 2 个键:'class_labels' 和 'boxes'(批次中图像的类别标签和边界框)。类别标签本身应为长度为(图像中边界框的数量,)
的torch.LongTensor
,而 boxes 的形状为(图像中边界框的数量, 4)
的torch.FloatTensor
。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attention 张量。有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - labels (长度为
(batch_size,)
的List[Dict]
, 可选) — 用于计算二分图匹配损失的标签。字典列表,每个字典至少包含以下 2 个键:'class_labels' 和 'boxes'(批次中图像的类别标签和边界框)。类别标签本身应为长度为(图像中边界框的数量,)
的torch.LongTensor
,而 boxes 的形状为(图像中边界框的数量, 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 (形状为
(1,)
的torch.FloatTensor
, 可选, 当提供labels
时返回) — 总损失,是类别预测的负对数似然(交叉熵)损失和边界框损失的线性组合。后者定义为 L1 损失和广义尺度不变 IoU 损失的线性组合。 - loss_dict (
Dict
, 可选) — 包含各个损失的字典。用于日志记录。 - logits (形状为
(batch_size, num_queries, num_classes + 1)
的torch.FloatTensor
) — 所有 queries 的分类 logits(包括无对象)。 - pred_boxes (形状为
(batch_size, num_queries, 4)
的torch.FloatTensor
) — 所有 queries 的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每个单独图像的大小(忽略可能的 padding)。您可以使用 post_process_object_detection() 来检索未归一化(绝对)的边界框。 - auxiliary_outputs (
list[Dict]
, 可选) — 可选,仅当辅助损失激活时返回(即config.auxiliary_loss
设置为True
)并且提供了 labels。它是字典列表,其中包含每个解码器层的上述两个键(logits
和pred_boxes
)。 - 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_logits (形状为
(batch_size, config.decoder_layers, num_queries, config.num_labels)
的torch.FloatTensor
) — 堆叠的中间 logits(解码器每一层的 logits)。 - 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, 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)
。解码器的注意力权重,在 attention softmax 之后,用于计算自注意力头中的加权平均值。 - cross_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组(每层一个),形状为(batch_size, num_queries, num_heads, 4, 4)
。解码器的交叉注意力层的注意力权重,在 attention 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_queries, num_heads, 4, 4)
。编码器的注意力权重,在 attention softmax 之后,用于计算自注意力头中的加权平均值。 - init_reference_points (形状为
(batch_size, num_queries, 4)
的torch.FloatTensor
) — 通过 Transformer 解码器发送的初始参考点。 - enc_topk_logits (形状为
(batch_size, sequence_length, config.num_labels)
的torch.FloatTensor
, 可选, 当config.with_box_refine=True
且config.two_stage=True
时返回) — 编码器中预测的边界框坐标的 logits。 - enc_topk_bboxes (形状为
(batch_size, sequence_length, 4)
的torch.FloatTensor
, 可选, 当config.with_box_refine=True
且config.two_stage=True
时返回) — 编码器中预测的边界框坐标的 logits。 - enc_outputs_class (形状为
(batch_size, sequence_length, config.num_labels)
的torch.FloatTensor
, 可选, 当config.with_box_refine=True
且config.two_stage=True
时返回) — 预测的边界框分数,其中在第一阶段选择 topconfig.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。 - denoising_meta_values (
dict
) — 用于去噪相关值的额外字典
RTDetrForObjectDetection 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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
class transformers.RTDetrResNetBackbone
< source >( config )
参数
- config (RTDetrResNetConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
ResNet 骨干网络,用于诸如 RTDETR 之类的框架。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。
forward
< 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 (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 像素值。像素值可以使用 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 (形状为
(batch_size, num_channels, height, width)
的tuple(torch.FloatTensor)
) — 各个阶段的特征图。 -
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)
,取决于backbone。模型在每个阶段输出以及初始嵌入输出的隐藏状态。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递了output_attentions=True
或者当config.output_attentions=True
时返回) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。 仅当backbone使用attention时适用。attention softmax 之后的 attention 权重,用于计算自注意力头中的加权平均值。
RTDetrResNetBackbone 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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]