Transformers 文件

金字塔視覺Transformer (PVT)

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

金字塔視覺Transformer (PVT)

PyTorch

概述

PVT 模型由 Wenhai Wang、Enze Xie、Xiang Li、Deng-Ping Fan、Kaitao Song、Ding Liang、Tong Lu、Ping Luo、Ling Shao 在 《金字塔視覺Transformer:一個用於密集預測的通用骨幹網路,無需卷積》中提出。PVT 是一種利用金字塔結構的視覺 Transformer,使其成為密集預測任務的有效骨幹網路。具體來說,它允許使用更細粒度的輸入(每個補丁 4 x 4 畫素),同時隨著 Transformer 的深入而縮小序列長度,從而降低計算成本。此外,還使用空間縮減注意力(SRA)層,以進一步減少學習高解析度特徵時的資源消耗。

論文摘要如下:

儘管卷積神經網路(CNN)在計算機視覺領域取得了巨大成功,但這項工作研究了一種更簡單、無需卷積的骨幹網路,適用於許多密集預測任務。與最近提出的專門用於影像分類的 Vision Transformer (ViT) 不同,我們引入了金字塔視覺 Transformer (PVT),它克服了將 Transformer 移植到各種密集預測任務的困難。與當前的最新技術相比,PVT 具有多項優點。與通常產生低解析度輸出並導致高計算和記憶體成本的 ViT 不同,PVT 不僅可以在影像的密集分割槽上進行訓練以實現高輸出解析度(這對於密集預測很重要),而且還使用漸進式縮小的金字塔來減少大特徵圖的計算量。PVT 繼承了 CNN 和 Transformer 的優點,使其成為各種視覺任務的統一骨幹網路,無需卷積,可以直接替代 CNN 骨幹網路。我們透過大量實驗驗證了 PVT,表明它提升了許多下游任務的效能,包括目標檢測、例項分割和語義分割。例如,在引數數量相當的情況下,PVT+RetinaNet 在 COCO 資料集上取得了 40.4 AP,比 ResNet50+RetinaNet(36.3 AP)高出 4.1 絕對 AP(參見圖 2)。我們希望 PVT 能夠作為畫素級預測的替代和有用的骨幹網路,並促進未來的研究。

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

  • ImageNet-1K 上的 PVTv1
模型變體 大小 Acc@1 引數 (M)
PVT-Tiny 224 75.1 13.2
PVT-Small 224 79.8 24.5
PVT-Medium 224 81.2 44.2
PVT-Large 224 81.7 61.4

PvtConfig

transformers.PvtConfig

< >

( image_size: int = 224 num_channels: int = 3 num_encoder_blocks: int = 4 depths: list = [2, 2, 2, 2] sequence_reduction_ratios: list = [8, 4, 2, 1] hidden_sizes: list = [64, 128, 320, 512] patch_sizes: list = [4, 2, 2, 2] strides: list = [4, 2, 2, 2] num_attention_heads: list = [1, 2, 5, 8] mlp_ratios: list = [8, 8, 4, 4] hidden_act: Mapping = 'gelu' hidden_dropout_prob: float = 0.0 attention_probs_dropout_prob: float = 0.0 initializer_range: float = 0.02 drop_path_rate: float = 0.0 layer_norm_eps: float = 1e-06 qkv_bias: bool = True num_labels: int = 1000 **kwargs )

