Transformers 文件

LeViT

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

LeViT

PyTorch

概述

LeViT 模型由 Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze 在 LeViT: Introducing Convolutions to Vision Transformers 中提出。LeViT 透過 Transformer 中解析度遞減的啟用圖和引入注意力偏差以整合位置資訊等架構差異,提高了 Vision Transformer (ViT) 的效能和效率。

論文摘要如下:

我們設計了一個影像分類架構系列,旨在高速狀態下最佳化精度和效率之間的權衡。我們的工作利用了最近在基於注意力的架構方面的發現,這些架構在高度並行處理硬體上具有競爭力。我們回顧了大量關於卷積神經網路的文獻中的原則,並將其應用於 Transformer,特別是解析度遞減的啟用圖。我們還引入了注意力偏差,這是一種在視覺 Transformer 中整合位置資訊的新方法。因此,我們提出了 LeViT:一種用於快速推理影像分類的混合神經網路。我們考慮了在不同硬體平臺上的不同效率度量,以最好地反映各種應用場景。我們大量的實驗經驗性地驗證了我們的技術選擇,並表明它們適用於大多數架構。總的來說,LeViT 在速度/精度權衡方面顯著優於現有的卷積網路和視覺 Transformer。例如,在 80% ImageNet top-1 精度下,LeViT 在 CPU 上比 EfficientNet 快 5 倍。

drawing LeViT 架構。摘自原始論文

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

使用技巧

  • 與 ViT 相比,LeViT 模型使用了一個額外的蒸餾頭,以有效地從教師模型(在 LeViT 論文中是 ResNet 類似模型)中學習。蒸餾頭透過反向傳播在 ResNet 類似模型的監督下進行學習。它們還從卷積神經網路中汲取靈感,使用解析度遞減的啟用圖來提高效率。
  • 微調蒸餾模型有兩種方式:(1) 經典方式,只在最終隱藏狀態之上放置一個預測頭,不使用蒸餾頭;或者 (2) 同時在最終隱藏狀態之上放置預測頭和蒸餾頭。在這種情況下,預測頭使用預測頭和真實標籤之間的常規交叉熵進行訓練,而蒸餾預測頭使用硬蒸餾(蒸餾頭預測和教師預測的標籤之間的交叉熵)進行訓練。在推理時,取兩個頭的平均預測作為最終預測。(2) 也稱為“帶蒸餾的微調”,因為它依賴於已在下游資料集上微調過的教師模型。在模型方面,(1) 對應於 LevitForImageClassification,(2) 對應於 LevitForImageClassificationWithTeacher
  • 所有釋出的檢查點均僅在 ImageNet-1k(也稱為 ILSVRC 2012,包含 130 萬張影像和 1,000 個類別)上進行預訓練和微調。未使用任何外部資料。這與原始 ViT 模型形成對比,原始 ViT 模型使用 JFT-300M 資料集/Imagenet-21k 等外部資料進行預訓練。
  • LeViT 的作者釋出了 5 個經過訓練的 LeViT 模型,你可以直接將其插入 LevitModelLevitForImageClassification。為了模擬在更大的資料集上進行訓練(同時只使用 ImageNet-1k 進行預訓練),使用了資料增強、最佳化和正則化等技術。可用的 5 種變體(所有均在 224x224 尺寸影像上訓練)包括:*facebook/levit-128S*、*facebook/levit-128*、*facebook/levit-192*、*facebook/levit-256* 和 *facebook/levit-384*。請注意,應該使用 LevitImageProcessor 來準備影像供模型使用。
  • LevitForImageClassificationWithTeacher 目前僅支援推理,不支援訓練或微調。
  • 你可以在此處檢視關於推理以及在自定義資料上進行微調的演示筆記本(你可以將 ViTFeatureExtractor 替換為 LevitImageProcessor,並將 ViTForImageClassification 替換為 LevitForImageClassificationLevitForImageClassificationWithTeacher)。

資源

Hugging Face 官方和社群 (🌎 標記) 資源列表,助你快速開始使用 LeViT。

影像分類

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

LevitConfig

class transformers.LevitConfig

< >

( image_size = 224 num_channels = 3 kernel_size = 3 stride = 2 padding = 1 patch_size = 16 hidden_sizes = [128, 256, 384] num_attention_heads = [4, 8, 12] depths = [4, 4, 4] key_dim = [16, 16, 16] drop_path_rate = 0 mlp_ratio = [2, 2, 2] attention_ratio = [2, 2, 2] initializer_range = 0.02 **kwargs )

