Transformers 文件

YOLOS

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

YOLOS

PyTorch FlashAttention SDPA

概述

YOLOS 模型由 Yuxin Fang、Bencheng Liao、Xinggang Wang、Jiemin Fang、Jiyang Qi、Rui Wu、Jianwei Niu 和 Wenyu Liu 在論文 You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection 中提出。受 DETR 啟發,YOLOS 提出僅利用普通的 Vision Transformer (ViT) 進行目標檢測。事實證明,一個基礎大小的僅編碼器 Transformer 也能在 COCO 資料集上達到 42 AP,與 DETR 以及更復雜的框架(如 Faster R-CNN)效能相當。

論文摘要如下:

摘要:Transformer 能否從純粹的序列到序列的角度,在對二維空間結構瞭解最少的情況下,執行二維目標和區域級識別?為了回答這個問題,我們提出了 YOLOS (You Only Look at One Sequence),這是一系列基於原始 Vision Transformer 的目標檢測模型,並對目標任務的區域先驗和歸納偏置進行了最少的修改。我們發現,僅在中等大小的 ImageNet-1k 資料集上預訓練的 YOLOS 已經可以在具有挑戰性的 COCO 目標檢測基準上取得相當有競爭力的效能,例如,直接從 BERT-Base 架構改編的 YOLOS-Base 可以在 COCO 驗證集上獲得 42.0 的 box AP。我們還透過 YOLOS 討論了當前視覺 Transformer 預訓練方案和模型縮放策略的影響和侷限性。

drawing YOLOS 架構。摘自原始論文

該模型由 nielsr 貢獻。原始程式碼可在此處找到。

使用縮放點積注意力 (SDPA)

PyTorch 包含一個原生的縮放點積注意力(SDPA)運算元,作為 torch.nn.functional 的一部分。該函式包含多種實現,可根據輸入和使用的硬體進行應用。更多資訊請參閱官方文件GPU 推理頁面。

當實現可用時,SDPA 預設用於 `torch>=2.1.1`,但你也可以在 `from_pretrained()` 中設定 `attn_implementation="sdpa"` 來明確請求使用 SDPA。

from transformers import AutoModelForObjectDetection
model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-base", attn_implementation="sdpa", torch_dtype=torch.float16)
...

為了獲得最佳加速效果,我們建議以半精度(例如 `torch.float16` 或 `torch.bfloat16`)載入模型。

在一個本地基準測試(A100-40GB,PyTorch 2.3.0,作業系統 Ubuntu 22.04)中,使用 float32hustvl/yolos-base 模型,我們在推理過程中觀察到以下加速效果。

批次大小 平均推理時間(毫秒),eager 模式 平均推理時間(毫秒),sdpa 模型 加速,Sdpa / Eager (x)
1 106 76 1.39
2 154 90 1.71
4 222 116 1.91
8 368 168 2.19

資源

Hugging Face 官方和社群(由 🌎 標識)提供的資源列表,幫助您開始使用 YOLOS。

物體檢測

如果您有興趣在此處提交資源,請隨時開啟 Pull Request,我們將對其進行審查!該資源最好能展示一些新內容,而不是重複現有資源。

使用 YolosImageProcessor 為模型準備影像(以及可選的目標)。與 DETR 不同,YOLOS 不需要建立 pixel_mask

YolosConfig

class transformers.YolosConfig

< >

( hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-12 image_size = [512, 864] patch_size = 16 num_channels = 3 qkv_bias = True num_detection_tokens = 100 use_mid_position_embeddings = True auxiliary_loss = False class_cost = 1 bbox_cost = 5 giou_cost = 2 bbox_loss_coefficient = 5 giou_loss_coefficient = 2 eos_coefficient = 0.1 **kwargs )

