Transformers 文件

大遷移 (BiT)

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

大遷移 (BiT)

PyTorch

概述

BiT 模型由 Alexander Kolesnikov, Lucas Beyer, Xiaohua Zhai, Joan Puigcerver, Jessica Yung, Sylvain Gelly, Neil Houlsby 在 Big Transfer (BiT): General Visual Representation Learning 中提出。BiT 是一種簡單的方案,用於擴充套件 ResNet-like 架構(特別是 ResNetv2)的預訓練。該方法顯著改進了遷移學習。

論文摘要如下:

預訓練表示的遷移提高了樣本效率,並簡化了用於視覺的深度神經網路訓練時的超引數調整。我們重新審視了在大規模監督資料集上進行預訓練並在目標任務上對模型進行微調的正規化。我們擴充套件了預訓練,並提出了一種我們稱之為 Big Transfer (BiT) 的簡單方案。透過結合一些精心選擇的元件,並使用簡單的啟發式方法進行遷移,我們在 20 多個數據集上取得了強大的效能。BiT 在令人驚訝的廣泛資料範圍內表現良好——從每個類別 1 個示例到總共 100 萬個示例。BiT 在 ILSVRC-2012 上實現了 87.5% 的 Top-1 準確率,在 CIFAR-10 上實現了 99.4% 的準確率,在 19 個任務的 Visual Task Adaptation Benchmark (VTAB) 上實現了 76.3% 的準確率。在小型資料集上,BiT 在 ILSVRC-2012 上以每個類別 10 個示例實現了 76.8% 的準確率,在 CIFAR-10 上以每個類別 10 個示例實現了 97.0% 的準確率。我們對導致高遷移效能的主要元件進行了詳細分析。

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

使用技巧

  • BiT 模型在架構上等同於 ResNetv2,除了:1) 所有批次歸一化層都被 組歸一化 取代,2) 卷積層使用 權重標準化。作者表明,兩者的結合對於使用大批次進行訓練很有用,並且對遷移學習有顯著影響。

資源

Hugging Face 官方和社群(由 🌎 指示)資源列表,可幫助您開始使用 BiT。

影像分類

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

BitConfig

class transformers.BitConfig

< >

( num_channels = 3 embedding_size = 64 hidden_sizes = [256, 512, 1024, 2048] depths = [3, 4, 6, 3] layer_type = 'preactivation' hidden_act = 'relu' global_padding = None num_groups = 32 drop_path_rate = 0.0 embedding_dynamic_padding = False output_stride = 32 width_factor = 1 out_features = None out_indices = None **kwargs )

引數

  • num_channels (int, 可選, 預設為 3) — 輸入通道數。
  • embedding_size (int, 可選, 預設為 64) — 嵌入層的維度(隱藏大小)。
  • hidden_sizes (list[int], 可選, 預設為 [256, 512, 1024, 2048]) — 每個階段的維度(隱藏大小)。
  • depths (list[int], 可選, 預設為 [3, 4, 6, 3]) — 每個階段的深度(層數)。
  • layer_type (str, 可選, 預設為 "preactivation") — 要使用的層,可以是 "preactivation""bottleneck"
  • hidden_act (str, 可選, 預設為 "relu") — 每個塊中的非線性啟用函式。如果是字串,則支援 "gelu""relu""selu""gelu_new"
  • global_padding (str, 可選) — 卷積層使用的填充策略。可以是 "valid""same"None
  • num_groups (int, 可選, 預設為 32) — BitGroupNormActivation 層使用的組數。
  • drop_path_rate (float, 可選, 預設為 0.0) — 隨機深度路徑的丟棄率。
  • embedding_dynamic_padding (bool, 可選, 預設為 False) — 是否對嵌入層使用動態填充。
  • output_stride (int, 可選, 預設為 32) — 模型的輸出步幅。
  • width_factor (int, 可選, 預設為 1) — 模型的寬度因子。
  • out_features (list[str], 可選) — 如果用作骨幹網路,則輸出特徵列表。可以是 "stem""stage1""stage2" 等(取決於模型有多少個階段)。如果未設定且 out_indices 已設定,則預設為相應的階段。如果未設定且 out_indices 未設定,則預設為最後一個階段。必須與 stage_names 屬性中定義的順序相同。
  • out_indices (list[int], 可選) — 如果用作骨幹網路,則輸出特徵的索引列表。可以是 0、1、2 等(取決於模型有多少個階段)。如果未設定且 out_features 已設定,則預設為相應的階段。如果未設定且 out_features 未設定,則預設為最後一個階段。必須與 stage_names 屬性中定義的順序相同。

這是用於儲存 BitModel 配置的配置類。它用於根據指定的引數例項化 BiT 模型,定義模型架構。使用預設值例項化配置將產生類似於 BiT google/bit-50 架構的配置。

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

示例

>>> from transformers import BitConfig, BitModel

>>> # Initializing a BiT bit-50 style configuration
>>> configuration = BitConfig()

>>> # Initializing a model (with random weights) from the bit-50 style configuration
>>> model = BitModel(configuration)

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

BitImageProcessor

