Transformers documentation
RT-DETR
该模型于 2023-04-17 在 HF papers 上发表,并于 2024-06-22 贡献至 Hugging Face Transformers。
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 是一种目标检测模型,全称为“Real-Time DEtection Transformer”(实时检测 Transformer)。该模型专为执行目标检测任务而设计,旨在保持高精度的同时实现实时性能。借助在深度学习多个领域广受欢迎的 Transformer 架构,RT-DETR 对图像进行处理,以识别并定位其中的多个目标。
该论文的摘要如下:
近期,基于 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 倍。
RT-DETR performance relative to YOLO models. Taken from the original paper. 该模型版本由 rafaelpadilla 和 sangbumchoi 贡献。原始代码可在此处找到。
使用技巧
最初,图像会使用预训练的卷积神经网络进行处理,具体为原始代码中引用的 Resnet-D 变体。该网络从架构的最后三层中提取特征。随后,使用混合编码器将多尺度特征转换为图像特征的序列数组。然后,配备辅助预测头的解码器用于优化目标查询。此过程能够直接生成边界框,无需任何额外的后处理即可获取边界框的 logits 和坐标。该模型旨在与对应的 ImageProcessor 配合使用,将图像调整为 640x640 的尺寸。调整为其他尺寸通常会导致性能下降。
import requests
import torch
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", device_map="auto")
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([(image.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。
RTDetrConfig
class transformers.RTDetrConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneis_encoder_decoder: bool = Trueinitializer_range: float = 0.01initializer_bias_prior_prob: float | None = Nonelayer_norm_eps: float = 1e-05batch_norm_eps: float = 1e-05backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonefreeze_backbone_batch_norms: bool = Trueencoder_hidden_dim: int = 256encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)encoder_layers: int = 1encoder_ffn_dim: int = 1024encoder_attention_heads: int = 8dropout: float | int = 0.0activation_dropout: float | int = 0.0encode_proj_layers: list[int] | tuple[int, ...] = (2,)positional_encoding_temperature: int = 10000encoder_activation_function: str = 'gelu'activation_function: str = 'silu'eval_size: int | None = Nonenormalize_before: bool = Falsehidden_expansion: float = 1.0d_model: int = 256num_queries: int = 300decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)decoder_ffn_dim: int = 1024num_feature_levels: int = 3decoder_n_points: int = 4decoder_layers: int = 6decoder_attention_heads: int = 8decoder_activation_function: str = 'relu'attention_dropout: float | int = 0.0num_denoising: int = 100label_noise_ratio: float = 0.5box_noise_scale: float = 1.0learn_initial_query: bool = Falseanchor_image_size: int | list[int] | None = Nonedisable_custom_kernels: bool = Truewith_box_refine: bool = Truematcher_alpha: float = 0.25matcher_gamma: float = 2.0matcher_class_cost: float = 2.0matcher_bbox_cost: float = 5.0matcher_giou_cost: float = 2.0use_focal_loss: bool = Trueauxiliary_loss: bool = Truefocal_loss_alpha: float = 0.75focal_loss_gamma: float = 2.0weight_loss_vfl: float = 1.0weight_loss_bbox: float = 5.0weight_loss_giou: float = 2.0eos_coefficient: float = 0.0001 )
参数
- is_encoder_decoder (
bool,可选,默认为True) — 指示该模型是否用作编码器/解码器。 - initializer_range (
float,可选,默认为0.01) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - 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 (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。 - freeze_backbone_batch_norms (
bool,可选,默认为True) — 是否冻结主干网络中的批归一化层。 - encoder_hidden_dim (
int,可选,默认为256) — 隐藏表示的维度。 - encoder_in_channels (
list,可选,默认为[512, 1024, 2048]) — 编码器的多级特征输入。 - feat_strides(
list[int],可选,默认为[8, 16, 32])— 每个特征图中使用的步长。 - encoder_layers (
int,可选,默认为1) — Transformer 编码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - encoder_ffn_dim (
int,可选,默认为1024) — 编码器中“中间”(通常称为前馈)层的维度。 - encoder_attention_heads (
int,可选,默认为8) — Transformer 编码器中每个注意力层的注意力头数量。 - dropout (
Union[float, int],可选,默认为0.0) — 所有 dropout 层的比率。 - activation_dropout (
Union[float, int],可选,默认为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"等。 - 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) — Transformer 解码器中的隐藏层数量。如果未设置,将使用与num_layers相同的值。 - decoder_attention_heads (
int,可选,默认为8) — Transformer 解码器中每个注意力层的注意力头数量。 - decoder_activation_function (
str,可选,默认为"relu") — 解码器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"、"relu"、"silu"和"gelu_new"。 - attention_dropout (
Union[float, int],可选,默认为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) — 是否应用迭代式边界框细化,即每个解码器层基于上一层的预测结果来细化边界框。 - 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) — 在目标检测损失中,变焦点损失的相对权重。 - weight_loss_bbox (
float,可选,默认值为 5.0) — 目标检测损失中 L1 边界框损失的相对权重。 - weight_loss_giou (
float,可选,默认为 2.0) — 目标检测损失中广义 IoU 损失的相对权重。 - eos_coefficient (
float,可选,默认为0.0001) — 目标检测损失中“无目标”类别的相对分类权重。
这是用于存储 RTDetrModel 配置的类。它根据指定的参数实例化 Rt Detr 模型,并定义模型架构。使用默认值实例化配置将得到与 PekingU/rtdetr_r50vd 类似的配置。
配置对象继承自 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.configRTDetrResNetConfig
类 transformers.RTDetrResNetConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonenum_channels: int = 3embedding_size: int = 64hidden_sizes: list[int] | tuple[int, ...] = (256, 512, 1024, 2048)depths: list[int] | tuple[int, ...] = (3, 4, 6, 3)layer_type: str = 'bottleneck'hidden_act: str = 'relu'downsample_in_first_stage: bool = Falsedownsample_in_bottleneck: bool = False_out_features: list[str] | None = None_out_indices: list[int] | None = None )
参数
- num_channels (
int,可选,默认为3) — 输入通道的数量。 - embedding_size (
int,可选,默认为64) — 嵌入和隐藏状态的维度。 - hidden_sizes (
Union[list[int], tuple[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,第一阶段将使用stride为 2 的方式对输入进行下采样。 - downsample_in_bottleneck (
bool,可选,默认为False) — 如果为True,ResNetBottleNeckLayer 中的第一个 1x1 卷积层将使用stride为 2 的方式对输入进行下采样。
这是用于存储 Rt Detr ResnetModel 配置的类。它根据指定的参数实例化 Rt Detr 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.configRTDetrImageProcessor
class transformers.RTDetrImageProcessor
< source >( **kwargs: *<class 'transformers.models.rt_detr.image_processing_rt_detr.RTDetrImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 640, 'width': 640}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为False) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool,kwargs,可选,默认为False) — 是否对图像进行填充。填充方式是将图像填充到批次中的最大尺寸,或填充到每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - format (
str, kwargs, optional, 默认为AnnotationFormat.COCO_DETECTION) — 标注的数据格式。取值为 “coco_detection” 或 “coco_panoptic” 之一。 - do_convert_annotations (
bool,kwargs,可选,默认为True) — 控制是否将标注转换为 RT_DETR 模型所期望的格式。将边界框转换为(center_x, center_y, width, height)格式,且取值范围为[0, 1]。 可以通过preprocess方法中的do_convert_annotations参数进行覆盖。
构建一个 RTDetrImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class 'transformers.models.rt_detr.image_processing_rt_detr.RTDetrImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - annotations(
AnnotationType或list[AnnotationType],可选)— 根据应用于图像的填充进行转换的注释。 - return_segmentation_masks (
bool,可选,默认为self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str或pathlib.Path,可选) — 包含分割掩码的目录路径。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - format (
str, kwargs, optional, 默认为AnnotationFormat.COCO_DETECTION) — 标注的数据格式。取值为 “coco_detection” 或 “coco_panoptic” 之一。 - do_convert_annotations (
bool, kwargs, 可选,默认为True) — 控制是否将标注转换为 RT_DETR 模型所期望的格式。将边界框转换为(center_x, center_y, width, height)格式,且取值范围为[0, 1]。 可通过preprocess方法中的do_convert_annotations参数进行覆盖。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_object_detection
< source >( outputsthreshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] = Noneuse_focal_loss: bool = True ) → list[Dict]
参数
- outputs (
DetrObjectDetectionOutput) — 模型的原始输出。 - threshold (
float,可选,默认为 0.5) — 用于保留目标检测预测结果的分数阈值。 - target_sizes (
torch.Tensor或list[tuple[int, int]],可选) — 形状为(batch_size, 2)的张量,或包含目标尺寸(height, width)的元组列表(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。
RTDetrImageProcessorPil
class transformers.RTDetrImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.rt_detr.image_processing_pil_rt_detr.RTDetrImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 640, 'width': 640}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为False) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool,kwargs,可选,默认为False) — 是否对图像进行填充。填充方式是将图像填充到批次中的最大尺寸,或填充到每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - format (
str, kwargs, optional, 默认为AnnotationFormat.COCO_DETECTION) — 标注的数据格式。取值为 “coco_detection” 或 “coco_panoptic” 之一。 - do_convert_annotations (
bool,kwargs,可选,默认为True) — 控制是否将标注转换为 RT_DETR 模型所期望的格式。将边界框转换为(center_x, center_y, width, height)格式,且取值范围为[0, 1]。 可以通过preprocess方法中的do_convert_annotations参数进行覆盖。
构建一个 RTDetrImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = Nonereturn_segmentation_masks: bool | None = Nonemasks_path: str | pathlib.Path | None = None**kwargs: *<class 'transformers.models.rt_detr.image_processing_pil_rt_detr.RTDetrImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - annotations(
AnnotationType或list[AnnotationType],可选)— 根据应用于图像的填充进行转换的注释。 - return_segmentation_masks (
bool,可选,默认为self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str或pathlib.Path,可选) — 包含分割掩码的目录路径。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - format (
str, kwargs, optional, 默认为AnnotationFormat.COCO_DETECTION) — 标注的数据格式。取值为 “coco_detection” 或 “coco_panoptic” 之一。 - do_convert_annotations (
bool,kwargs,可选,默认为True) — 控制是否将标注转换为 RT_DETR 模型所期望的格式。将边界框转换为(center_x, center_y, width, height)格式,且取值范围为[0, 1]。 可以通过preprocess方法中的do_convert_annotations参数进行覆盖。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_object_detection
< source >( outputsthreshold: float = 0.5target_sizes: transformers.utils.generic.TensorType | list[tuple] = Noneuse_focal_loss: bool = True ) → list[Dict]
参数
- outputs (
DetrObjectDetectionOutput) — 模型的原始输出。 - threshold (
float,可选,默认为 0.5) — 用于保留目标检测预测结果的分数阈值。 - target_sizes (
torch.Tensor或list[tuple[int, int]],可选) — 形状为(batch_size, 2)的张量,或包含目标尺寸(height, width)的元组列表(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。
RTDetrModel
class transformers.RTDetrModel
< source >( config: RTDetrConfig )
参数
- config (RTDetrConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
RT-DETR 模型(由骨干网络和编码器-解码器组成),输出未经任何头部处理的原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: FloatTensorpixel_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → RTDetrModelOutput or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - pixel_mask (
torch.LongTensor形状为(batch_size, height, width), 可选) — 用于避免对填充像素值执行注意力机制的掩码。掩码值取自[0, 1]:- 对于真实的像素(即未被掩码的像素),值为 1,
- 对于填充像素(即 被屏蔽 的像素),值为 0。
- encoder_outputs (
torch.FloatTensor, 可选) — 元组由 (last_hidden_state, 可选:hidden_states, 可选:attentions)last_hidden_state的形状为(batch_size, sequence_length, hidden_size), 可选),是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。 - inputs_embeds (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,除了传入展平的特征图(backbone + 投影层的输出)之外,你还可以选择直接传入图像的展平表示。 - labels (
list[Dict],长度为(batch_size,),可选) — 用于计算二部图匹配损失的标签。一个字典列表,每个字典至少包含以下 2 个键:‘class_labels’ 和 ‘boxes’(分别对应批次中某张图像的分类标签和边界框)。分类标签本身应是一个长度为(number of bounding boxes in the image,)的torch.LongTensor,边界框应是一个形状为(number of bounding boxes in the image, 4)的torch.FloatTensor。
返回值
RTDetrModelOutput 或 tuple(torch.FloatTensor)
RTDetrModelOutput 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。
RTDetrModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
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)— 堆叠的中间参考点(解码器每一层的参考点)。intermediate_predicted_corners(形状为
(batch_size, config.decoder_layers, num_queries, 4)的torch.FloatTensor)— 堆叠的中间预测角点(解码器每一层预测的角点)。initial_reference_points(形状为
(batch_size, num_queries, 4)的torch.FloatTensor)— 用于第一个解码器层的初始参考点。decoder_hidden_states (
tuple[torch.FloatTensor],可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每一层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。解码器在每一层输出处的隐藏状态,以及初始嵌入输出。
decoder_attentions(
tuple[torch.FloatTensor],可选,在传入output_attentions=True或config.output_attentions=True时返回)—— 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器在注意力 softmax 之后的注意力权重,用于在自注意力头中计算加权平均值。
cross_attentions(
tuple[torch.FloatTensor],可选,当传入output_attentions=True或config.output_attentions=True时返回)—— 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器交叉注意力层在注意力 softmax 之后的注意力权重,用于在交叉注意力头中计算加权平均值。
encoder_last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor,可选)— 模型编码器最后一层输出的隐藏状态序列。encoder_hidden_states (
tuple[torch.FloatTensor],可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。编码器在每一层输出处的隐藏状态,以及初始嵌入输出。
encoder_attentions(
tuple[torch.FloatTensor],可选,当传入output_attentions=True或config.output_attentions=True时返回)—— 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。编码器在注意力 softmax 之后的注意力权重,用于在自注意力头中计算加权平均值。
init_reference_points(形状为
(batch_size, num_queries, 4)的torch.FloatTensor)— 通过 Transformer 解码器传递的初始参考点。enc_topk_logits (
torch.FloatTensor,形状为(batch_size, sequence_length, config.num_labels)) — 预测的边界框分数,其中得分最高的config.two_stage_num_proposals个边界框将在编码器阶段被选为区域建议。这是边界框二分类(即前景和背景)的输出。enc_topk_bboxes(形状为
(batch_size, sequence_length, 4)的torch.FloatTensor)— 编码器阶段预测的边界框坐标的 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(形状为
(batch_size, sequence_length, 4)的torch.FloatTensor,可选,当config.with_box_refine=True且config.two_stage=True时返回) — 第一阶段中预测的边界框坐标的 logits。denoising_meta_values (
dict,可选) — 用于去噪相关值的额外字典。
示例:
>>> from transformers import AutoImageProcessor, RTDetrModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> image_processor = AutoImageProcessor.from_pretrained("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 模型(由 backbone 和 encoder-decoder 组成)输出 bounding boxes 和 logits,以便进一步解码为 scores 和 classes。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: FloatTensorpixel_mask: typing.Optional[torch.LongTensor] = Noneencoder_outputs: typing.Optional[torch.FloatTensor] = Noneinputs_embeds: typing.Optional[torch.FloatTensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → RTDetrObjectDetectionOutput or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor,形状为(batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - pixel_mask (
torch.LongTensor形状为(batch_size, height, width), 可选) — 用于避免对填充像素值执行注意力机制的掩码。掩码值取自[0, 1]:- 对于真实的像素(即未被掩码的像素),值为 1,
- 对于填充像素(即 被屏蔽 的像素),值为 0。
- encoder_outputs (
torch.FloatTensor, 可选) — 元组由 (last_hidden_state, 可选:hidden_states, 可选:attentions)last_hidden_state的形状为(batch_size, sequence_length, hidden_size), 可选),是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。 - inputs_embeds (
torch.FloatTensor,形状为(batch_size, sequence_length, hidden_size),可选) — 可选地,除了传入展平的特征图(backbone + 投影层的输出)之外,你还可以选择直接传入图像的展平表示。 - labels (
list[Dict],长度为(batch_size,),可选) — 用于计算二部图匹配损失的标签。一个字典列表,每个字典至少包含以下 2 个键:‘class_labels’ 和 ‘boxes’(分别对应批次中某张图像的分类标签和边界框)。分类标签本身应是一个长度为(number of bounding boxes in the image,)的torch.LongTensor,边界框应是一个形状为(number of bounding boxes in the image, 4)的torch.FloatTensor。
返回值
RTDetrObjectDetectionOutput 或 tuple(torch.FloatTensor)
RTDetrObjectDetectionOutput 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。
RTDetrForObjectDetection 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.FloatTensor,形状为(1,),可选,在提供labels时返回)) — 总损失,是类别预测的负对数似然(交叉熵)与边界框损失的线性组合。后者定义为 L1 损失与广义尺度不变 IoU 损失的线性组合。loss_dict (
Dict,可选) — 包含各项单独损失的字典。适用于日志记录。logits(形状为
(batch_size, num_queries, num_classes + 1)的torch.FloatTensor)— 所有查询的分类 logits(包含 no-object)。pred_boxes(形状为
(batch_size, num_queries, 4)的torch.FloatTensor)— 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内进行归一化,相对于批次中每张图片各自的尺寸(忽略可能的填充)。您可以使用 post_process_object_detection() 来获取未归一化(绝对)的边界框。auxiliary_outputs (
list[Dict],可选) — 可选,仅在启用辅助损失(即config.auxiliary_loss设置为True)且提供了标签时返回。它是一个字典列表,包含每个解码器层的上述两个键(logits和pred_boxes)。last_hidden_state(形状为
(batch_size, num_queries, hidden_size)的torch.FloatTensor)— 模型解码器最后一层输出的隐藏状态序列。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)— 堆叠的中间参考点(解码器每一层的参考点)。intermediate_predicted_corners(形状为
(batch_size, config.decoder_layers, num_queries, 4)的torch.FloatTensor)— 堆叠的中间预测角点(解码器每一层预测的角点)。initial_reference_points(形状为
(batch_size, config.decoder_layers, num_queries, 4)的torch.FloatTensor)— 堆叠的初始参考点(解码器每一层的初始参考点)。decoder_hidden_states (
tuple[torch.FloatTensor],可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每一层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。解码器在每一层输出处的隐藏状态,以及初始嵌入输出。
decoder_attentions(
tuple[torch.FloatTensor],可选,在传入output_attentions=True或config.output_attentions=True时返回)—— 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器在注意力 softmax 之后的注意力权重,用于在自注意力头中计算加权平均值。
cross_attentions(
tuple[torch.FloatTensor],可选,当传入output_attentions=True或config.output_attentions=True时返回)—— 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器交叉注意力层在注意力 softmax 之后的注意力权重,用于在交叉注意力头中计算加权平均值。
encoder_last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.FloatTensor,可选)— 模型编码器最后一层输出的隐藏状态序列。encoder_hidden_states (
tuple[torch.FloatTensor],可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。编码器在每一层输出处的隐藏状态,以及初始嵌入输出。
encoder_attentions(
tuple[torch.FloatTensor],可选,当传入output_attentions=True或config.output_attentions=True时返回)—— 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。编码器在注意力 softmax 之后的注意力权重,用于在自注意力头中计算加权平均值。
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 (
torch.FloatTensor,形状为(batch_size, sequence_length, config.num_labels),可选,当config.with_box_refine=True且config.two_stage=True时返回) — 预测的边界框分数,其中得分最高的config.two_stage_num_proposals个边界框在第一阶段被选为区域建议。这是边界框二分类(即前景和背景)的输出。enc_outputs_coord_logits(形状为
(batch_size, sequence_length, 4)的torch.FloatTensor,可选,当config.with_box_refine=True且config.two_stage=True时返回) — 第一阶段中预测的边界框坐标的 logits。denoising_meta_values (
dict,可选) — 用于去噪相关值的额外字典
示例:
>>> from transformers import RTDetrImageProcessor, RTDetrForObjectDetection
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> 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: RTDetrResNetConfig )
参数
- config (RTDetrResNetConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
ResNet 骨干网络,用于与 RTDETR 等框架配合使用。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensoroutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BackboneOutput or tuple(torch.FloatTensor)
参数
- pixel_values(形状为
(batch_size, num_channels, image_size, image_size)的torch.Tensor)— 对应于输入图像的张量。可以使用image_processor_class获取像素值。有关详细信息,请参阅image_processor_class.__call__(processor_class使用image_processor_class来处理图像)。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
BackboneOutput 或 tuple(torch.FloatTensor)
BackboneOutput 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(RTDetrResNetConfig)和输入。
RTDetrResNetBackbone 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
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),具体取决于骨干网络。模型在每个阶段输出处的隐藏状态,以及初始嵌入输出。
attentions(
tuple(torch.FloatTensor),可选,当传入output_attentions=True或config.output_attentions=True时返回)—— 一个torch.FloatTensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力机制时适用。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from transformers import RTDetrResNetConfig, RTDetrResNetBackbone
>>> import torch
precation import deprecate_kwarg
precation import deprecate_kwarg
precation import deprecate_kwarg
utils.deprecation import deprecate_kwarg
utils.deprecation import deprecate_kwarg
>>> 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]