引數

  • hidden_size (int, 可選, 預設為 768) — 編碼器層和池化層的維度。
  • num_hidden_layers (int, 可選, 預設為 12) — Transformer 編碼器中的隱藏層數量。
  • num_attention_heads (int, 可選, 預設為 12) — Transformer 編碼器中每個注意力層的注意力頭數量。
  • intermediate_size (int, 可選, 預設為 3072) — Transformer 編碼器中“中間層”(即前饋層)的維度。
  • hidden_act (strfunction, 可選, 預設為 "gelu") — 編碼器和池化層中的非線性啟用函式(函式或字串)。如果為字串,支援 "gelu""relu""selu""gelu_new"
  • hidden_dropout_prob (float, 可選, 預設為 0.0) — 嵌入層、編碼器和池化層中所有全連線層的丟棄機率。
  • attention_probs_dropout_prob (float, 可選, 預設為 0.0) — 注意力機率的丟棄率。
  • initializer_range (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的 truncated_normal_initializer 的標準差。
  • layer_norm_eps (float, 可選, 預設為 1e-12) — 層歸一化層使用的 epsilon 值。
  • image_size (list[int], 可選, 預設為 [512, 864]) — 每張影像的大小(解析度)。
  • patch_size (int, 可選, 預設為 16) — 每個影像塊的大小(解析度)。
  • num_channels (int, 可選, 預設為 3) — 輸入通道的數量。
  • qkv_bias (bool, 可選, 預設為 True) — 是否為查詢、鍵和值新增偏置。
  • num_detection_tokens (int, 可選, 預設為 100) — 檢測令牌的數量。
  • use_mid_position_embeddings (bool, 可選, 預設為 True) — 是否使用中間層位置編碼。
  • auxiliary_loss (bool, 可選, 預設為 False) — 是否使用輔助解碼損失(每個解碼器層的損失)。
  • class_cost (float, 可選, 預設為 1) — 匈牙利匹配代價中分類錯誤的相對權重。
  • bbox_cost (float, 可選, 預設為 5) — 匈牙利匹配代價中邊界框座標 L1 錯誤的相對權重。
  • giou_cost (float, 可選, 預設為 2) — 匈牙利匹配代價中邊界框廣義 IoU 損失的相對權重。
  • bbox_loss_coefficient (float, 可選, 預設為 5) — 目標檢測損失中 L1 邊界框損失的相對權重。
  • giou_loss_coefficient (float, 可選, 預設為 2) — 目標檢測損失中廣義 IoU 損失的相對權重。
  • eos_coefficient (float, 可選, 預設為 0.1) — 目標檢測損失中“無目標”類別的相對分類權重。

這是用於儲存 YolosModel 配置的配置類。它用於根據指定的引數例項化一個 YOLOS 模型,定義模型架構。使用預設值例項化配置將產生與 YOLOS hustvl/yolos-base 架構類似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。更多資訊請閱讀 PretrainedConfig 的文件。

示例

>>> from transformers import YolosConfig, YolosModel

>>> # Initializing a YOLOS hustvl/yolos-base style configuration
>>> configuration = YolosConfig()

>>> # Initializing a model (with random weights) from the hustvl/yolos-base style configuration
>>> model = YolosModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

YolosImageProcessor

class transformers.YolosImageProcessor

< >

( 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, 可選, 預設為 "coco_detection") — 標註的資料格式。可以是 “coco_detection” 或 “coco_panoptic”。
  • do_resize (bool, 可選, 預設為 True) — 控制是否將影像的(高、寬)維度調整為指定的 size。可在 preprocess 方法中透過 do_resize 引數覆蓋此設定。
  • size (dict[str, int] 可選, 預設為 {"shortest_edge" -- 800, "longest_edge": 1333}): 調整大小後圖像的 (高, 寬) 維度。可在 preprocess 方法中透過 size 引數覆蓋此設定。可用選項有:
    • {"height": int, "width": int}: 影像將被調整為精確的 (高, 寬) 尺寸。不保持寬高比。
    • {"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 (intfloat, 可選, 預設為 1/255) — 縮放影像時使用的縮放因子。可在 preprocess 方法中透過 rescale_factor 引數覆蓋此設定。
  • do_normalize — 控制是否對影像進行歸一化。可在 preprocess 方法中透過 do_normalize 引數覆蓋此設定。
  • image_mean (floatlist[float], 可選, 預設為 IMAGENET_DEFAULT_MEAN) — 歸一化影像時使用的均值。可以是一個單一值,也可以是一個列表,每個通道一個值。可在 preprocess 方法中透過 image_mean 引數覆蓋此設定。
  • image_std (floatlist[float], 可選, 預設為 IMAGENET_DEFAULT_STD) — 歸一化影像時使用的標準差值。可以是一個單一值,也可以是一個列表,每個通道一個值。可在 preprocess 方法中透過 image_std 引數覆蓋此設定。
  • do_pad (bool, optional, defaults to True) — 控制是否對影像進行填充。可在 `preprocess` 方法中使用 `do_pad` 引數進行覆蓋。如果為 `True`,則會在影像的底部和右側用零進行填充。如果提供了 `pad_size`,影像將被填充到指定尺寸。否則,影像將被填充到批處理中的最大高度和寬度。
  • pad_size (dict[str, int], optional) — 用於填充影像的尺寸 {"height": int, "width" int}。必須大於為預處理提供的任何影像尺寸。如果未提供 `pad_size`,影像將被填充到批處理中的最大高度和寬度。

構建一個 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 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: 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 or list[AnnotationType], optional) — 與影像或影像批次相關聯的標註列表。如果標註用於目標檢測,標註應為包含以下鍵的字典:
    • “image_id” (int): 影像 ID。
    • “annotations” (list[Dict]): 影像的標註列表。每個標註都應為一個字典。一張影像可以沒有標註,此時列表應為空。如果標註用於分割,標註應為包含以下鍵的字典:
    • “image_id” (int): 影像 ID。
    • “segments_info” (list[Dict]): 影像的分割資訊列表。每個分割資訊都應為一個字典。一張影像可以沒有分割資訊,此時列表應為空。
    • “file_name” (str): 影像的檔名。
  • return_segmentation_masks (bool, optional, defaults to self.return_segmentation_masks) — 是否返回分割掩碼。
  • masks_path (str or pathlib.Path, optional) — 包含分割掩碼的目錄路徑。
  • do_resize (bool, optional, defaults to self.do_resize) — 是否調整影像大小。
  • size (dict[str, int], optional, defaults to self.size) — 調整大小後圖像的 `(height, width)` 尺寸。可用選項包括:
    • {"height": int, "width": int}: 影像將被調整為精確的 `(height, width)` 尺寸。不保持寬高比。
    • {"shortest_edge": int, "longest_edge": int}: 影像將被調整到最大尺寸,同時保持寬高比,並使最短邊小於或等於 `shortest_edge`,最長邊小於或等於 `longest_edge`。
    • {"max_height": int, "max_width": int}: 影像將被調整到最大尺寸,同時保持寬高比,並使高度小於或等於 `max_height`,寬度小於或等於 `max_width`。
  • resample (PILImageResampling, optional, defaults to self.resample) — 調整影像大小時使用的重取樣濾波器。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否對影像進行縮放。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 對影像進行縮放時使用的縮放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否對影像進行歸一化。
  • image_mean (float or list[float], optional, defaults to self.image_mean) — 歸一化影像時使用的均值。
  • image_std (float or list[float], optional, defaults to self.image_std) — 歸一化影像時使用的標準差。
  • do_convert_annotations (bool, optional, defaults to self.do_convert_annotations) — 是否將標註轉換為模型期望的格式。將邊界框從 `(top_left_x, top_left_y, width, height)` 格式轉換為 `(center_x, center_y, width, height)` 格式,並使用相對座標。
  • do_pad (bool, optional, defaults to self.do_pad) — 是否對影像進行填充。如果為 `True`,則會在影像的底部和右側用零進行填充。如果提供了 `pad_size`,影像將被填充到指定尺寸。否則,影像將被填充到批處理中的最大高度和寬度。
  • format (str or AnnotationFormat, optional, defaults to self.format) — 標註的格式。
  • return_tensors (str or TensorType, optional, defaults to self.return_tensors) — 返回張量的型別。如果為 `None`,將返回影像列表。
  • data_format (str or ChannelDimension, optional, defaults to self.data_format) — 影像的通道維度格式。如果未提供,將與輸入影像相同。
  • input_data_format (ChannelDimension or str, optional) — 輸入影像的通道維度格式。如果未設定,將從輸入影像中推斷通道維度格式。可以是以下之一:
    • "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], optional) — 用於填充影像的尺寸 {"height": int, "width" int}。必須大於為預處理提供的任何影像尺寸。如果未提供 `pad_size`,影像將被填充到批處理中的最大高度和寬度。

預處理影像或影像批次,以便模型可以使用。

YolosImageProcessorFast

class transformers.YolosImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.yolos.image_processing_yolos_fast.YolosFastImageProcessorKwargs] )

