DETA
Overview
DETA モデルは、NMS Strikes Back で Jeffrey Ouyang-Zhang、Jang Hyun Cho、Xingyi Zhou、Philipp Krähenbühl によって提案されました。 DETA (Detection Transformers with Assignment の略) は、1 対 1 の 2 部ハンガリアン マッチング損失を置き換えることにより、Deformable DETR を改善します。 非最大抑制 (NMS) を備えた従来の検出器で使用される 1 対多のラベル割り当てを使用します。これにより、最大 2.5 mAP の大幅な増加が得られます。
論文の要約は次のとおりです。
Detection Transformer (DETR) は、トレーニング中に 1 対 1 の 2 部マッチングを使用してクエリを一意のオブジェクトに直接変換し、エンドツーエンドのオブジェクト検出を可能にします。最近、これらのモデルは、紛れもない優雅さで COCO の従来の検出器を上回りました。ただし、モデル アーキテクチャやトレーニング スケジュールなど、さまざまな設計において従来の検出器とは異なるため、1 対 1 マッチングの有効性は完全には理解されていません。この研究では、DETR での 1 対 1 のハンガリー語マッチングと、非最大監視 (NMS) を備えた従来の検出器での 1 対多のラベル割り当てとの間の厳密な比較を行います。驚くべきことに、NMS を使用した 1 対多の割り当ては、同じ設定の下で標準的な 1 対 1 のマッチングよりも一貫して優れており、最大 2.5 mAP という大幅な向上が見られます。従来の IoU ベースのラベル割り当てを使用して Deformable-DETR をトレーニングする当社の検出器は、ResNet50 バックボーンを使用して 12 エポック (1x スケジュール) 以内に 50.2 COCO mAP を達成し、この設定で既存のすべての従来の検出器またはトランスベースの検出器を上回りました。複数のデータセット、スケジュール、アーキテクチャに関して、私たちは一貫して、パフォーマンスの高い検出トランスフォーマーには二部マッチングが不要であることを示しています。さらに、検出トランスの成功は、表現力豊かなトランス アーキテクチャによるものであると考えています。
DETA の概要。 元の論文から抜粋。このモデルは、nielsr によって提供されました。 元のコードは ここ にあります。
Resources
DETA の使用を開始するのに役立つ公式 Hugging Face およびコミュニティ (🌎 で示されている) リソースのリスト。
- DETA のデモ ノートブックは こちら にあります。
- 参照: オブジェクト検出タスク ガイド
ここに含めるリソースの送信に興味がある場合は、お気軽にプル リクエストを開いてください。審査させていただきます。リソースは、既存のリソースを複製するのではなく、何か新しいものを示すことが理想的です。
DetaConfig
class transformers.DetaConfig
< source >( backbone_config = None backbone = None use_pretrained_backbone = False use_timm_backbone = False backbone_kwargs = None num_queries = 900 max_position_embeddings = 2048 encoder_layers = 6 encoder_ffn_dim = 2048 encoder_attention_heads = 8 decoder_layers = 6 decoder_ffn_dim = 1024 decoder_attention_heads = 8 encoder_layerdrop = 0.0 is_encoder_decoder = True activation_function = 'relu' d_model = 256 dropout = 0.1 attention_dropout = 0.0 activation_dropout = 0.0 init_std = 0.02 init_xavier_std = 1.0 return_intermediate = True auxiliary_loss = False position_embedding_type = 'sine' num_feature_levels = 5 encoder_n_points = 4 decoder_n_points = 4 two_stage = True two_stage_num_proposals = 300 with_box_refine = True assign_first_stage = True assign_second_stage = True class_cost = 1 bbox_cost = 5 giou_cost = 2 mask_loss_coefficient = 1 dice_loss_coefficient = 1 bbox_loss_coefficient = 5 giou_loss_coefficient = 2 eos_coefficient = 0.1 focal_alpha = 0.25 disable_custom_kernels = True **kwargs )
Parameters
- backbone_config (
PretrainedConfig
ordict
, optional, defaults toResNetConfig()
) — The configuration of the backbone model. - backbone (
str
, optional) — Name of backbone to use whenbackbone_config
isNone
. Ifuse_pretrained_backbone
isTrue
, this will load the corresponding pretrained weights from the timm or transformers library. Ifuse_pretrained_backbone
isFalse
, this loads the backbone’s config and uses that to initialize the backbone with random weights. - use_pretrained_backbone (
bool
, optional,False
) — Whether to use pretrained weights for the backbone. - use_timm_backbone (
bool
, optional,False
) — Whether to loadbackbone
from the timm library. IfFalse
, the backbone is loaded from the transformers library. - backbone_kwargs (
dict
, optional) — Keyword arguments to be passed to AutoBackbone when loading from a checkpoint e.g.{'out_indices': (0, 1, 2, 3)}
. Cannot be specified ifbackbone_config
is set. - num_queries (
int
, optional, defaults to 900) — Number of object queries, i.e. detection slots. This is the maximal number of objects DetaModel can detect in a single image. In casetwo_stage
is set toTrue
, we usetwo_stage_num_proposals
instead. - d_model (
int
, optional, defaults to 256) — Dimension of the layers. - encoder_layers (
int
, optional, defaults to 6) — Number of encoder layers. - decoder_layers (
int
, optional, defaults to 6) — Number of decoder layers. - encoder_attention_heads (
int
, optional, defaults to 8) — Number of attention heads for each attention layer in the Transformer encoder. - decoder_attention_heads (
int
, optional, defaults to 8) — Number of attention heads for each attention layer in the Transformer decoder. - decoder_ffn_dim (
int
, optional, defaults to 2048) — Dimension of the “intermediate” (often named feed-forward) layer in decoder. - encoder_ffn_dim (
int
, optional, defaults to 2048) — Dimension of the “intermediate” (often named feed-forward) layer in decoder. - activation_function (
str
orfunction
, optional, defaults to"relu"
) — The non-linear activation function (function or string) in the encoder and pooler. If string,"gelu"
,"relu"
,"silu"
and"gelu_new"
are supported. - dropout (
float
, optional, defaults to 0.1) — The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. - attention_dropout (
float
, optional, defaults to 0.0) — The dropout ratio for the attention probabilities. - activation_dropout (
float
, optional, defaults to 0.0) — The dropout ratio for activations inside the fully connected layer. - init_std (
float
, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices. - init_xavier_std (
float
, optional, defaults to 1) — The scaling factor used for the Xavier initialization gain in the HM Attention map module. - encoder_layerdrop (
float
, optional, defaults to 0.0) — The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more details. - auxiliary_loss (
bool
, optional, defaults toFalse
) — Whether auxiliary decoding losses (loss at each decoder layer) are to be used. - position_embedding_type (
str
, optional, defaults to"sine"
) — Type of position embeddings to be used on top of the image features. One of"sine"
or"learned"
. - class_cost (
float
, optional, defaults to 1) — Relative weight of the classification error in the Hungarian matching cost. - bbox_cost (
float
, optional, defaults to 5) — Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost. - giou_cost (
float
, optional, defaults to 2) — Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost. - mask_loss_coefficient (
float
, optional, defaults to 1) — Relative weight of the Focal loss in the panoptic segmentation loss. - dice_loss_coefficient (
float
, optional, defaults to 1) — Relative weight of the DICE/F-1 loss in the panoptic segmentation loss. - bbox_loss_coefficient (
float
, optional, defaults to 5) — Relative weight of the L1 bounding box loss in the object detection loss. - giou_loss_coefficient (
float
, optional, defaults to 2) — Relative weight of the generalized IoU loss in the object detection loss. - eos_coefficient (
float
, optional, defaults to 0.1) — Relative classification weight of the ‘no-object’ class in the object detection loss. - num_feature_levels (
int
, optional, defaults to 5) — The number of input feature levels. - encoder_n_points (
int
, optional, defaults to 4) — The number of sampled keys in each feature level for each attention head in the encoder. - decoder_n_points (
int
, optional, defaults to 4) — The number of sampled keys in each feature level for each attention head in the decoder. - two_stage (
bool
, optional, defaults toTrue
) — Whether to apply a two-stage deformable DETR, where the region proposals are also generated by a variant of DETA, which are further fed into the decoder for iterative bounding box refinement. - two_stage_num_proposals (
int
, optional, defaults to 300) — The number of region proposals to be generated, in casetwo_stage
is set toTrue
. - with_box_refine (
bool
, optional, defaults toTrue
) — Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes based on the predictions from the previous layer. - focal_alpha (
float
, optional, defaults to 0.25) — Alpha parameter in the focal loss. - assign_first_stage (
bool
, optional, defaults toTrue
) — Whether to assign each prediction i to the highest overlapping ground truth object if the overlap is larger than a threshold 0.7. - assign_second_stage (
bool
, optional, defaults toTrue
) — Whether to assign second assignment procedure in the second stage closely follows the first stage assignment procedure. - disable_custom_kernels (
bool
, optional, defaults toTrue
) — Disable the use of custom CUDA and CPU kernels. This option is necessary for the ONNX export, as custom kernels are not supported by PyTorch ONNX export.
This is the configuration class to store the configuration of a DetaModel. It is used to instantiate a DETA model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the DETA SenseTime/deformable-detr architecture.
Configuration objects inherit from PretrainedConfig and can be used to control the model outputs. Read the documentation from PretrainedConfig for more information.
Examples:
>>> from transformers import DetaConfig, DetaModel
>>> # Initializing a DETA SenseTime/deformable-detr style configuration
>>> configuration = DetaConfig()
>>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
>>> model = DetaModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
DetaImageProcessor
class transformers.DetaImageProcessor
< 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 = True 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 = True pad_size: typing.Optional[typing.Dict[str, int]] = None **kwargs )
Parameters
- format (
str
, optional, defaults to"coco_detection"
) — Data format of the annotations. One of “coco_detection” or “coco_panoptic”. - do_resize (
bool
, optional, defaults toTrue
) — Controls whether to resize the image’s (height, width) dimensions to the specifiedsize
. Can be overridden by thedo_resize
parameter in thepreprocess
method. - size (
Dict[str, int]
optional, defaults to{"shortest_edge" -- 800, "longest_edge": 1333}
): Size of the image’s(height, width)
dimensions after resizing. Can be overridden by thesize
parameter in thepreprocess
method. Available options are:{"height": int, "width": int}
: The image will be resized to the exact size(height, width)
. Do NOT keep the aspect ratio.{"shortest_edge": int, "longest_edge": int}
: The image will be resized to a maximum size respecting the aspect ratio and keeping the shortest edge less or equal toshortest_edge
and the longest edge less or equal tolongest_edge
.{"max_height": int, "max_width": int}
: The image will be resized to the maximum size respecting the aspect ratio and keeping the height less or equal tomax_height
and the width less or equal tomax_width
.
- resample (
PILImageResampling
, optional, defaults toPILImageResampling.BILINEAR
) — Resampling filter to use if resizing the image. - do_rescale (
bool
, optional, defaults toTrue
) — Controls whether to rescale the image by the specified scalerescale_factor
. Can be overridden by thedo_rescale
parameter in thepreprocess
method. - rescale_factor (
int
orfloat
, optional, defaults to1/255
) — Scale factor to use if rescaling the image. Can be overridden by therescale_factor
parameter in thepreprocess
method. - do_normalize —
Controls whether to normalize the image. Can be overridden by the
do_normalize
parameter in thepreprocess
method. - image_mean (
float
orList[float]
, optional, defaults toIMAGENET_DEFAULT_MEAN
) — Mean values to use when normalizing the image. Can be a single value or a list of values, one for each channel. Can be overridden by theimage_mean
parameter in thepreprocess
method. - image_std (
float
orList[float]
, optional, defaults toIMAGENET_DEFAULT_STD
) — Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one for each channel. Can be overridden by theimage_std
parameter in thepreprocess
method. - do_convert_annotations (
bool
, optional, defaults toTrue
) — Controls whether to convert the annotations to the format expected by the DETR model. Converts the bounding boxes to the format(center_x, center_y, width, height)
and in the range[0, 1]
. Can be overridden by thedo_convert_annotations
parameter in thepreprocess
method. - do_pad (
bool
, optional, defaults toTrue
) — Controls whether to pad the image. Can be overridden by thedo_pad
parameter in thepreprocess
method. IfTrue
, padding will be applied to the bottom and right of the image with zeros. Ifpad_size
is provided, the image will be padded to the specified dimensions. Otherwise, the image will be padded to the maximum height and width of the batch. - pad_size (
Dict[str, int]
, optional) — The size{"height": int, "width" int}
to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_size
is not provided, images will be padded to the largest height and width in the batch.
Constructs a Deformable DETR image processor.
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] annotations: typing.Union[typing.List[typing.Dict], typing.List[typing.List[typing.Dict]], NoneType] = None return_segmentation_masks: bool = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None do_resize: typing.Optional[bool] = None size: typing.Optional[typing.Dict[str, int]] = None resample = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Union[int, float, NoneType] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_annotations: typing.Optional[bool] = 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 **kwargs )
Parameters
- images (
ImageInput
) — Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False
. - annotations (
List[Dict]
orList[List[Dict]]
, optional) — List of annotations associated with the image or batch of images. If annotation is for object detection, the annotations should be a dictionary with the following keys:- “image_id” (
int
): The image id. - “annotations” (
List[Dict]
): List of annotations for an image. Each annotation should be a dictionary. An image can have no annotations, in which case the list should be empty. If annotation is for segmentation, the annotations should be a dictionary with the following keys: - “image_id” (
int
): The image id. - “segments_info” (
List[Dict]
): List of segments for an image. Each segment should be a dictionary. An image can have no segments, in which case the list should be empty. - “file_name” (
str
): The file name of the image.
- “image_id” (
- return_segmentation_masks (
bool
, optional, defaults to self.return_segmentation_masks) — Whether to return segmentation masks. - masks_path (
str
orpathlib.Path
, optional) — Path to the directory containing the segmentation masks. - do_resize (
bool
, optional, defaults to self.do_resize) — Whether to resize the image. - size (
Dict[str, int]
, optional, defaults to self.size) — Size of the image’s(height, width)
dimensions after resizing. Available options are:{"height": int, "width": int}
: The image will be resized to the exact size(height, width)
. Do NOT keep the aspect ratio.{"shortest_edge": int, "longest_edge": int}
: The image will be resized to a maximum size respecting the aspect ratio and keeping the shortest edge less or equal toshortest_edge
and the longest edge less or equal tolongest_edge
.{"max_height": int, "max_width": int}
: The image will be resized to the maximum size respecting the aspect ratio and keeping the height less or equal tomax_height
and the width less or equal tomax_width
.
- resample (
PILImageResampling
, optional, defaults to self.resample) — Resampling filter to use when resizing the image. - do_rescale (
bool
, optional, defaults to self.do_rescale) — Whether to rescale the image. - rescale_factor (
float
, optional, defaults to self.rescale_factor) — Rescale factor to use when rescaling the image. - do_normalize (
bool
, optional, defaults to self.do_normalize) — Whether to normalize the image. - image_mean (
float
orList[float]
, optional, defaults to self.image_mean) — Mean to use when normalizing the image. - image_std (
float
orList[float]
, optional, defaults to self.image_std) — Standard deviation to use when normalizing the image. - do_convert_annotations (
bool
, optional, defaults to self.do_convert_annotations) — Whether to convert the annotations to the format expected by the model. Converts the bounding boxes from the format(top_left_x, top_left_y, width, height)
to(center_x, center_y, width, height)
and in relative coordinates. - do_pad (
bool
, optional, defaults to self.do_pad) — Whether to pad the image. IfTrue
, padding will be applied to the bottom and right of the image with zeros. Ifpad_size
is provided, the image will be padded to the specified dimensions. Otherwise, the image will be padded to the maximum height and width of the batch. - format (
str
orAnnotationFormat
, optional, defaults to self.format) — Format of the annotations. - return_tensors (
str
orTensorType
, optional, defaults to self.return_tensors) — Type of tensors to return. IfNone
, will return the list of images. - data_format (
ChannelDimension
orstr
, optional, defaults toChannelDimension.FIRST
) — The channel dimension format for the output image. Can be one of:"channels_first"
orChannelDimension.FIRST
: image in (num_channels, height, width) format."channels_last"
orChannelDimension.LAST
: image in (height, width, num_channels) format.- Unset: Use the channel dimension format of the input image.
- input_data_format (
ChannelDimension
orstr
, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:"channels_first"
orChannelDimension.FIRST
: image in (num_channels, height, width) format."channels_last"
orChannelDimension.LAST
: image in (height, width, num_channels) format."none"
orChannelDimension.NONE
: image in (height, width) format.
- pad_size (
Dict[str, int]
, optional) — The size{"height": int, "width" int}
to pad the images to. Must be larger than any image size provided for preprocessing. Ifpad_size
is not provided, images will be padded to the largest height and width in the batch.
Preprocess an image or a batch of images so that it can be used by the model.
post_process_object_detection
< source >( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple]] = None nms_threshold: float = 0.7 ) → List[Dict]
Parameters
- outputs (
DetrObjectDetectionOutput
) — Raw outputs of the model. - threshold (
float
, optional, defaults to 0.5) — Score threshold to keep object detection predictions. - target_sizes (
torch.Tensor
orList[Tuple[int, int]]
, optional) — Tensor of shape(batch_size, 2)
or list of tuples (Tuple[int, int]
) containing the target size (height, width) of each image in the batch. If left to None, predictions will not be resized. - nms_threshold (
float
, optional, defaults to 0.7) — NMS threshold.
Returns
List[Dict]
A list of dictionaries, each dictionary containing the scores, labels and boxes for an image in the batch as predicted by the model.
Converts the output of DetaForObjectDetection into final bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
DetaModel
class transformers.DetaModel
< source >( config: DetaConfig )
Parameters
- config (DetaConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
The bare DETA Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without any specific head on top.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( pixel_values: FloatTensor pixel_mask: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.FloatTensor] = None encoder_outputs: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.deprecated.deta.modeling_deta.DetaModelOutput
or tuple(torch.FloatTensor)
Parameters
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — Pixel values. Padding will be ignored by default should you provide it.Pixel values can be obtained using AutoImageProcessor. See
AutoImageProcessor.__call__()
for details. - pixel_mask (
torch.LongTensor
of shape(batch_size, height, width)
, optional) — Mask to avoid performing attention on padding pixel values. Mask values selected in[0, 1]
:- 1 for pixels that are real (i.e. not masked),
- 0 for pixels that are padding (i.e. masked).
- decoder_attention_mask (
torch.FloatTensor
of shape(batch_size, num_queries)
, optional) — Not used by default. Can be used to mask object queries. - encoder_outputs (
tuple(tuple(torch.FloatTensor)
, optional) — Tuple consists of (last_hidden_state
, optional:hidden_states
, optional:attentions
)last_hidden_state
of shape(batch_size, sequence_length, hidden_size)
, optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you can choose to directly pass a flattened representation of an image. - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, num_queries, hidden_size)
, optional) — Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an embedded representation. - output_attentions (
bool
, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail. - output_hidden_states (
bool
, optional) — Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail. - return_dict (
bool
, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
Returns
transformers.models.deprecated.deta.modeling_deta.DetaModelOutput
or tuple(torch.FloatTensor)
A transformers.models.deprecated.deta.modeling_deta.DetaModelOutput
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (DetaConfig) and inputs.
- init_reference_points (
torch.FloatTensor
of shape(batch_size, num_queries, 4)
) — Initial reference points sent through the Transformer decoder. - last_hidden_state (
torch.FloatTensor
of shape(batch_size, num_queries, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the decoder of the model. - intermediate_hidden_states (
torch.FloatTensor
of shape(batch_size, config.decoder_layers, num_queries, hidden_size)
) — Stacked intermediate hidden states (output of each layer of the decoder). - intermediate_reference_points (
torch.FloatTensor
of shape(batch_size, config.decoder_layers, num_queries, 4)
) — Stacked intermediate reference points (reference points of each layer of the decoder). - decoder_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, num_queries, hidden_size)
. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. - decoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, num_queries, num_queries)
. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. - cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_queries, num_heads, 4, 4)
. Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. - encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. - encoder_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. - encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_queries, num_heads, 4, 4)
. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. - enc_outputs_class (
torch.FloatTensor
of shape(batch_size, sequence_length, config.num_labels)
, optional, returned whenconfig.with_box_refine=True
andconfig.two_stage=True
) — Predicted bounding boxes scores where the topconfig.two_stage_num_proposals
scoring bounding boxes are picked as region proposals in the first stage. Output of bounding box binary classification (i.e. foreground and background). - enc_outputs_coord_logits (
torch.FloatTensor
of shape(batch_size, sequence_length, 4)
, optional, returned whenconfig.with_box_refine=True
andconfig.two_stage=True
) — Logits of predicted bounding boxes coordinates in the first stage. - output_proposals (
torch.FloatTensor
of shape(batch_size, sequence_length, 4)
, optional, returned whenconfig.two_stage=True
) — Logits of proposal bounding boxes coordinates in the gen_encoder_output_proposals.
The DetaModel forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import AutoImageProcessor, DetaModel
>>> 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("jozhang97/deta-swin-large-o365")
>>> model = DetaModel.from_pretrained("jozhang97/deta-swin-large-o365", two_stage=False)
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 900, 256]
DetaForObjectDetection
class transformers.DetaForObjectDetection
< source >( config: DetaConfig )
Parameters
- config (DetaConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.
DETA Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks such as COCO detection.
This model inherits from PreTrainedModel. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch torch.nn.Module subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
forward
< source >( pixel_values: FloatTensor pixel_mask: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.FloatTensor] = None encoder_outputs: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[typing.List[dict]] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.deprecated.deta.modeling_deta.DetaObjectDetectionOutput
or tuple(torch.FloatTensor)
Parameters
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — Pixel values. Padding will be ignored by default should you provide it.Pixel values can be obtained using AutoImageProcessor. See
AutoImageProcessor.__call__()
for details. - pixel_mask (
torch.LongTensor
of shape(batch_size, height, width)
, optional) — Mask to avoid performing attention on padding pixel values. Mask values selected in[0, 1]
:- 1 for pixels that are real (i.e. not masked),
- 0 for pixels that are padding (i.e. masked).
- decoder_attention_mask (
torch.FloatTensor
of shape(batch_size, num_queries)
, optional) — Not used by default. Can be used to mask object queries. - encoder_outputs (
tuple(tuple(torch.FloatTensor)
, optional) — Tuple consists of (last_hidden_state
, optional:hidden_states
, optional:attentions
)last_hidden_state
of shape(batch_size, sequence_length, hidden_size)
, optional) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you can choose to directly pass a flattened representation of an image. - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, num_queries, hidden_size)
, optional) — Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an embedded representation. - output_attentions (
bool
, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail. - output_hidden_states (
bool
, optional) — Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail. - return_dict (
bool
, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - labels (
List[Dict]
of len(batch_size,)
, optional) — Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the following 2 keys: ‘class_labels’ and ‘boxes’ (the class labels and bounding boxes of an image in the batch respectively). The class labels themselves should be atorch.LongTensor
of len(number of bounding boxes in the image,)
and the boxes atorch.FloatTensor
of shape(number of bounding boxes in the image, 4)
.
Returns
transformers.models.deprecated.deta.modeling_deta.DetaObjectDetectionOutput
or tuple(torch.FloatTensor)
A transformers.models.deprecated.deta.modeling_deta.DetaObjectDetectionOutput
or a tuple of
torch.FloatTensor
(if return_dict=False
is passed or when config.return_dict=False
) comprising various
elements depending on the configuration (DetaConfig) and inputs.
- loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
are provided)) — Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized scale-invariant IoU loss. - loss_dict (
Dict
, optional) — A dictionary containing the individual losses. Useful for logging. - logits (
torch.FloatTensor
of shape(batch_size, num_queries, num_classes + 1)
) — Classification logits (including no-object) for all queries. - pred_boxes (
torch.FloatTensor
of shape(batch_size, num_queries, 4)
) — Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding). You can use~DetaProcessor.post_process_object_detection
to retrieve the unnormalized bounding boxes. - auxiliary_outputs (
list[Dict]
, optional) — Optional, only returned when auxilary losses are activated (i.e.config.auxiliary_loss
is set toTrue
) and labels are provided. It is a list of dictionaries containing the two above keys (logits
andpred_boxes
) for each decoder layer. - last_hidden_state (
torch.FloatTensor
of shape(batch_size, num_queries, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the decoder of the model. - decoder_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, num_queries, hidden_size)
. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs. - decoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, num_queries, num_queries)
. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads. - cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_queries, num_heads, 4, 4)
. Attentions weights of the decoder’s cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads. - encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — Sequence of hidden-states at the output of the last layer of the encoder of the model. - encoder_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs. - encoder_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, sequence_length, num_heads, 4, 4)
. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the self-attention heads. - intermediate_hidden_states (
torch.FloatTensor
of shape(batch_size, config.decoder_layers, num_queries, hidden_size)
) — Stacked intermediate hidden states (output of each layer of the decoder). - intermediate_reference_points (
torch.FloatTensor
of shape(batch_size, config.decoder_layers, num_queries, 4)
) — Stacked intermediate reference points (reference points of each layer of the decoder). - init_reference_points (
torch.FloatTensor
of shape(batch_size, num_queries, 4)
) — Initial reference points sent through the Transformer decoder. - enc_outputs_class (
torch.FloatTensor
of shape(batch_size, sequence_length, config.num_labels)
, optional, returned whenconfig.with_box_refine=True
andconfig.two_stage=True
) — Predicted bounding boxes scores where the topconfig.two_stage_num_proposals
scoring bounding boxes are picked as region proposals in the first stage. Output of bounding box binary classification (i.e. foreground and background). - enc_outputs_coord_logits (
torch.FloatTensor
of shape(batch_size, sequence_length, 4)
, optional, returned whenconfig.with_box_refine=True
andconfig.two_stage=True
) — Logits of predicted bounding boxes coordinates in the first stage. - output_proposals (
torch.FloatTensor
of shape(batch_size, sequence_length, 4)
, optional, returned whenconfig.two_stage=True
) — Logits of proposal bounding boxes coordinates in the gen_encoder_output_proposals.
The DetaForObjectDetection forward method, overrides the __call__
special method.
Although the recipe for forward pass needs to be defined within this function, one should call the Module
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.
Examples:
>>> from transformers import AutoImageProcessor, DetaForObjectDetection
>>> 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("jozhang97/deta-swin-large")
>>> model = DetaForObjectDetection.from_pretrained("jozhang97/deta-swin-large")
>>> 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.802 at location [9.87, 54.36, 316.93, 473.44]
Detected cat with confidence 0.795 at location [346.62, 24.35, 639.62, 373.2]
Detected remote with confidence 0.725 at location [40.41, 73.36, 175.77, 117.29]
Detected remote with confidence 0.638 at location [333.34, 76.81, 370.22, 187.94]
Detected couch with confidence 0.584 at location [0.03, 0.99, 640.02, 474.93]