class transformers.BitImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BICUBIC: 3> do_center_crop: bool = True crop_size: typing.Optional[dict[str, int]] = None 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_rgb: bool = True **kwargs )

引數

  • do_resize (bool, 可選, 預設為 True) — 是否將影像的(高度,寬度)尺寸調整為指定的 size。可在 preprocess 方法中由 do_resize 覆蓋。
  • size (dict[str, int] 可選, 預設為 {"shortest_edge" -- 224}): 調整大小後圖像的尺寸。影像最短邊調整為 size[“shortest_edge”],最長邊保持輸入縱橫比。可在 preprocess 方法中由 size 覆蓋。
  • resample (PILImageResampling, 可選, 預設為 PILImageResampling.BICUBIC) — 如果調整影像大小,要使用的重取樣過濾器。可在 preprocess 方法中由 resample 覆蓋。
  • do_center_crop (bool, 可選, 預設為 True) — 是否將影像中心裁剪為指定的 crop_size。可在 preprocess 方法中由 do_center_crop 覆蓋。
  • crop_size (dict[str, int] 可選, 預設為 224) — 應用 center_crop 後輸出影像的大小。可在 preprocess 方法中由 crop_size 覆蓋。
  • 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], 可選, 預設為 OPENAI_CLIP_MEAN) — 如果對影像進行歸一化,要使用的均值。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可在 preprocess 方法中由 image_mean 引數覆蓋。
  • image_std (floatlist[float], 可選, 預設為 OPENAI_CLIP_MEAN) — 如果對影像進行歸一化,要使用的標準差。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可在 preprocess 方法中由 image_std 引數覆蓋。可在 preprocess 方法中由 image_std 引數覆蓋。
  • do_convert_rgb (bool, 可選, 預設為 True) — 是否將影像轉換為 RGB。

構建一個 BiT 影像處理器。

預處理

< >

( 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_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[int] = 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 do_convert_rgb: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[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) — 調整大小後的影像尺寸。影像的最短邊將調整為 size[“shortest_edge”],最長邊將調整為保持輸入寬高比。
  • resample (int, 可選, 預設為 self.resample) — 如果調整影像大小,使用的重取樣過濾器。可以是列舉 PILImageResampling 之一。僅當 do_resize 設定為 True 時有效。
  • do_center_crop (bool, 可選, 預設為 self.do_center_crop) — 是否對影像進行中心裁剪。
  • crop_size (dict[str, int], 可選, 預設為 self.crop_size) — 中心裁剪的尺寸。僅當 do_center_crop 設定為 True 時有效。
  • do_rescale (bool, 可選, 預設為 self.do_rescale) — 是否對影像進行縮放。
  • 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 時有效。
  • do_convert_rgb (bool, 可選, 預設為 self.do_convert_rgb) — 是否將影像轉換為 RGB。
  • 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) 格式。

預處理一張或一批影像。

BitImageProcessorFast

class transformers.BitImageProcessorFast

< >

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

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

預處理

< >

( 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, 可選) — 如果 size 是一個整數,是否預設將影像調整為正方形。
  • 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張量。

BitModel

class transformers.BitModel

< >

( config )

引數

  • config (BitModel) — 帶有模型所有引數的模型配置類。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法來載入模型權重。

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

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

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

前向傳播

< >

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

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一個 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontorch.FloatTensor 的元組(如果傳入 return_dict=Falseconfig.return_dict=False),包含根據配置(BitConfig)和輸入的不同元素。

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

  • pooler_output (torch.FloatTensor, 形狀為 (batch_size, hidden_size)) — 經過空間維度池化操作後的最後一層隱藏狀態。

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

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

BitModel 的前向傳播方法,覆蓋了 __call__ 特殊方法。

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

示例

BitForImageClassification

class transformers.BitForImageClassification

< >

( config )

引數

  • config (BitForImageClassification) — 帶有模型所有引數的模型配置類。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法來載入模型權重。

帶有影像分類頭部(在池化特徵之上是一個線性層)的 BiT 模型,例如用於 ImageNet。

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

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

前向傳播

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(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} 處理影像)。
  • labels (形狀為 (batch_size,)torch.LongTensor, 可選) — 用於計算影像分類/迴歸損失的標籤。索引應在 [0, ..., config.num_labels - 1] 之間。如果 config.num_labels > 1,則計算分類損失(交叉熵)。
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量中的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是純元組。

返回

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

一個 transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontorch.FloatTensor 的元組(如果傳入 return_dict=Falseconfig.return_dict=False),包含根據配置(BitConfig)和輸入的不同元素。

  • 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 時返回) — 形狀為 (batch_size, num_channels, height, width)torch.FloatTensor 元組(一個用於嵌入層的輸出(如果模型有嵌入層),加上一個用於每個階段的輸出)。模型的隱藏狀態(也稱為特徵圖)在每個階段的輸出處。

BitForImageClassification 的前向傳播方法,覆蓋了 __call__ 特殊方法。

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

示例

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/bit-50")
>>> model = BitForImageClassification.from_pretrained("google/bit-50")

>>> 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])
...
< > 在 GitHub 上更新

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