構建一個快速 Yolos 影像處理器。

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 masks_path: typing.Union[str, pathlib.Path, NoneType] = None **kwargs: typing_extensions.Unpack[transformers.models.yolos.image_processing_yolos_fast.YolosFastImageProcessorKwargs] ) <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 or list[AnnotationType], optional) — 與影像或影像批次相關聯的標註列表。如果標註用於目標檢測,標註應為包含以下鍵的字典:
    • “image_id” (int): 影像 ID。
    • “annotations” (list[Dict]): 影像的標註列表。每個標註都應為一個字典。一張影像可以沒有標註,此時列表應為空。如果標註用於分割,標註應為包含以下鍵的字典:
    • “image_id” (int): 影像 ID。
    • “segments_info” (list[Dict]): 影像的分割資訊列表。每個分割資訊都應為一個字典。一張影像可以沒有分割資訊,此時列表應為空。
    • “file_name” (str): 影像的檔名。
  • masks_path (str or pathlib.Path, optional) — 包含分割掩碼的目錄路徑。
  • do_resize (bool, optional) — 是否調整影像大小。
  • size (dict[str, int], optional) — 描述模型的最大輸入尺寸。
  • default_to_square (bool, optional) — 在調整大小時,如果 size 是一個整數,是否預設調整為方形影像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果要調整影像大小,使用的重取樣濾波器。這可以是 `PILImageResampling` 列舉之一。僅當 `do_resize` 設定為 `True` 時有效。
  • do_center_crop (bool, optional) — 是否對影像進行中心裁剪。
  • crop_size (dict[str, int], optional) — 應用 `center_crop` 後輸出影像的尺寸。
  • do_rescale (bool, optional) — 是否對影像進行縮放。
  • rescale_factor (Union[int, float, NoneType]) — 如果 `do_rescale` 設定為 `True`,用於縮放影像的縮放因子。
  • do_normalize (bool, optional) — 是否對影像進行歸一化。
  • image_mean (Union[float, list[float], NoneType]) — 用於歸一化的影像均值。僅當 `do_normalize` 設定為 `True` 時有效。
  • image_std (Union[float, list[float], NoneType]) — 用於歸一化的影像標準差。僅當 `do_normalize` 設定為 `True` 時有效。
  • do_convert_rgb (bool, optional) — 是否將影像轉換為 RGB 格式。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果設定為 `pt`,則返回堆疊的張量,否則返回張量列表。
  • data_format (~image_utils.ChannelDimension, optional) — 僅支援 `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, optional) — 處理影像的裝置。如果未設定,將從輸入影像中推斷裝置。
  • disable_grouping (bool, optional) — 是否停用按尺寸對影像進行分組,以便單獨處理而不是分批處理。如果為 None,則在影像位於 CPU 上時設定為 True,否則設定為 False。此選擇基於經驗觀察,詳見:https://github.com/huggingface/transformers/pull/38157
  • format (str, optional, defaults to AnnotationFormat.COCO_DETECTION) — 標註的資料格式。可以是 “coco_detection” 或 “coco_panoptic” 之一。
  • do_convert_annotations (bool, optional, defaults to True) — 控制是否將標註轉換為 YOLOS 模型期望的格式。將邊界框轉換為 `(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張量。

pad

< >

( image: Tensor padded_size: tuple annotation: typing.Optional[dict[str, typing.Any]] = None update_bboxes: bool = True fill: int = 0 )

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 (YolosObjectDetectionOutput) — 模型的原始輸出。
  • threshold (float, 可選) — 用於保留目標檢測預測結果的分數閾值。
  • target_sizes (torch.Tensorlist[tuple[int, int]], 可選) — 形狀為 (batch_size, 2) 的張量或包含批處理中每張影像目標尺寸(高度,寬度)的元組列表 (tuple[int, int])。如果留空為 None,則不會調整預測結果的大小。
  • top_k (int, 可選, 預設為 100) — 在透過閾值過濾之前,僅保留前 k 個邊界框。

返回

list[Dict]

一個字典列表,每個字典包含模型預測的批處理中每張影像的分數、標籤和框。

YolosForObjectDetection 的原始輸出轉換為最終的邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。僅支援 PyTorch。

YolosFeatureExtractor

class transformers.YolosFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

預處理單張或批次影像。

pad

< >

( images: list annotations: typing.Optional[list[dict[str, typing.Any]]] = None constant_values: typing.Union[float, collections.abc.Iterable[float]] = 0 return_pixel_mask: bool = False return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None update_bboxes: bool = True pad_size: typing.Optional[dict[str, int]] = None )

引數

  • image (np.ndarray) — 待填充的影像。
  • annotations (list[dict[str, any]], 可選) — 隨影像一同填充的標註。如果提供此引數,邊界框將被更新以匹配填充後的影像。
  • constant_values (floatIterable[float], 可選) — 當 `mode` 為 `"constant"` 時用於填充的值。
  • return_pixel_mask (bool, 可選, 預設為 True) — 是否返回畫素掩碼。
  • return_tensors (strTensorType, 可選) — 返回張量的型別。可以是以下之一:
    • 未設定:返回 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回型別為 tf.Tensor 的批處理。
    • TensorType.PYTORCH'pt':返回型別為 torch.Tensor 的批處理。
    • TensorType.NUMPY'np':返回型別為 np.ndarray 的批處理。
    • TensorType.JAX'jax':返回型別為 jax.numpy.ndarray 的批處理。
  • data_format (strChannelDimension, 可選) — 影像的通道維度格式。如果未提供,將與輸入影像的格式相同。
  • input_data_format (ChannelDimensionstr, 可選) — 輸入影像的通道維度格式。如果未提供,將自動推斷。
  • update_bboxes (bool, 可選, 預設為 True) — 是否更新標註中的邊界框以匹配填充後的影像。如果邊界框尚未轉換為相對座標和 `(centre_x, centre_y, width, height)` 格式,則不會更新邊界框。
  • 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 ) list[Dict]