引數

  • image_size (int, 可選, 預設為 224) — 輸入影像的大小。
  • num_channels (int, 可選, 預設為 3) — 輸入影像中的通道數。
  • kernel_size (int, 可選, 預設為 3) — 補丁嵌入初始卷積層的核大小。
  • stride (int, 可選, 預設為 2) — 補丁嵌入初始卷積層的步幅大小。
  • padding (int, 可選, 預設為 1) — 補丁嵌入初始卷積層的填充大小。
  • patch_size (int, 可選, 預設為 16) — 嵌入的補丁大小。
  • hidden_sizes (list[int], 可選, 預設為 [128, 256, 384]) — 每個編碼器塊的維度。
  • num_attention_heads (list[int], 可選, 預設為 [4, 8, 12]) — Transformer 編碼器每個塊中每個注意力層的注意力頭數量。
  • depths (list[int], 可選, 預設為 [4, 4, 4]) — 每個編碼器塊中的層數。
  • key_dim (list[int], 可選, 預設為 [16, 16, 16]) — 每個編碼器塊中鍵的維度。
  • drop_path_rate (int, 可選, 預設為 0) — Transformer 編碼器塊中使用的隨機深度丟棄機率。
  • mlp_ratios (list[int], 可選, 預設為 [2, 2, 2]) — 編碼器塊中 Mix FFNs 的隱藏層大小與輸入層大小的比例。
  • attention_ratios (list[int], 可選, 預設為 [2, 2, 2]) — 注意力層輸出維度與輸入維度之比。
  • initializer_range (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的截斷正態初始化器的標準差。

這是儲存 LevitModel 配置的配置類。它用於根據指定引數例項化 LeViT 模型,定義模型架構。使用預設值例項化配置將生成與 LeViT facebook/levit-128S 架構類似的配置。

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

示例

>>> from transformers import LevitConfig, LevitModel

>>> # Initializing a LeViT levit-128S style configuration
>>> configuration = LevitConfig()

>>> # Initializing a model (with random weights) from the levit-128S style configuration
>>> model = LevitModel(configuration)

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

LevitFeatureExtractor

class transformers.LevitFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

預處理單張或批次影像。

LevitImageProcessor

class transformers.LevitImageProcessor

< >

( 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, collections.abc.Iterable[float], NoneType] = [0.485, 0.456, 0.406] image_std: typing.Union[float, collections.abc.Iterable[float], NoneType] = [0.229, 0.224, 0.225] **kwargs )

引數

  • do_resize (bool, 可選, 預設為 True) — 是否將輸入影像的最短邊調整為 int(256/224 *size)。可以透過 preprocess 方法中的 do_resize 引數覆蓋。
  • size (dict[str, int], 可選, 預設為 {"shortest_edge" -- 224}): 調整大小後的輸出影像大小。如果 size 是一個包含 "width" 和 "height" 鍵的字典,影像將調整為 (size["height"], size["width"])。如果 size 是一個包含 "shortest_edge" 鍵的字典,最短邊值 c 將按 int(c * (256/224)) 進行縮放。影像的較短邊將與此值匹配,即,如果高度 > 寬度,則影像將縮放為 (size["shortest_egde"] * height / width, size["shortest_egde"])。可以透過 preprocess 方法中的 size 引數覆蓋。
  • resample (PILImageResampling, 可選, 預設為 Resampling.BICUBIC) — 如果調整影像大小,使用的重取樣濾波器。可以透過 preprocess 方法中的 resample 引數覆蓋。
  • do_center_crop (bool, 可選, 預設為 True) — 是否將輸入影像中心裁剪為 (crop_size["height"], crop_size["width"])。可以透過 preprocess 方法中的 do_center_crop 引數覆蓋。
  • crop_size (Dict, 可選, 預設為 {"height" -- 224, "width": 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 (bool, 可選, 預設為 True) — 控制是否對影像進行標準化。可以透過 preprocess 方法中的 do_normalize 引數覆蓋。
  • image_mean (list[int], 可選, 預設為 [0.485, 0.456, 0.406]) — 如果對影像進行標準化,使用的均值。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可以透過 preprocess 方法中的 image_mean 引數覆蓋。
  • image_std (list[int], 可選, 預設為 [0.229, 0.224, 0.225]) — 如果對影像進行標準化,使用的標準差。這是一個浮點數或浮點數列表,其長度與影像中的通道數相同。可以透過 preprocess 方法中的 image_std 引數覆蓋。

構建一個 LeViT 影像處理器。

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_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, 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, collections.abc.Iterable[float], NoneType] = None image_std: typing.Union[float, collections.abc.Iterable[float], NoneType] = None return_tensors: typing.Optional[transformers.utils.generic.TensorType] = None data_format: 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 是一個包含 "width" 和 "height" 鍵的字典,影像將調整為 (height, width)。如果 size 是一個包含 "shortest_edge" 鍵的字典,最短邊值 c 將按 int(c * (256/224)) 進行縮放。影像的較短邊將與此值匹配,即,如果高度 > 寬度,則影像將縮放為 (size * height / width, size)。
  • resample (PILImageResampling, 可選, 預設為 PILImageResampling.BICUBIC) — 調整影像大小時使用的重取樣濾波器。
  • do_center_crop (bool, 可選, 預設為 self.do_center_crop) — 是否中心裁剪影像。
  • crop_size (dict[str, int], 可選, 預設為 self.crop_size) — 中心裁剪後輸出影像的大小。將影像裁剪為 (crop_size[“height”], crop_size[“width”])。
  • do_rescale (bool, 可選, 預設為 self.do_rescale) — 是否透過 rescaling_factor 縮放影像畫素值——通常縮放到 0 和 1 之間的值。
  • rescale_factor (float, 可選, 預設為 self.rescale_factor) — 縮放影像畫素值的因子。
  • do_normalize (bool, 可選, 預設為 self.do_normalize) — 是否透過 image_meanimage_std 規範化影像畫素值。
  • image_mean (floatlist[float], 可選, 預設為 self.image_mean) — 用於規範化影像畫素值的平均值。
  • image_std (floatlist[float], 可選, 預設為 self.image_std) — 用於規範化影像畫素值的標準差。
  • 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, 可選, 預設為 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) 格式。