引數

  • image_size (int, 可選, 預設為 224) — 輸入影像大小
  • num_channels (int, 可選, 預設為 3) — 輸入通道數。
  • num_encoder_blocks (int, 可選, 預設為 4) — 編碼器塊的數量(即 Mix Transformer 編碼器中的階段)。
  • depths (list[int], 可選, 預設為 [2, 2, 2, 2]) — 每個編碼器塊中的層數。
  • sequence_reduction_ratios (list[int], 可選, 預設為 [8, 4, 2, 1]) — 每個編碼器塊中的序列縮減比率。
  • hidden_sizes (list[int], 可選, 預設為 [64, 128, 320, 512]) — 每個編碼器塊的維度。
  • patch_sizes (list[int], 可選, 預設為 [4, 2, 2, 2]) — 每個編碼器塊前的補丁大小。
  • strides (list[int], 可選, 預設為 [4, 2, 2, 2]) — 每個編碼器塊前的步幅。
  • num_attention_heads (list[int], 可選, 預設為 [1, 2, 5, 8]) — Transformer 編碼器每個塊中每個注意力層的注意力頭數量。
  • mlp_ratios (list[int], 可選, 預設為 [8, 8, 4, 4]) — 編碼器塊中 Mix FFNs 的隱藏層大小與輸入層大小的比率。
  • hidden_act (strfunction, 可選, 預設為 "gelu") — 編碼器和池化器中的非線性啟用函式(函式或字串)。如果是字串,則支援 "gelu""relu""selu""gelu_new"
  • hidden_dropout_prob (float, 可選, 預設為 0.0) — 嵌入、編碼器和池化器中所有全連線層的 dropout 機率。
  • attention_probs_dropout_prob (float, 可選, 預設為 0.0) — 注意力機率的 dropout 比率。
  • initializer_range (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的截斷正態分佈初始化器的標準差。
  • drop_path_rate (float, 可選, 預設為 0.0) — Transformer 編碼器塊中用於隨機深度的 dropout 機率。
  • layer_norm_eps (float, 可選, 預設為 1e-06) — 層歸一化層使用的 epsilon 值。
  • qkv_bias (bool, 可選, 預設為 True) — 是否為查詢、鍵和值新增可學習的偏置。
  • num_labels (int, 可選, 預設為 1000) — 類別數量。

這是用於儲存 PvtModel 配置的配置類。它用於根據指定的引數例項化 Pvt 模型,定義模型架構。使用預設值例項化配置將生成類似於 Pvt Xrenya/pvt-tiny-224 架構的配置。

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

示例

>>> from transformers import PvtModel, PvtConfig

>>> # Initializing a PVT Xrenya/pvt-tiny-224 style configuration
>>> configuration = PvtConfig()

>>> # Initializing a model from the Xrenya/pvt-tiny-224 style configuration
>>> model = PvtModel(configuration)

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

PvtImageProcessor

transformers.PvtImageProcessor

< >

( 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 **kwargs )

引數

  • do_resize (bool, 可選, 預設為 True) — 是否將影像的(高度,寬度)尺寸調整為指定的 (size["height"], size["width"])。可以透過 preprocess 方法中的 do_resize 引數覆蓋。
  • size (dict, 可選, 預設為 {"height" -- 224, "width": 224}):調整大小後輸出影像的大小。可以透過 preprocess 方法中的 size 引數覆蓋。
  • resample (PILImageResampling, 可選, 預設為 Resampling.BILINEAR) — 如果調整影像大小,要使用的重取樣過濾器。可以透過 preprocess 方法中的 resample 引數覆蓋。
  • do_rescale (bool, 可選, 預設為 True) — 是否透過指定的比例 rescale_factor 縮放影像。可以透過 preprocess 方法中的 do_rescale 引數覆蓋。
  • rescale_factor (intfloat, 可選, 預設為 1/255) — 如果縮放影像,要使用的比例因子。可以透過 preprocess 方法中的 rescale_factor 引數覆蓋。
  • do_normalize (bool, 可選, 預設為 True) — 是否歸一化影像。可以透過 preprocess 方法中的 do_normalize 引數覆蓋。
  • image_mean (floatlist[float], 可選, 預設為 IMAGENET_DEFAULT_MEAN) — 歸一化影像時使用的均值。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可以透過 preprocess 方法中的 image_mean 引數覆蓋。
  • image_std (floatlist[float], 可選, 預設為 IMAGENET_DEFAULT_STD) — 歸一化影像時使用的標準差。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可以透過 preprocess 方法中的 image_std 引數覆蓋。

構造 PVT 影像處理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = 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 return_tensors: typing.Union[transformers.utils.generic.TensorType, str, 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 )

引數

  • images (ImageInput) — 要預處理的影像。期望單個或批處理影像,畫素值範圍為 0 到 255。如果傳入畫素值在 0 到 1 之間的影像,請設定 do_rescale=False
  • do_resize (bool, 可選, 預設為 self.do_resize) — 是否調整影像大小。
  • size (dict[str, int], 可選, 預設為 self.size) — 字典格式為 {"height": h, "width": w},指定調整大小後輸出影像的尺寸。
  • resample (PILImageResampling 過濾器, 可選, 預設為 self.resample) — 如果調整影像大小,使用的 PILImageResampling 過濾器,例如 PILImageResampling.BILINEAR。僅當 do_resize 設定為 True 時有效。
  • do_rescale (bool, 可選, 預設為 self.do_rescale) — 是否將影像值重新縮放到 [0 - 1] 之間。
  • rescale_factor (float, 可選, 預設為 self.rescale_factor) — 如果 do_rescale 設定為 True,則按此重新縮放因子調整影像。
  • do_normalize (bool, 可選, 預設為 self.do_normalize) — 是否對影像進行歸一化。
  • image_mean (floatlist[float], 可選, 預設為 self.image_mean) — 如果 do_normalize 設定為 True,則使用的影像均值。
  • image_std (floatlist[float], 可選, 預設為 self.image_std) — 如果 do_normalize 設定為 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 (ChannelDimensionstr, 可選, 預設為 ChannelDimension.FIRST) — 輸出影像的通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 影像格式為 (height, width, num_channels)。
    • 未設定: 使用輸入影像的通道維度格式。
  • input_data_format (ChannelDimensionstr, 可選) — 輸入影像的通道維度格式。如果未設定,則從輸入影像推斷通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 影像格式為 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 影像格式為 (height, width)。

預處理一張或一批影像。

PvtImageProcessorFast

class transformers.PvtImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )

構造一個快速 Pvt 影像處理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) <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 設定。
  • 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

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/陣列/張量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可選) — 您可以在此處提供一個`tensor_type`,以便在初始化時將整數列表轉換為PyTorch/TensorFlow/Numpy張量。

PvtForImageClassification

class transformers.PvtForImageClassification

< >

( config: PvtConfig )

引數

  • config (PvtConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化不會載入與模型相關的權重,僅載入配置。請檢視 from_pretrained() 方法以載入模型權重。

Pvt 模型轉換器,頂部帶有一個影像分類頭([CLS] 標記最終隱藏狀態頂部的線性層),例如用於 ImageNet。

此模型繼承自 PreTrainedModel。請檢視超類文件以獲取庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

此模型也是 PyTorch torch.nn.Module 子類。請將其用作常規 PyTorch Module,並參考 PyTorch 文件中與通用用法和行為相關的所有事項。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] labels: 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.ImageClassifierOutput or tuple(torch.FloatTensor)

引數

  • pixel_values (形狀為 (batch_size, num_channels, image_size, image_size)torch.Tensor, 可選) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • labels (形狀為 (batch_size,)torch.LongTensor, 可選) — 用於計算影像分類/迴歸損失的標籤。索引應在 [0, ..., config.num_labels - 1] 範圍內。如果 config.num_labels == 1,則計算迴歸損失(均方損失),如果 config.num_labels > 1,則計算分類損失(交叉熵損失)。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是普通的元組。

返回

transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

一個 transformers.modeling_outputs.ImageClassifierOutput 或一個 torch.FloatTensor 元組(如果傳入 return_dict=Falseconfig.return_dict=False),包含取決於配置 (PvtConfig) 和輸入的不同元素。

  • loss (形狀為 (1,)torch.FloatTensor可選,當提供 labels 時返回) — 分類損失(如果 config.num_labels==1,則為迴歸損失)。

  • logits (形狀為 (batch_size, config.num_labels)torch.FloatTensor) — 分類(如果 config.num_labels==1,則為迴歸)分數(SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), 可選, 當傳入 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — torch.FloatTensor 元組(一個用於嵌入層的輸出,如果模型有嵌入層,再加上每個階段的輸出)形狀為 (batch_size, sequence_length, hidden_size)。模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。

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

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

PvtForImageClassification 的 forward 方法,覆蓋了 __call__ 特殊方法。

儘管前向傳播的配方需要在此函式中定義,但此後應呼叫 Module 例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則靜默忽略它們。

示例

>>> from transformers import AutoImageProcessor, PvtForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("Xrenya/pvt-tiny-224")
>>> model = PvtForImageClassification.from_pretrained("Xrenya/pvt-tiny-224")

>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...

PvtModel

class transformers.PvtModel

< >

( config: PvtConfig )

引數

  • config (PvtConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化不會載入與模型相關的權重,僅載入配置。請檢視 from_pretrained() 方法以載入模型權重。

裸 Pvt 模型,輸出原始隱藏狀態,頂部沒有任何特定頭部。

此模型繼承自 PreTrainedModel。請檢視超類文件以獲取庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

此模型也是 PyTorch torch.nn.Module 子類。請將其用作常規 PyTorch Module,並參考 PyTorch 文件中與通用用法和行為相關的所有事項。

forward

< >

( pixel_values: FloatTensor output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputtuple(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} 處理影像)。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是普通的元組。

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

一個 transformers.modeling_outputs.BaseModelOutput 或一個 torch.FloatTensor 元組(如果傳入 return_dict=Falseconfig.return_dict=False),包含取決於配置 (PvtConfig) 和輸入的不同元素。

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

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

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

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

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

PvtModel 的 forward 方法,覆蓋了 __call__ 特殊方法。

儘管前向傳播的配方需要在此函式中定義,但此後應呼叫 Module 例項而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則靜默忽略它們。

示例

< > 在 GitHub 上更新

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