引數

  • outputs (YolosObjectDetectionOutput) — 模型的原始輸出。
  • threshold (float, 可選) — 用於保留目標檢測預測結果的分數閾值。
  • target_sizes (torch.Tensorlist[tuple[int, int]], 可選) — 形狀為 (batch_size, 2) 的張量或包含批處理中每張影像目標尺寸 (height, width) 的元組列表 (tuple[int, int])。如果未設定,則不會調整預測結果的大小。

返回

list[Dict]

一個字典列表,每個字典包含模型預測的批處理中每張影像的分數、標籤和框。

YolosForObjectDetection 的原始輸出轉換為最終的邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。僅支援 PyTorch。

YolosModel

class transformers.YolosModel

< >

( config: YolosConfig add_pooling_layer: bool = True )

引數

  • config (YolosConfig) — 包含模型所有引數的模型配置類。使用配置檔案進行初始化不會載入與模型關聯的權重,只會載入配置。請查閱 from_pretrained() 方法來載入模型權重。
  • add_pooling_layer (bool, 可選, 預設為 True) — 是否新增池化層。

基礎的 Yolos 模型,輸出原始的隱藏狀態,頂部沒有任何特定的頭。

該模型繼承自 PreTrainedModel。查閱超類文件以瞭解該庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

該模型也是一個 PyTorch torch.nn.Module 子類。可以像常規 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與通用用法和行為相關的事項。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

