Transformers 文件
可變形 DETR
並獲得增強的文件體驗
開始使用
Deformable DETR
概述
Deformable DETR 模型由 Xizhou Zhu、Weijie Su、Lewei Lu、Bin Li、Xiaogang Wang 和 Jifeng Dai 在 Deformable DETR: Deformable Transformers for End-to-End Object Detection 中提出。Deformable DETR 透過利用新的可變形注意力模組,僅關注參考點周圍的一小部分關鍵取樣點,從而緩解了原始 DETR 收斂緩慢和特徵空間解析度有限的問題。
論文摘要如下:
DETR 最近被提出,旨在消除目標檢測中許多手動設計元件的需求,同時表現出良好的效能。然而,由於 Transformer 注意力模組在處理影像特徵圖方面的限制,它存在收斂緩慢和特徵空間解析度有限的問題。為了緩解這些問題,我們提出了 Deformable DETR,其注意力模組只關注參考點周圍的一小部分關鍵取樣點。Deformable DETR 在訓練 epoch 減少 10 倍的情況下,可以比 DETR 獲得更好的效能(尤其是在小目標上)。在 COCO 基準上的大量實驗證明了我們方法的有效性。

使用技巧
資源
Hugging Face 官方和社群(🌎 表示)資源列表,助您開始使用 Deformable DETR。
- 關於 DeformableDetrForObjectDetection 的推理 + 在自定義資料集上微調的演示筆記本可以在這裡找到。
- 使用 Trainer 或 Accelerate 微調 DeformableDetrForObjectDetection 的指令碼可以在這裡找到。
- 另請參閱:目標檢測任務指南。
如果您有興趣在此處提交資源,請隨時開啟 Pull Request,我們將對其進行審查!該資源最好能展示一些新內容,而不是重複現有資源。
DeformableDetrImageProcessor
class transformers.DeformableDetrImageProcessor
< 源 >( format: typing.Union[str, transformers.image_utils.AnnotationFormat] = <AnnotationFormat.COCO_DETECTION: 'coco_detection'> do_resize: bool = True size: typing.Optional[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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_annotations: typing.Optional[bool] = None do_pad: bool = True pad_size: typing.Optional[dict[str, int]] = None **kwargs )
引數
- format (
str
, optional, 預設為"coco_detection"
) — 註釋的資料格式。可以是 "coco_detection" 或 "coco_panoptic" 之一。 - do_resize (
bool
, optional, 預設為True
) — 控制是否將影像的(高,寬)維度調整為指定的size
。可以透過preprocess
方法中的do_resize
引數覆蓋。 - size (
dict[str, int]
可選, 預設為{"shortest_edge" -- 800, "longest_edge": 1333}
): 調整大小後圖像的(height, width)
維度大小。可以透過preprocess
方法中的size
引數覆蓋。可用選項包括:{"height": int, "width": int}
: 影像將調整到精確的(height, width)
大小。不保留縱橫比。{"shortest_edge": int, "longest_edge": int}
: 影像將調整到最大大小,同時保留縱橫比,並將最短邊小於或等於shortest_edge
,最長邊小於或等於longest_edge
。{"max_height": int, "max_width": int}
: 影像將調整到最大大小,同時保留縱橫比,並將高度小於或等於max_height
,寬度小於或等於max_width
。
- resample (
PILImageResampling
, 可選, 預設為PILImageResampling.BILINEAR
) — 如果調整影像大小,要使用的重取樣過濾器。 - do_rescale (
bool
, 可選, 預設為True
) — 控制是否按指定比例rescale_factor
重新縮放影像。可以透過preprocess
方法中的do_rescale
引數覆蓋。 - rescale_factor (
int
或float
, 可選, 預設為1/255
) — 如果重新縮放影像,要使用的比例因子。可以透過preprocess
方法中的rescale_factor
引數覆蓋。 - do_normalize — 控制是否對影像進行歸一化。可以透過
preprocess
方法中的do_normalize
引數覆蓋。 - image_mean (
float
或list[float]
, 可選, 預設為IMAGENET_DEFAULT_MEAN
) — 影像歸一化時使用的平均值。可以是單個值或值列表,每個通道一個值。可以透過preprocess
方法中的image_mean
引數覆蓋。 - image_std (
float
或list[float]
, 可選, 預設為IMAGENET_DEFAULT_STD
) — 影像歸一化時使用的標準差值。可以是單個值或值列表,每個通道一個值。可以透過preprocess
方法中的image_std
引數覆蓋。 - do_convert_annotations (
bool
, 可選, 預設為True
) — 控制是否將註釋轉換為 DETR 模型期望的格式。將邊界框轉換為(center_x, center_y, width, height)
格式和[0, 1]
範圍。可以透過preprocess
方法中的do_convert_annotations
引數覆蓋。 - do_pad (
bool
, 可選, 預設為True
) — 控制是否填充影像。如果為True
,將用零填充影像的底部和右側。如果提供了pad_size
,影像將填充到指定的尺寸。否則,影像將填充到批次中的最大高度和寬度。 - pad_size (
dict[str, int]
, 可選) — 填充影像的尺寸{"height": int, "width" int}
。必須大於任何為預處理提供的影像尺寸。如果未提供pad_size
,影像將填充到批次中的最大高度和寬度。
構造一個 Deformable DETR 影像處理器。
preprocess
< 源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: typing.Union[dict[str, typing.Union[int, str, list[dict]]], list[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None return_segmentation_masks: typing.Optional[bool] = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Union[int, float, NoneType] = None do_normalize: typing.Optional[bool] = None do_convert_annotations: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_pad: typing.Optional[bool] = None format: typing.Union[str, transformers.image_utils.AnnotationFormat, NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None pad_size: typing.Optional[dict[str, int]] = None **kwargs )
引數
- images (
ImageInput
) — 要預處理的影像或影像批次。期望單個影像或批次影像的畫素值範圍為 0 到 255。如果傳入的影像畫素值在 0 到 1 之間,請將do_rescale=False
。 - annotations (
AnnotationType
或list[AnnotationType]
, 可選) — 與影像或影像批次關聯的註釋列表。如果註釋用於目標檢測,則註釋應是一個字典,包含以下鍵:- “image_id” (
int
): 影像 ID。 - “annotations” (
list[Dict]
): 影像的註釋列表。每個註釋應是一個字典。影像可以沒有註釋,在這種情況下,列表應為空。如果註釋用於分割,則註釋應是一個字典,包含以下鍵: - “image_id” (
int
): 影像 ID。 - “segments_info” (
list[Dict]
): 影像的分割列表。每個分割應是一個字典。影像可以沒有分割,在這種情況下,列表應為空。 - “file_name” (
str
): 影像的檔名。
- “image_id” (
- return_segmentation_masks (
bool
, 可選, 預設為 self.return_segmentation_masks) — 是否返回分割掩碼。 - masks_path (
str
或pathlib.Path
, 可選) — 包含分割掩碼的目錄路徑。 - do_resize (
bool
, 可選, 預設為 self.do_resize) — 是否調整影像大小。 - size (
dict[str, int]
, 可選, 預設為 self.size) — 調整大小後圖像的(height, width)
維度大小。可用選項包括:{"height": int, "width": int}
: 影像將調整到精確的(height, width)
大小。不保留縱橫比。{"shortest_edge": int, "longest_edge": int}
: 影像將調整到最大大小,同時保留縱橫比,並將最短邊小於或等於shortest_edge
,最長邊小於或等於longest_edge
。{"max_height": int, "max_width": int}
: 影像將調整到最大大小,同時保留縱橫比,並將高度小於或等於max_height
,寬度小於或等於max_width
。
- resample (
PILImageResampling
, 可選, 預設為 self.resample) — 調整影像大小時使用的重取樣過濾器。 - do_rescale (
bool
, 可選, 預設為 self.do_rescale) — 是否重新縮放影像。 - rescale_factor (
float
, 可選, 預設為 self.rescale_factor) — 重新縮放影像時使用的比例因子。 - do_normalize (
bool
, 可選, 預設為 self.do_normalize) — 是否對影像進行歸一化。 - do_convert_annotations (
bool
, 可選, 預設為 self.do_convert_annotations) — 是否將註釋轉換為模型期望的格式。將邊界框從(top_left_x, top_left_y, width, height)
格式轉換為(center_x, center_y, width, height)
格式並轉換為相對座標。 - image_mean (
float
或list[float]
, 可選, 預設為 self.image_mean) — 影像歸一化時使用的平均值。 - image_std (
float
或list[float]
, 可選, 預設為 self.image_std) — 影像歸一化時使用的標準差。 - do_pad (
bool
, 可選, 預設為 self.do_pad) — 是否填充影像。如果為True
,將用零填充影像的底部和右側。如果提供了pad_size
,影像將填充到指定的尺寸。否則,影像將填充到批次中的最大高度和寬度。 - format (
str
或AnnotationFormat
, 可選, 預設為 self.format) — 註釋的格式。 - return_tensors (
str
或TensorType
, 可選, 預設為 self.return_tensors) — 要返回的張量型別。如果為None
,將返回影像列表。 - data_format (
ChannelDimension
或str
, 可選, 預設為ChannelDimension.FIRST
) — 輸出影像的通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 影像格式為 (height, width, num_channels)。- 未設定: 使用輸入影像的通道維度格式。
- input_data_format (
ChannelDimension
或str
, 可選) — 輸入影像的通道維度格式。如果未設定,則從輸入影像推斷通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 影像格式為 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 影像格式為 (height, width)。
- pad_size (
dict[str, int]
, 可選) — 填充影像的尺寸{"height": int, "width" int}
。必須大於任何為預處理提供的影像尺寸。如果未提供pad_size
,影像將填充到批次中的最大高度和寬度。
預處理影像或影像批次,以便模型可以使用。
post_process_object_detection
< 源 >( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple]] = None top_k: int = 100 ) → list[Dict]
引數
- outputs (
DetrObjectDetectionOutput
) — 模型的原始輸出。 - threshold (
float
, 可選) — 保留目標檢測預測的分數閾值。 - target_sizes (
torch.Tensor
或list[tuple[int, int]]
, 可選) — 形狀為(batch_size, 2)
的張量,或包含批次中每張影像的目標尺寸(高,寬)的元組列表(tuple[int, int]
)。如果留空,預測將不會被調整大小。 - top_k (
int
, 可選, 預設為 100) — 在閾值過濾之前,只保留前 k 個邊界框。
返回
list[Dict]
一個字典列表,每個字典包含模型預測的批處理中每張影像的分數、標籤和框。
將 DeformableDetrForObjectDetection 的原始輸出轉換為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最終邊界框。僅支援 PyTorch。
DeformableDetrImageProcessorFast
class transformers.DeformableDetrImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_deformable_detr_fast.DeformableDetrFastImageProcessorKwargs] )
構建一個快速 Deformable Detr 影像處理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: typing.Union[dict[str, typing.Union[int, str, list[dict]]], list[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None **kwargs: typing_extensions.Unpack[transformers.models.deformable_detr.image_processing_deformable_detr_fast.DeformableDetrFastImageProcessorKwargs] ) → <class 'transformers.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]
, 可選) — 與影像或影像批次關聯的標註列表。如果標註用於目標檢測,標註應為包含以下鍵的字典:- “image_id” (
int
):影像 ID。 - “annotations” (
list[Dict]
):影像的標註列表。每個標註應為一個字典。影像可以沒有標註,在這種情況下列表應為空。如果標註用於分割,標註應為包含以下鍵的字典: - “image_id” (
int
):影像 ID。 - “segments_info” (
list[Dict]
):影像的片段列表。每個片段應為一個字典。影像可以沒有片段,在這種情況下列表應為空。 - “file_name” (
str
):影像的檔名。
- “image_id” (
- masks_path (
str
或pathlib.Path
, 可選) — 包含分割掩碼的目錄路徑。 - do_resize (
bool
, 可選) — 是否調整影像大小。 - size (
dict[str, int]
, 可選) — 描述模型的最大輸入維度。 - default_to_square (
bool
, 可選) — 如果尺寸為整數,是否在調整大小後預設使用方形影像。 - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — 如果調整影像大小,要使用的重取樣過濾器。可以是列舉PILImageResampling
之一。僅在do_resize
設定為True
時有效。 - do_center_crop (
bool
, 可選) — 是否對影像進行中心裁剪。 - crop_size (
dict[str, int]
, 可選) — 應用center_crop
後輸出影像的尺寸。 - do_rescale (
bool
, 可選) — 是否重新縮放影像。 - rescale_factor (
Union[int, float, NoneType]
) — 如果do_rescale
設定為True
,則按此重新縮放因子調整影像大小。 - do_normalize (
bool
, 可選) — 是否歸一化影像。 - image_mean (
Union[float, list[float], NoneType]
) — 用於歸一化的影像均值。僅在do_normalize
設定為True
時有效。 - image_std (
Union[float, list[float], NoneType]
) — 用於歸一化的影像標準差。僅在do_normalize
設定為True
時有效。 - do_convert_rgb (
bool
, 可選) — 是否將影像轉換為 RGB。 - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — 如果設定為 `pt`,則返回堆疊張量,否則返回張量列表。 - data_format (
~image_utils.ChannelDimension
, 可選) — 僅支援ChannelDimension.FIRST
。為了與慢速處理器相容而新增。 - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]
) — 輸入影像的通道維度格式。如果未設定,則從輸入影像推斷通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像為 (num_channels, height, width) 格式。"channels_last"
或ChannelDimension.LAST
:影像為 (height, width, num_channels) 格式。"none"
或ChannelDimension.NONE
:影像為 (height, width) 格式。
- device (
torch.device
, 可選) — 處理影像的裝置。如果未設定,則從輸入影像推斷裝置。 - disable_grouping (
bool
, 可選) — 是否停用按大小對影像進行分組以單獨而非批處理它們。如果為 None,則如果影像在 CPU 上,則設定為 True,否則設定為 False。此選擇基於經驗觀察,詳情請參閱:https://github.com/huggingface/transformers/pull/38157 - format (
str
, 可選, 預設為AnnotationFormat.COCO_DETECTION
) — 標註的資料格式。可以是 "coco_detection" 或 "coco_panoptic" 之一。 - do_convert_annotations (
bool
, 可選, 預設為True
) — 控制是否將標註轉換為 DEFORMABLE_DETR 模型期望的格式。將邊界框轉換為(center_x, center_y, width, height)
格式,範圍為[0, 1]
。可以透過preprocess
方法中的do_convert_annotations
引數覆蓋。 - do_pad (
bool
, 可選, 預設為True
) — 控制是否對影像進行填充。可以透過preprocess
方法中的do_pad
引數覆蓋。如果為True
,影像的底部和右側將用零填充。如果提供了pad_size
,影像將填充到指定維度。否則,影像將填充到批次中的最大高度和寬度。 - pad_size (
dict[str, int]
, 可選) — 影像填充到的尺寸{"height": int, "width" int}
。必須大於任何用於預處理的影像尺寸。如果未提供pad_size
,影像將填充到批次中的最大高度和寬度。 - return_segmentation_masks (
bool
, 可選, 預設為False
) — 是否返回分割掩碼。
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/陣列/張量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可選) — 您可以在此處提供一個`tensor_type`,以便在初始化時將整數列表轉換為PyTorch/TensorFlow/Numpy張量。
post_process_object_detection
< source >( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple]] = None top_k: int = 100 ) → list[Dict]
引數
- outputs (
DetrObjectDetectionOutput
) — 模型的原始輸出。 - threshold (
float
, 可選) — 保留目標檢測預測的得分閾值。 - target_sizes (
torch.Tensor
或list[tuple[int, int]]
, 可選) — 形狀為(batch_size, 2)
的張量,或包含批次中每張影像的目標尺寸(高,寬)的元組列表(tuple[int, int]
)。如果留空,預測將不會被調整大小。 - top_k (
int
, 可選, 預設為 100) — 在閾值過濾之前,只保留前 k 個邊界框。
返回
list[Dict]
一個字典列表,每個字典包含模型預測的批處理中每張影像的分數、標籤和框。
將 DeformableDetrForObjectDetection 的原始輸出轉換為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最終邊界框。僅支援 PyTorch。
DeformableDetrFeatureExtractor
預處理單張或批次影像。
post_process_object_detection
< source >( outputs threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple]] = None top_k: int = 100 ) → list[Dict]
引數
- outputs (
DetrObjectDetectionOutput
) — 模型的原始輸出。 - threshold (
float
, 可選) — 保留目標檢測預測的得分閾值。 - target_sizes (
torch.Tensor
或list[tuple[int, int]]
, 可選) — 形狀為(batch_size, 2)
的張量,或包含批次中每張影像的目標尺寸(高,寬)的元組列表(tuple[int, int]
)。如果留空,預測將不會被調整大小。 - top_k (
int
, 可選, 預設為 100) — 在閾值過濾之前,只保留前 k 個邊界框。
返回
list[Dict]
一個字典列表,每個字典包含模型預測的批處理中每張影像的分數、標籤和框。
將 DeformableDetrForObjectDetection 的原始輸出轉換為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最終邊界框。僅支援 PyTorch。
DeformableDetrConfig
class transformers.DeformableDetrConfig
< source >( use_timm_backbone = True backbone_config = None num_channels = 3 num_queries = 300 max_position_embeddings = 1024 encoder_layers = 6 encoder_ffn_dim = 1024 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' backbone = 'resnet50' use_pretrained_backbone = True backbone_kwargs = None dilation = False num_feature_levels = 4 encoder_n_points = 4 decoder_n_points = 4 two_stage = False two_stage_num_proposals = 300 with_box_refine = False 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 = False **kwargs )
引數
- use_timm_backbone (
bool
, 可選, 預設為True
) — 是否使用timm
庫作為骨幹網路。如果設定為False
,將使用 AutoBackbone API。 - backbone_config (
PretrainedConfig
或dict
, 可選) — 骨幹模型的配置。僅在use_timm_backbone
設定為False
時使用,預設為ResNetConfig()
。 - num_channels (
int
, 可選, 預設為 3) — 輸入通道的數量。 - num_queries (
int
, 可選, 預設為 300) — 物件查詢的數量,即檢測槽。這是 DeformableDetrModel 在單張影像中可以檢測到的最大物件數量。如果two_stage
設定為True
,則使用two_stage_num_proposals
代替。 - d_model (
int
, 可選, 預設為 256) — 層的維度。 - encoder_layers (
int
, 可選, 預設為 6) — 編碼器層的數量。 - decoder_layers (
int
, 可選, 預設為 6) — 解碼器層的數量。 - encoder_attention_heads (
int
, 可選, 預設為 8) — Transformer 編碼器中每個注意力層的注意力頭數量。 - decoder_attention_heads (
int
, 可選, 預設為 8) — Transformer 解碼器中每個注意力層的注意力頭數量。 - decoder_ffn_dim (
int
, 可選, 預設為 1024) — 解碼器中“中間層”(通常稱為前饋層)的維度。 - encoder_ffn_dim (
int
, 可選, 預設為 1024) — 解碼器中“中間層”(通常稱為前饋層)的維度。 - activation_function (
str
或function
, 可選, 預設為"relu"
) — 編碼器和池化器中的非線性啟用函式(函式或字串)。如果是字串,支援"gelu"
,"relu"
,"silu"
和"gelu_new"
。 - dropout (
float
, 可選, 預設為 0.1) — 嵌入層、編碼器和池化器中所有全連線層的 dropout 機率。 - attention_dropout (
float
, 可選, 預設為 0.0) — 注意力機率的 dropout 比率。 - activation_dropout (
float
, 可選, 預設為 0.0) — 全連線層內部啟用的 dropout 比率。 - init_std (
float
, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的截斷正態初始化器的標準差。 - init_xavier_std (
float
, 可選, 預設為 1) — HM Attention 模組中用於 Xavier 初始化增益的比例因子。 - encoder_layerdrop (
float
, 可選, 預設為 0.0) — 編碼器的 LayerDrop 機率。有關更多詳細資訊,請參閱 [LayerDrop 論文](參見 https://huggingface.co/papers/1909.11556)。 - auxiliary_loss (
bool
, 可選, 預設為False
) — 是否使用輔助解碼損失(每個解碼器層的損失)。 - position_embedding_type (
str
, 可選, 預設為"sine"
) — 在影像特徵之上使用的位置嵌入型別。可選擇"sine"
或"learned"
。 - backbone (
str
, 可選, 預設為"resnet50"
) — 當backbone_config
為None
時使用的骨幹網路名稱。如果use_pretrained_backbone
為True
,這將從 timm 或 transformers 庫載入相應的預訓練權重。如果use_pretrained_backbone
為False
,這將載入骨幹網路的配置並使用該配置初始化骨幹網路,權重隨機。 - use_pretrained_backbone (
bool
, 可選, 預設為True
) — 是否使用骨幹網路的預訓練權重。 - backbone_kwargs (
dict
, 可選) — 從檢查點載入時傳遞給 AutoBackbone 的關鍵字引數,例如{'out_indices': (0, 1, 2, 3)}
。如果設定了backbone_config
,則不能指定。 - dilation (
bool
, 可選, 預設為False
) — 是否在最後一個卷積塊(DC5)中用膨脹代替步幅。僅當use_timm_backbone
=True
時支援。 - class_cost (
float
, 可選, 預設為 1) — 匈牙利匹配成本中分類錯誤的相對權重。 - bbox_cost (
float
, 可選, 預設為 5) — 匈牙利匹配成本中邊界框座標 L1 誤差的相對權重。 - giou_cost (
float
, 可選, 預設為 2) — 匈牙利匹配成本中邊界框廣義 IoU 損失的相對權重。 - mask_loss_coefficient (
float
, 可選, 預設為 1) — 全景分割損失中 Focal 損失的相對權重。 - dice_loss_coefficient (
float
, 可選, 預設為 1) — 全景分割損失中 DICE/F-1 損失的相對權重。 - bbox_loss_coefficient (
float
, 可選, 預設為 5) — 目標檢測損失中 L1 邊界框損失的相對權重。 - giou_loss_coefficient (
float
, 可選, 預設為 2) — 目標檢測損失中廣義 IoU 損失的相對權重。 - eos_coefficient (
float
, 可選, 預設為 0.1) — 目標檢測損失中“無目標”類別的相對分類權重。 - num_feature_levels (
int
, 可選, 預設為 4) — 輸入特徵層的數量。 - encoder_n_points (
int
, 可選, 預設為 4) — 編碼器中每個注意力頭在每個特徵層中取樣的鍵點數量。 - decoder_n_points (
int
, 可選, 預設為 4) — 解碼器中每個注意力頭在每個特徵層中取樣的鍵點數量。 - two_stage (
bool
, 可選, 預設為False
) — 是否應用兩階段可變形 DETR,其中區域提案也由可變形 DETR 的變體生成,然後進一步饋送到解碼器進行迭代邊界框細化。 - two_stage_num_proposals (
int
, 可選, 預設為 300) — 如果two_stage
設定為True
,則生成的區域提案數量。 - with_box_refine (
bool
, 可選, 預設為False
) — 是否應用迭代邊界框細化,其中每個解碼器層根據前一層預測的邊界框進行細化。 - focal_alpha (
float
, 可選, 預設為 0.25) — Focal 損失中的 Alpha 引數。 - disable_custom_kernels (
bool
, 可選, 預設為False
) — 停用自定義 CUDA 和 CPU 核心的使用。此選項對於 ONNX 匯出是必需的,因為 PyTorch ONNX 匯出不支援自定義核心。
這是配置類,用於儲存 DeformableDetrModel 的配置。它用於根據指定的引數例項化 Deformable DETR 模型,定義模型架構。使用預設值例項化配置將生成與 Deformable DETR SenseTime/deformable-detr 架構類似的配置。
配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。
示例
>>> from transformers import DeformableDetrConfig, DeformableDetrModel
>>> # Initializing a Deformable DETR SenseTime/deformable-detr style configuration
>>> configuration = DeformableDetrConfig()
>>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
>>> model = DeformableDetrModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
DeformableDetrModel
class transformers.DeformableDetrModel
< 源 >( config: DeformableDetrConfig )
引數
- config (DeformableDetrConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法載入模型權重。
裸 Deformable DETR 模型(由骨幹網路和編碼器-解碼器 Transformer 組成),輸出原始隱藏狀態,不帶任何特定頭部。
此模型繼承自 PreTrainedModel。有關庫為所有模型實現的通用方法(如下載或儲存、調整輸入嵌入大小、修剪頭部等),請檢視超類文件。
此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,有關通用用法和行為的所有事項,請參閱 PyTorch 文件。
forward
< 源 >( 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.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutput
或 tuple(torch.FloatTensor)
引數
- pixel_values (形狀為
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
) — 對應於輸入影像的張量。畫素值可以使用{image_processor_class}
獲得。有關詳細資訊,請參見{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
處理影像)。 - pixel_mask (形狀為
(batch_size, height, width)
的torch.LongTensor
, 可選) — 避免對填充畫素值執行注意力的遮罩。遮罩值選擇範圍[0, 1]
:- 1 表示真實畫素(即未遮罩),
- 0 表示填充畫素(即已遮罩)。
- decoder_attention_mask (形狀為
(batch_size, num_queries)
的torch.FloatTensor
, 可選) — 預設情況下不使用。可用於遮罩物件查詢。 - encoder_outputs (
torch.FloatTensor
, 可選) — 元組由 (last_hidden_state
, 可選:hidden_states
, 可選:attentions
) 組成,last_hidden_state
的形狀為(batch_size, sequence_length, hidden_size)
,是編碼器最後一層輸出的隱藏狀態序列。用於解碼器的交叉注意力。 - inputs_embeds (形狀為
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
, 可選) — 另外,除了傳遞展平的特徵圖(骨幹網路 + 投影層的輸出)外,您還可以選擇直接傳遞影像的展平表示。 - decoder_inputs_embeds (形狀為
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
, 可選) — 另外,除了用零張量初始化查詢外,您還可以選擇直接傳遞嵌入表示。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參見返回張量下的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參見返回張量下的hidden_states
。 - return_dict (
bool
, 可選) — 是否返回 ModelOutput 而不是普通元組。
返回
transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutput
或 tuple(torch.FloatTensor)
一個 transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrModelOutput
或一個 torch.FloatTensor
元組(如果傳遞了 return_dict=False
或當 config.return_dict=False
時),包含根據配置 (DeformableDetrConfig) 和輸入的不同元素。
-
init_reference_points (
torch.FloatTensor
, 形狀為(batch_size, num_queries, 4)
) — 透過 Transformer 解碼器傳送的初始參考點。 -
last_hidden_state (
torch.FloatTensor
, 形狀為(batch_size, num_queries, hidden_size)
) — 模型解碼器最後一層輸出的隱藏狀態序列。 -
intermediate_hidden_states (
torch.FloatTensor
, 形狀為(batch_size, config.decoder_layers, num_queries, hidden_size)
) — 堆疊的中間隱藏狀態(解碼器每層的輸出)。 -
intermediate_reference_points (
torch.FloatTensor
, 形狀為(batch_size, config.decoder_layers, num_queries, 4)
) — 堆疊的中間參考點(解碼器每層的參考點)。 -
decoder_hidden_states (
tuple[torch.FloatTensor]
, 可選, 當傳遞output_hidden_states=True
或當config.output_hidden_states=True
時返回) —torch.FloatTensor
的元組(一個用於嵌入層的輸出,如果模型有嵌入層,+ 一個用於每個層的輸出),形狀為(batch_size, 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
, 可選, 預設為None
) — 模型編碼器最後一層輸出的隱藏狀態序列。 -
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 之後,用於計算自注意力頭中的加權平均。
-
enc_outputs_class (形狀為
(batch_size, sequence_length, config.num_labels)
的torch.FloatTensor
, 可選, 當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。
DeformableDetrModel 的 forward 方法,覆蓋了 __call__
特殊方法。
儘管 forward pass 的配方需要在此函式中定義,但之後應該呼叫 Module
例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則默默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, DeformableDetrModel
>>> 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("SenseTime/deformable-detr")
>>> model = DeformableDetrModel.from_pretrained("SenseTime/deformable-detr")
>>> 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]
DeformableDetrForObjectDetection
class transformers.DeformableDetrForObjectDetection
< source >( config: DeformableDetrConfig )
引數
- config (DeformableDetrConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化並不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
Deformable DETR 模型(由骨幹網路和編碼器-解碼器 Transformer 組成),頂部帶有目標檢測頭,用於 COCO 檢測等任務。
此模型繼承自 PreTrainedModel。有關庫為所有模型實現的通用方法(如下載或儲存、調整輸入嵌入大小、修剪頭部等),請檢視超類文件。
此模型也是 PyTorch torch.nn.Module 子類。將其作為常規 PyTorch 模組使用,有關通用用法和行為的所有事項,請參閱 PyTorch 文件。
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[list[dict]] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutput
或 tuple(torch.FloatTensor)
引數
- pixel_values (形狀為
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
) — 對應於輸入影像的張量。畫素值可以使用{image_processor_class}
獲取。有關詳細資訊,請參見{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
處理影像)。 - pixel_mask (形狀為
(batch_size, height, width)
的torch.LongTensor
,可選) — 用於避免對填充畫素值執行注意力操作的掩碼。掩碼值選擇在[0, 1]
之間:- 1 表示真實畫素(即未被掩蓋),
- 0 表示填充畫素(即被掩蓋)。
- decoder_attention_mask (形狀為
(batch_size, num_queries)
的torch.FloatTensor
,可選) — 預設情況下不使用。可用於掩蓋物件查詢。 - encoder_outputs (
torch.FloatTensor
,可選) — 元組,包含(last_hidden_state
,可選:hidden_states
,可選:attentions
)last_hidden_state
的形狀為(batch_size, sequence_length, hidden_size)
,可選)是編碼器最後一層輸出的隱藏狀態序列。在解碼器的交叉注意力中用到。 - inputs_embeds (形狀為
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
,可選) — 可選地,您可以選擇直接傳遞影像的平坦表示,而不是傳遞平坦的特徵圖(骨幹網路 + 投影層 的輸出)。 - decoder_inputs_embeds (形狀為
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
,可選) — 可選地,您可以選擇直接傳遞嵌入表示,而不是用零張量初始化查詢。 - labels (長度為
(batch_size,)
的list[Dict]
,可選) — 用於計算二分匹配損失的標籤。字典列表,每個字典至少包含以下兩個鍵:“class_labels”和“boxes”(分別表示批次中影像的類別標籤和邊界框)。類別標籤本身應為長度為(影像中邊界框的數量,)
的torch.LongTensor
,邊界框應為形狀為(影像中邊界框的數量, 4)
的torch.FloatTensor
。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。更多詳細資訊請參見返回張量中的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。更多詳細資訊請參見返回張量中的hidden_states
。 - return_dict (
bool
, 可選) — 是否返回 ModelOutput 而不是普通元組。
返回
transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutput
或 tuple(torch.FloatTensor)
一個 transformers.models.deformable_detr.modeling_deformable_detr.DeformableDetrObjectDetectionOutput
或 torch.FloatTensor
元組(如果傳遞 return_dict=False
或 config.return_dict=False
),包含根據配置 (DeformableDetrConfig) 和輸入的不同元素。
-
loss (形狀為
(1,)
的torch.FloatTensor
,可選,當提供labels
時返回) — 總損失,是類別預測的負對數似然(交叉熵)和邊界框損失的線性組合。後者定義為 L1 損失和廣義尺度不變 IoU 損失的線性組合。 -
loss_dict (
Dict
, 可選) — 包含各個損失的字典。用於日誌記錄。 -
logits (形狀為
(batch_size, num_queries, num_classes + 1)
的torch.FloatTensor
) — 所有查詢的分類 logits(包括無物件)。 -
pred_boxes (形狀為
(batch_size, num_queries, 4)
的torch.FloatTensor
) — 所有查詢的歸一化框座標,表示為 (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 (
torch.FloatTensor
, 形狀為(batch_size, num_queries, 4)
) — 透過 Transformer 解碼器傳送的初始參考點。 -
last_hidden_state (形狀為
(batch_size, num_queries, hidden_size)
的torch.FloatTensor
,可選) — 模型解碼器最後一層輸出的隱藏狀態序列。 -
intermediate_hidden_states (
torch.FloatTensor
, 形狀為(batch_size, config.decoder_layers, num_queries, hidden_size)
) — 堆疊的中間隱藏狀態(解碼器每層的輸出)。 -
intermediate_reference_points (
torch.FloatTensor
, 形狀為(batch_size, config.decoder_layers, num_queries, 4)
) — 堆疊的中間參考點(解碼器每層的參考點)。 -
decoder_hidden_states (
tuple[torch.FloatTensor]
, 可選, 當傳遞output_hidden_states=True
或當config.output_hidden_states=True
時返回) —torch.FloatTensor
的元組(一個用於嵌入層的輸出,如果模型有嵌入層,+ 一個用於每個層的輸出),形狀為(batch_size, 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
, 可選, 預設為None
) — 模型編碼器最後一層輸出的隱藏狀態序列。 -
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 之後,用於計算自注意力頭中的加權平均。
-
enc_outputs_class (形狀為
(batch_size, sequence_length, config.num_labels)
的torch.FloatTensor
, 可選, 當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。
DeformableDetrForObjectDetection 的 forward 方法,覆蓋了 __call__
特殊方法。
儘管 forward pass 的配方需要在此函式中定義,但之後應該呼叫 Module
例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則默默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, DeformableDetrForObjectDetection
>>> 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("SenseTime/deformable-detr")
>>> model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr")
>>> 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]