Transformers documentation
LW-DETR
该模型于 2024-07-24 在 HF papers 上发布,并于 2026-01-12 贡献至 Hugging Face Transformers。
LW-DETR
LW-DETR 提出了一种轻量级的 Detection Transformer (DETR) 架构,旨在实时目标检测领域与主流的 YOLO 系列竞争并超越其性能。该架构通过结合最新的 transformer 进展与高效的设计选择,在速度(延迟)和精度(mAP)之间实现了新的最先进平衡。
LW-DETR 架构以其简洁高效的架构为特点:一个普通的 ViT Encoder、一个 Projector 和一个浅层 DETR Decoder。 它通过以下核心修改来增强 DETR 架构的效率和速度:
- 高效 ViT 编码器:采用朴素的 ViT,结合交替的窗口/全局注意力机制以及以窗口为主的组织方式,从而大幅降低注意力计算的复杂度和延迟。
- 更丰富的输入:聚合来自编码器的多级特征,并使用 C2f Projector(YOLOv8)传递两个尺度的特征($1/8$ 和 $1/32$)。
- 更快的解码器:采用浅层 3 层 DETR 解码器,并结合可变形交叉注意力机制,以降低延迟并加快收敛速度。
- 优化查询:采用混合查询方案,结合可学习的内容查询和生成的空间查询。
您可以在 AnnaZhang 组织下找到所有可用的 LW DETR 检查点。 原始代码可在此处找到。
该模型由 stevenbucaille 贡献。
点击右侧边栏中的 LW-DETR 模型,以查看更多将 LW-DETR 应用于不同目标检测任务的示例。
以下示例演示了如何使用 Pipeline 和 AutoModel 类执行目标检测。
from transformers import pipeline
pipeline = pipeline(
"object-detection",
model="AnnaZhang/lwdetr_small_60e_coco",
device_map=0
)
pipeline("http://images.cocodataset.org/val2017/000000039769.jpg")import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForObjectDetection
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
image_processor = AutoImageProcessor.from_pretrained("AnnaZhang/lwdetr_small_60e_coco")
model = AutoModelForObjectDetection.from_pretrained("AnnaZhang/lwdetr_small_60e_coco", device_map="auto")
# prepare image for the model
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
with torch.no_grad():
outputs = model(**inputs)
results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([image.size[::-1]]), threshold=0.3)
for result in results:
for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
score, label = score.item(), label_id.item()
box = [round(i, 2) for i in box.tolist()]
print(f"{model.config.id2label[label]}: {score:.2f} {box}")资源
以下是 Hugging Face 官方和社区(以 🌎 标识)提供的资源列表,可帮助您快速上手 LwDetr。
- 另请参阅:目标检测任务指南。
LwDetrConfig
class transformers.LwDetrConfig
< 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 = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprojector_scale_factors: list[float] | tuple[float, ...] = ()hidden_expansion: float = 0.5c2f_num_blocks: int = 3activation_function: str = 'silu'batch_norm_eps: float = 1e-05dropout: float | int = 0.0decoder_ffn_dim: int = 2048decoder_n_points: int = 4decoder_layers: int = 3decoder_self_attention_heads: int = 8decoder_cross_attention_heads: int = 16decoder_activation_function: str = 'relu'num_queries: int = 300attention_bias: bool = Trueattention_dropout: float | int = 0.0activation_dropout: float | int = 0.0group_detr: int = 13init_std: float = 0.02disable_custom_kernels: bool = Trueclass_cost: int | float = 2bbox_cost: int | float = 5giou_cost: int | float = 2class_loss_coefficient: int | float = 1dice_loss_coefficient: int | float = 1bbox_loss_coefficient: int | float = 5giou_loss_coefficient: int | float = 2eos_coefficient: float = 0.1focal_alpha: float = 0.25auxiliary_loss: bool = Trued_model: int = 256 )
参数
- backbone_config (
Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。 - projector_scale_factors (
list[float],可选,默认为[]) — 特征金字塔网络的缩放因子。每个缩放因子决定了不同层级特征的分辨率。支持的值为 0.5、1.0 和 2.0。 - hidden_expansion (
float,可选,默认为 0.5) — 投影层中隐藏维度的扩展因子。 - c2f_num_blocks (
int,可选,默认为 3) — C2F 层中的块数。 - activation_function (
str,可选,默认为"silu") — 投影器中使用的非线性激活函数。支持的取值为"silu"、"relu"、"gelu"。 - batch_norm_eps (
float,可选,默认值为 1e-05) — 批归一化层的 epsilon 值。 - dropout (
Union[float, int],可选,默认为0.0) — 所有 dropout 层的比率。 - decoder_ffn_dim (
int, 可选,默认为 2048) — 解码器中“中间”(通常称为前馈)层的维度。 - decoder_n_points (
int,可选,默认为 4) — 解码器中每个注意力头在每个特征层级上采样的键数量。 - decoder_layers (
int, 可选,默认为3) — Transformer 解码器中的隐藏层数。如果未设置,将使用与num_layers相同的值。 - decoder_self_attention_heads (
int,可选,默认为 8) — 解码器自注意力中每个注意力层的注意力头数量。 - decoder_cross_attention_heads (
int, 可选,默认为 16) — 解码器交叉注意力中每个注意力层的注意力头数量。 - decoder_activation_function (
str,可选,默认为"relu") — 解码器中的非线性激活函数。支持的值为"relu"、"silu"、"gelu"。 - num_queries (
int,可选,默认为 300) — 对象查询的数量,即检测槽位。这是 LwDetrModel 在单张图像中可检测到的最大对象数量。 - attention_bias (
bool,可选,默认为True) — 在自注意力机制中,是否在查询、键、值以及输出投影层中使用偏置。 - attention_dropout (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - activation_dropout (
Union[float, int],可选,默认为0.0) — 全连接层中激活值的 dropout 比率。 - group_detr (
int, 可选,默认为 13) — Group DETR 注意力机制的组数,有助于降低计算复杂度。 - init_std (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - disable_custom_kernels (
bool,可选,默认为True) — 禁用自定义 CUDA 和 CPU 内核。此选项对于 ONNX 导出是必需的,因为 PyTorch ONNX 导出不支持自定义内核。 - class_cost (
Union[int, float],可选,默认为2) — 匈牙利匹配代价中分类错误的相对权重。 - bbox_cost (
Union[int, float],可选,默认为5) — 匈牙利匹配代价中 L1 边界框误差的相对权重。 - giou_cost (
Union[int, float],可选,默认为2) — 匈牙利匹配代价中广义 IoU 损失的相对权重。 - class_loss_coefficient (
float,可选,默认为 1) — 匈牙利匹配代价中分类损失的相对权重。 - dice_loss_coefficient (
Union[int, float], 可选,默认为1) — 在全景分割损失中,Dice 损失的相对权重。 - bbox_loss_coefficient (
Union[int, float],可选,默认为5) — 全景分割损失中 L1 边界框损失的相对权重。 - giou_loss_coefficient (
Union[int, float], 可选,默认为2) — 全景分割损失中广义 IoU 损失的相对权重。 - eos_coefficient (
float,可选,默认为0.1) — 目标检测损失中“无目标”类别的相对分类权重。 - focal_alpha (
float,可选,默认为0.25) — Focal loss 中的 Alpha 参数。 - auxiliary_loss (
bool,可选,默认为True) — 是否使用辅助解码损失(即每个解码器层的损失)。 - d_model (
int,可选,默认为256) — 编码器层和池化层的维度大小。
这是用于存储 LwDetrModel 配置的类。它根据指定的参数实例化 Lw Detr 模型,并定义模型架构。使用默认值实例化配置将生成与 AnnaZhang/lwdetr_small_60e_coco 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import LwDetrConfig, LwDetrModel
>>> # Initializing a LW-DETR AnnaZhang/lwdetr_small_60e_coco style configuration
>>> configuration = LwDetrConfig()
>>> # Initializing a model (with random weights) from the AnnaZhang/lwdetr_small_60e_coco style configuration
>>> model = LwDetrModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configLwDetrViTConfig
类 transformers.LwDetrViTConfig
< 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 = Nonehidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12mlp_ratio: int = 4hidden_act: str = 'gelu'dropout_prob: float | int = 0.0initializer_range: float = 0.02layer_norm_eps: float = 1e-06image_size: int | list[int] | tuple[int, int] = 256pretrain_image_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 16num_channels: int = 3qkv_bias: bool = Truewindow_block_indices: list[int] | tuple[int, ...] = ()use_absolute_position_embeddings: bool = True_out_features: list[str] | None = None_out_indices: list[int] | None = Nonecae_init_values: float = 0.1num_windows: int = 16 )
参数
- hidden_size (
int,可选,默认为768) — 隐藏表示的维度。 - num_hidden_layers (
int, 可选, 默认为12) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为12) — Transformer 解码器中每个注意力层的注意力头数量。 - mlp_ratio (
int,可选,默认为4) — MLP 隐藏层维度与嵌入维度的比值。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - dropout_prob (
Union[float, int],可选,默认为0.0) — 所有 dropout 层的比率。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float,可选,默认为1e-06) — 层归一化层所使用的 epsilon 值。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为256) — 每张图片的尺寸(分辨率)。 - pretrain_image_size (
int,可选,默认为 224) — 预训练期间每张图片的尺寸(分辨率)。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为16) — 每个 patch 的大小(分辨率)。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - qkv_bias (
bool,可选,默认为True) — 是否向查询、键和值添加偏置。 - window_block_indices (
list[int],可选,默认为[]) — 应使用窗口注意力而非常规全局自注意力的块索引列表。 - use_absolute_position_embeddings (
bool,可选,默认为True) — 是否向 patch 嵌入中添加绝对位置嵌入。 - cae_init_values (
float, 可选,默认为 0.1) — 当启用use_cae时,CAE 参数的初始化值。 - num_windows (
int,可选,默认为 16) — 基于窗口的注意力机制的窗口数量。该值必须是一个完全平方数,且图像尺寸必须能被该值的平方根整除。这可以实现高效的窗口优先特征图组织。
这是用于存储 LwDetrModel 配置的类。它根据指定的参数实例化 Lw Detr 模型,并定义模型架构。使用默认值实例化配置将生成与 AnnaZhang/lwdetr_small_60e_coco 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import LwDetrViTConfig, LwDetrViTModel
>>> # Initializing a LW-DETR ViT configuration
>>> configuration = LwDetrViTConfig()
>>> # Initializing a model (with random weights) from the configuration
>>> model = LwDetrViTModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configLwDetrModel
class transformers.LwDetrModel
< source >( config: LwDetrConfig )
参数
- config (LwDetrConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
原始的 LW Detr 模型(由骨干网络和解码器 Transformer 组成),输出未经任何特定头部处理的原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor = Nonepixel_mask: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → LwDetrModelOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 DeformableDetrImageProcessor 获取像素值。有关详细信息,请参阅 DeformableDetrImageProcessor.call()(processor_class使用 DeformableDetrImageProcessor 处理图像)。 - pixel_mask (
torch.LongTensor形状为(batch_size, height, width), 可选) — 用于避免对填充像素值执行注意力机制的掩码。掩码值取自[0, 1]:- 对于真实的像素(即未被掩码的像素),值为 1,
- 对于填充像素(即 被屏蔽 的像素),值为 0。
返回值
LwDetrModelOutput 或 tuple(torch.Tensor)
LwDetrModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(LwDetrConfig)和输入。
LwDetrModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
init_reference_points(形状为
(batch_size, num_queries, 4)的torch.Tensor)— 通过 Transformer 解码器传输的初始参考点。last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选)— 模型最后一层输出的隐藏状态序列。intermediate_hidden_states(形状为
(batch_size, config.decoder_layers, num_queries, hidden_size)的torch.Tensor)— 堆叠的中间隐藏状态(解码器每一层的输出)。intermediate_reference_points(形状为
(batch_size, config.decoder_layers, num_queries, 4)的torch.Tensor)— 堆叠的中间参考点(解码器每一层的参考点)。enc_outputs_class (
torch.Tensor,形状为(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.Tensor,形状为(batch_size, sequence_length, 4),可选,当config.with_box_refine=True且config.two_stage=True时返回) — 第一阶段中预测的边界框坐标的 logits。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple[torch.Tensor, ...],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
cross_attentions (
tuple[torch.Tensor, ...],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器交叉注意力层在注意力 softmax 之后的注意力权重,用于在交叉注意力头中计算加权平均值。
示例:
>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> image_processor = AutoImageProcessor.from_pretrained("AnnaZhang/lwdetr_small_60e_coco")
>>> model = DeformableDetrModel.from_pretrained("AnnaZhang/lwdetr_small_60e_coco")
>>> 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]LwDetrForObjectDetection
class transformers.LwDetrForObjectDetection
< source >( config: LwDetrConfig )
参数
- config (LwDetrConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
LW DETR 模型(由骨干网络和解码器 Transformer 组成),顶部带有目标检测头,用于 COCO 检测等任务。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor = Nonepixel_mask: typing.Optional[torch.LongTensor] = Nonelabels: list[dict] | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → LwDetrObjectDetectionOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 DeformableDetrImageProcessor 获取像素值。有关详细信息,请参阅 DeformableDetrImageProcessor.call()(processor_class使用 DeformableDetrImageProcessor 处理图像)。 - pixel_mask (
torch.LongTensor形状为(batch_size, height, width), 可选) — 用于避免对填充像素值执行注意力机制的掩码。掩码值取自[0, 1]:- 对于真实的像素(即未被掩码的像素),值为 1,
- 对于填充像素(即 被屏蔽 的像素),值为 0。
- 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.Tensor。
返回值
LwDetrObjectDetectionOutput 或 tuple(torch.Tensor)
LwDetrObjectDetectionOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(LwDetrConfig)和输入。
LwDetrForObjectDetection 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,在提供labels时返回)) — 总损失,是类别预测的负对数似然(交叉熵)与边界框损失的线性组合。后者定义为 L1 损失与广义尺度不变 IoU 损失的线性组合。loss_dict (
Dict,可选) — 包含各项单独损失的字典。适用于日志记录。logits(形状为
(batch_size, num_queries, num_classes + 1)的torch.Tensor)— 所有查询的分类 logits(包括 no-object)。pred_boxes(形状为
(batch_size, num_queries, 4)的torch.Tensor)— 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每张图片的单独尺寸(忽略可能的填充)。您可以使用~DeformableDetrProcessor.post_process_object_detection来获取未归一化的边界框。auxiliary_outputs (
list[Dict],可选) — 可选,仅在启用辅助损失(即config.auxiliary_loss设置为True)且提供了标签时返回。它是一个字典列表,包含每个解码器层的上述两个键(logits和pred_boxes)。init_reference_points(形状为
(batch_size, num_queries, 4)的torch.Tensor)— 通过 Transformer 解码器传输的初始参考点。last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选)— 模型最后一层输出的隐藏状态序列。intermediate_hidden_states(形状为
(batch_size, config.decoder_layers, num_queries, hidden_size)的torch.Tensor)— 堆叠的中间隐藏状态(解码器每一层的输出)。intermediate_reference_points(形状为
(batch_size, config.decoder_layers, num_queries, 4)的torch.Tensor)— 堆叠的中间参考点(解码器每一层的参考点)。enc_outputs_class (
torch.Tensor,形状为(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.Tensor,形状为(batch_size, sequence_length, 4),可选,当config.with_box_refine=True且config.two_stage=True时返回) — 第一阶段中预测的边界框坐标的 logits。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple[torch.Tensor, ...],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
cross_attentions (
tuple[torch.Tensor, ...],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。解码器交叉注意力层在注意力 softmax 之后的注意力权重,用于在交叉注意力头中计算加权平均值。
示例:
>>> from transformers import AutoImageProcessor, LwDetrForObjectDetection
>>> 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("AnnaZhang/lwdetr_small_60e_coco")
>>> model = LwDetrForObjectDetection.from_pretrained("AnnaZhang/lwdetr_small_60e_coco")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
... 0
... ]
>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
... box = [round(i, 2) for i in box.tolist()]
... print(
... f"Detected {model.config.id2label[label.item()]} with confidence "
... f"{round(score.item(), 3)} at location {box}"
... )
Detected cat with confidence 0.8 at location [16.5, 52.84, 318.25, 470.78]
Detected cat with confidence 0.789 at location [342.19, 24.3, 640.02, 372.25]
Detected remote with confidence 0.633 at location [40.79, 72.78, 176.76, 117.25]LwDetrViTBackbone
class transformers.LwDetrViTBackbone
< source >( config: LwDetrViTConfig )
参数
- config (LwDetrViTConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Lw Detr 骨干网络。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BackboneOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 DeformableDetrImageProcessor 获取像素值。有关详细信息,请参阅 DeformableDetrImageProcessor.call()(processor_class使用 DeformableDetrImageProcessor 处理图像)。
返回值
BackboneOutput 或 tuple(torch.Tensor)
BackboneOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(LwDetrConfig)和输入。
LwDetrViTBackbone 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
feature_maps(形状为
(batch_size, num_channels, height, width)的tuple(torch.Tensor))— 各阶段的特征图。hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层的输出以及每一层的输出),形状为(batch_size, sequence_length, hidden_size)或(batch_size, num_channels, height, width),具体取决于骨干网络。模型在每个阶段输出处的隐藏状态,以及初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力机制时适用。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from transformers import LwDetrViTConfig, LwDetrViTBackbone
>>> import torch
>>> config = LwDetrViTConfig()
>>> model = LwDetrViTBackbone(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, 768, 14, 14]