引數

  • pixel_values (torch.Tensor,形狀為 (batch_size, num_channels, image_size, image_size), 可選) — 對應於輸入影像的張量。畫素值可以透過 {image_processor_class} 獲得。詳情請參閱 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 處理影像)。
  • head_mask (torch.Tensor,形狀為 (num_heads,)(num_layers, num_heads), 可選) — 用於使自注意力模組的選定頭部無效的掩碼。掩碼值選自 [0, 1]

    • 1 表示頭部未被遮蔽
    • 0 表示頭部被遮蔽
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

transformers.modeling_outputs.BaseModelOutputWithPoolingtorch.FloatTensor 的元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),根據配置(YolosConfig)和輸入,包含各種元素。

  • last_hidden_state (torch.FloatTensor, 形狀為 (batch_size, sequence_length, hidden_size)) — 模型最後一層輸出的隱藏狀態序列。

  • pooler_output (torch.FloatTensor,形狀為 (batch_size, hidden_size)) — 序列的第一個標記(分類標記)的最後一層隱藏狀態,經過用於輔助預訓練任務的層進一步處理。例如,對於 BERT 系列模型,這將返回經過線性層和 tanh 啟用函式處理後的分類標記。線性層權重是在預訓練期間從下一句預測(分類)目標中訓練的。

  • hidden_states (tuple(torch.FloatTensor), 可選, 當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — torch.FloatTensor 的元組(如果模型有嵌入層,則一個是嵌入層的輸出,加上每個層的輸出),形狀為 (batch_size, sequence_length, hidden_size)

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

  • attentions (tuple(torch.FloatTensor), 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — torch.FloatTensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

YolosModel 的 forward 方法覆蓋了 `__call__` 特殊方法。

雖然前向傳播的流程需要在此函式中定義,但之後應該呼叫 `Module` 例項而不是這個函式,因為前者會處理預處理和後處理步驟,而後者會靜默地忽略它們。

示例

YolosForObjectDetection

class transformers.YolosForObjectDetection

< >

( config: YolosConfig )

引數

  • config (YolosConfig) — 包含模型所有引數的模型配置類。使用配置檔案進行初始化不會載入與模型關聯的權重,只會載入配置。請查閱 from_pretrained() 方法來載入模型權重。

YOLOS 模型(由一個 ViT 編碼器組成),頂部帶有目標檢測頭,用於如 COCO 檢測等任務。

該模型繼承自 PreTrainedModel。查閱超類文件以瞭解該庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

該模型也是一個 PyTorch torch.nn.Module 子類。可以像常規 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與通用用法和行為相關的事項。

forward

< >

( pixel_values: FloatTensor 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.yolos.modeling_yolos.YolosObjectDetectionOutputtuple(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} 處理影像)。
  • labels (list[Dict],長度為 (batch_size,), 可選) — 用於計算二分匹配損失的標籤。是字典的列表,每個字典至少包含以下 2 個鍵:'class_labels''boxes'(分別表示批處理中影像的類別標籤和邊界框)。類別標籤本身應為長度為 (影像中邊界框的數量,)torch.LongTensor,而邊界框應為形狀為 (影像中邊界框的數量, 4)torch.FloatTensor
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。

返回

transformers.models.yolos.modeling_yolos.YolosObjectDetectionOutputtuple(torch.FloatTensor)

transformers.models.yolos.modeling_yolos.YolosObjectDetectionOutputtorch.FloatTensor 的元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),根據配置(YolosConfig)和輸入,包含各種元素。

  • loss (torch.FloatTensor,形狀為 (1,), 可選, 當提供了 labels 時返回) — 總損失,是類別預測的負對數似然(交叉熵)和邊界框損失的線性組合。後者定義為 L1 損失和廣義尺度不變 IoU 損失的線性組合。

  • loss_dict (Dict, 可選) — 包含各個損失的字典。用於日誌記錄。

  • logits (形狀為 (batch_size, num_queries, num_classes + 1)torch.FloatTensor) — 所有查詢的分類 logits(包括無物件)。

  • pred_boxes (torch.FloatTensor,形狀為 (batch_size, num_queries, 4)) — 所有查詢的歸一化邊界框座標,表示為 (center_x, center_y, width, height)。這些值在 [0, 1] 範圍內歸一化,相對於批處理中每個單獨影像的大小(不考慮可能的填充)。你可以使用 post_process() 來檢索未歸一化的邊界框。

  • auxiliary_outputs (list[Dict], 可選) — 可選,僅在啟用輔助損失(即 config.auxiliary_loss 設定為 True)並提供標籤時返回。它是一個字典列表,包含每個解碼器層的上述兩個鍵(`logits` 和 `pred_boxes`)。

  • last_hidden_state (形狀為 (batch_size, sequence_length, hidden_size)torch.FloatTensor可選) — 模型解碼器最後一層輸出的隱藏狀態序列。

  • hidden_states (tuple[torch.FloatTensor], 可選, 當傳遞 output_hidden_states=True 或當 config.output_hidden_states=True 時返回) — `torch.FloatTensor` 的元組(如果模型有嵌入層,則一個是嵌入層的輸出,加上每個層的輸出),形狀為 (batch_size, sequence_length, hidden_size)

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

  • attentions (tuple[torch.FloatTensor], 可選, 當傳遞 output_attentions=True 或當 config.output_attentions=True 時返回) — `torch.FloatTensor` 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

YolosForObjectDetection 的 forward 方法覆蓋了 `__call__` 特殊方法。

雖然前向傳播的流程需要在此函式中定義,但之後應該呼叫 `Module` 例項而不是這個函式,因為前者會處理預處理和後處理步驟,而後者會靜默地忽略它們。

示例

>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> import torch
>>> 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("hustvl/yolos-tiny")
>>> model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-tiny")

>>> 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.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 remote with confidence 0.991 at location [46.48, 72.78, 178.98, 119.3]
Detected remote with confidence 0.908 at location [336.48, 79.27, 368.23, 192.36]
Detected cat with confidence 0.934 at location [337.18, 18.06, 638.14, 373.09]
Detected cat with confidence 0.979 at location [10.93, 53.74, 313.41, 470.67]
Detected remote with confidence 0.974 at location [41.63, 72.23, 178.09, 119.99]
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.