預處理一個或一批影像,以用作 LeViT 模型的輸入。

LevitImageProcessorFast

class transformers.LevitImageProcessorFast

< >

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

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

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, 可選) — 當調整大小(如果 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張量。

LevitModel

class transformers.LevitModel

< >

( config )

引數

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

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

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

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

前向傳播

< >

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

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一個 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention 或一個 torch.FloatTensor 元組(如果傳入 return_dict=False 或當 config.return_dict=False 時),包含根據配置 (LevitConfig) 和輸入的不同元素。

  • 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=True 或當 config.output_hidden_states=True 時返回) — torch.FloatTensor 元組(如果模型有嵌入層,則為一個輸出,加上每個層的輸出)形狀為 (batch_size, num_channels, height, width)

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

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

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

示例

LevitForImageClassification

class transformers.LevitForImageClassification

< >

( config )

引數

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

帶影像分類頭(在池化特徵之上有一個線性層)的 Levit 模型,例如用於 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 (torch.FloatTensor, 形狀為 (batch_size, num_channels, image_size, image_size), 可選) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參見 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • labels (torch.LongTensor, 形狀為 (batch_size,), 可選) — 用於計算影像分類/迴歸損失的標籤。索引應在 [0, ..., config.num_labels - 1] 範圍內。如果 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.ImageClassifierOutputWithNoAttention 或一個 torch.FloatTensor 元組(如果傳入 return_dict=False 或當 config.return_dict=False 時),包含根據配置 (LevitConfig) 和輸入的不同元素。

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

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

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

示例

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/levit-128S")
>>> model = LevitForImageClassification.from_pretrained("facebook/levit-128S")

>>> 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])
...

LevitForImageClassificationWithTeacher

class transformers.LevitForImageClassificationWithTeacher

< >

( config )

引數

帶影像分類頭(在最終隱藏狀態之上有一個線性層,在蒸餾 token 的最終隱藏狀態之上有一個線性層)的 LeViT 模型轉換器,例如用於 ImageNet。..警告::此模型僅支援推理。尚不支援帶蒸餾(即帶教師)的微調。

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

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

前向傳播

< >

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

返回

transformers.models.levit.modeling_levit.LevitForImageClassificationWithTeacherOutputtuple(torch.FloatTensor)

一個 transformers.models.levit.modeling_levit.LevitForImageClassificationWithTeacherOutput 或一個 torch.FloatTensor 元組(如果傳遞 return_dict=False 或當 config.return_dict=False 時),根據配置(LevitConfig)和輸入包含各種元素。

  • logits (torch.FloatTensor,形狀為 (batch_size, config.num_labels)) — 作為 cls_logitsdistillation_logits 平均值的預測分數。

  • cls_logits (形狀為 (batch_size, config.num_labels)torch.FloatTensor) — 分類頭部(即類標記最終隱藏狀態頂部線性層)的預測分數。

  • distillation_logits (形狀為 (batch_size, config.num_labels)torch.FloatTensor) — 蒸餾頭部(即蒸餾標記最終隱藏狀態頂部線性層)的預測分數。

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

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

LevitForImageClassificationWithTeacher 的前向方法,覆蓋了 __call__ 特殊方法。

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

示例

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/levit-128S")
>>> model = LevitForImageClassificationWithTeacher.from_pretrained("facebook/levit-128S")

>>> 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.