Transformers 文件
DeiT
並獲得增強的文件體驗
開始使用
DeiT
概述
DeiT 模型由 Hugo Touvron、Matthieu Cord、Matthijs Douze、Francisco Massa、Alexandre Sablayrolles 和 Hervé Jégou 在論文 Training data-efficient image transformers & distillation through attention 中提出。Vision Transformer (ViT) 模型在 Dosovitskiy 等人,2020 的論文中提出,表明使用 Transformer 編碼器(類似 BERT)可以匹敵甚至超越現有的卷積神經網路。然而,該論文中介紹的 ViT 模型需要使用外部資料在昂貴的基礎設施上訓練數週。DeiT (data-efficient image transformers) 是為影像分類任務而設計的、訓練效率更高的 Transformer 模型,相比原始 ViT 模型,它需要的資料和計算資源都少得多。
論文摘要如下:
最近,純粹基於注意力機制的神經網路被證明可以解決影像理解任務,如影像分類。然而,這些視覺 Transformer 模型需要使用數億張圖片在昂貴的基礎設施上進行預訓練,從而限制了它們的普及。在這項工作中,我們僅在 ImageNet 上訓練,就產生了一個具有競爭力的無卷積 Transformer 模型。我們在單臺計算機上用不到 3 天的時間就完成了訓練。我們的參考視覺 Transformer 模型(8600 萬引數)在 ImageNet 上(單次裁剪評估)實現了 83.1% 的 top-1 準確率,且未使用任何外部資料。更重要的是,我們引入了一種專為 Transformer 設計的師生策略。它依賴一個蒸餾標記(distillation token),確保學生透過注意力機制向老師學習。我們展示了這種基於標記的蒸餾方法的優勢,特別是在使用卷積網路作為老師時。這使得我們在 ImageNet(準確率高達 85.2%)以及遷移到其他任務時,都取得了與卷積網路相媲美的結果。我們分享了我們的程式碼和模型。
此模型由 nielsr 貢獻。此模型的 TensorFlow 版本由 amyeroberts 新增。
使用技巧
- 與 ViT 相比,DeiT 模型使用一個所謂的蒸餾標記(distillation token),以便有效地從一個老師模型(在 DeiT 論文中,這是一個類似 ResNet 的模型)學習。蒸餾標記透過反向傳播進行學習,它透過自注意力層與類別標記 ([CLS]) 和影像塊標記(patch tokens)進行互動。
- 微調蒸餾模型有兩種方式:(1) 傳統方式,僅在類別標記的最終隱藏狀態之上放置一個預測頭,而不使用蒸餾訊號;或者 (2) 同時在類別標記和蒸餾標記之上都放置一個預測頭。在第二種情況下,[CLS] 預測頭透過常規的交叉熵損失進行訓練,即預測頭的預測與真實標籤之間的損失;而蒸餾預測頭則透過硬蒸餾進行訓練(蒸餾頭預測與老師模型預測的標籤之間的交叉熵)。在推理時,最終預測結果是兩個頭的預測的平均值。(2) 也被稱為“帶蒸餾的微調”,因為這依賴於一個已經在下游資料集上微調過的老師模型。在模型方面,(1) 對應 DeiTForImageClassification,而 (2) 對應 DeiTForImageClassificationWithTeacher。
- 請注意,作者也嘗試了針對 (2) 的軟蒸餾方法(在這種情況下,蒸餾預測頭透過 KL 散度來匹配老師模型的 softmax 輸出),但硬蒸餾取得了最好的結果。
- 所有釋出的檢查點都僅在 ImageNet-1k 上進行預訓練和微調,沒有使用任何外部資料。這與原始的 ViT 模型形成對比,後者使用了像 JFT-300M 資料集/ImageNet-21k 這樣的外部資料進行預訓練。
- DeiT 的作者還發布了訓練效率更高的 ViT 模型,您可以直接將其用於 ViTModel 或 ViTForImageClassification。透過使用資料增強、最佳化和正則化等技術,模擬了在更大的資料集上進行訓練的效果(儘管僅使用 ImageNet-1k 進行預訓練)。共有 4 種變體(3 種不同大小):facebook/deit-tiny-patch16-224、facebook/deit-small-patch16-224、facebook/deit-base-patch16-224 和 facebook/deit-base-patch16-384。請注意,您應該使用 DeiTImageProcessor 來為模型準備影像。
使用縮放點積注意力 (SDPA)
PyTorch 在 torch.nn.functional 中包含了原生的縮放點積注意力(SDPA)運算元。該函式包含多種實現,可根據輸入和使用的硬體進行應用。更多資訊請參閱官方文件或GPU 推理頁面。
當實現可用時,SDPA 預設用於 `torch>=2.1.1`,但你也可以在 `from_pretrained()` 中設定 `attn_implementation="sdpa"` 來明確請求使用 SDPA。
from transformers import DeiTForImageClassification
model = DeiTForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224", attn_implementation="sdpa", torch_dtype=torch.float16)
...為了獲得最佳加速效果,我們建議以半精度(例如 `torch.float16` 或 `torch.bfloat16`)載入模型。
在本地基準測試(A100-40GB, PyTorch 2.3.0, OS Ubuntu 22.04)中,使用 float32 和 facebook/deit-base-distilled-patch16-224 模型,我們在推理過程中觀察到了以下速度提升。
| 批次大小 | 平均推理時間(毫秒),eager 模式 | 平均推理時間(毫秒),sdpa 模型 | 加速,Sdpa / Eager (x) |
|---|---|---|---|
| 1 | 8 | 6 | 1.33 |
| 2 | 9 | 6 | 1.5 |
| 4 | 9 | 6 | 1.5 |
| 8 | 8 | 6 | 1.33 |
資源
一份官方 Hugging Face 和社群(由 🌎 標識)資源的列表,幫助您開始使用 DeiT。
- DeiTForImageClassification 受此示例指令碼和筆記本支援。
- 另請參閱:影像分類任務指南
除此之外
如果您有興趣在此處提交資源,請隨時開啟 Pull Request,我們將對其進行審查!該資源最好能展示一些新內容,而不是重複現有資源。
DeiTConfig
class transformers.DeiTConfig
< 原始檔 >( 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 = 224 patch_size = 16 num_channels = 3 qkv_bias = True encoder_stride = 16 pooler_output_size = None pooler_act = 'tanh' **kwargs )
引數
- hidden_size (
int, 可選, 預設為 768) — 編碼器層和池化層的維度。 - num_hidden_layers (
int, 可選, 預設為 12) — Transformer 編碼器中的隱藏層數量。 - num_attention_heads (
int, 可選, 預設為 12) — Transformer 編碼器中每個注意力層的注意力頭數量。 - intermediate_size (
int, 可選, 預設為 3072) — Transformer 編碼器中“中間”(即前饋)層的維度。 - hidden_act (
str或function, 可選, 預設為"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 (
int, 可選, 預設為 224) — 每張影像的大小(解析度)。 - patch_size (
int, 可選, 預設為 16) — 每個影像塊的大小(解析度)。 - num_channels (
int, 可選, 預設為 3) — 輸入通道的數量。 - qkv_bias (
bool, 可選, 預設為True) — 是否為查詢、鍵和值新增偏置。 - encoder_stride (
int, 可選, 預設為 16) — 在解碼器頭中用於掩碼影像建模時,增加空間解析度的因子。 - pooler_output_size (
int, 可選) — 池化層的維度。如果為 None,則預設為hidden_size。 - pooler_act (
str, 可選, 預設為"tanh") — 池化層要使用的啟用函式。對於 Flax 和 Pytorch,支援 ACT2FN 的鍵;對於 Tensorflow,支援 https://www.tensorflow.org/api_docs/python/tf/keras/activations 中的元素。
這是用於儲存 DeiTModel 配置的配置類。它用於根據指定的引數例項化一個 DeiT 模型,定義模型架構。使用預設值例項化配置將產生與 DeiT facebook/deit-base-distilled-patch16-224 架構類似的配置。
配置物件繼承自 PretrainedConfig,可用於控制模型輸出。更多資訊請參閱 PretrainedConfig 的文件。
示例
>>> from transformers import DeiTConfig, DeiTModel
>>> # Initializing a DeiT deit-base-distilled-patch16-224 style configuration
>>> configuration = DeiTConfig()
>>> # Initializing a model (with random weights) from the deit-base-distilled-patch16-224 style configuration
>>> model = DeiTModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configDeiTFeatureExtractor
預處理單張或批次影像。
DeiTImageProcessor
class transformers.DeiTImageProcessor
< 原始檔 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = 3 do_center_crop: bool = True crop_size: typing.Optional[dict[str, int]] = None rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_rescale: bool = True 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。可在preprocess中透過do_resize覆蓋。 - size (
dict[str, int]可選, 預設為{"height" -- 256, "width": 256}):resize後的影像尺寸。可在preprocess中透過size覆蓋。 - resample (
PILImageResampling過濾器, 可選, 預設為Resampling.BICUBIC) — 調整影像大小時使用的重取樣過濾器。可在preprocess中透過resample覆蓋。 - do_center_crop (
bool, 可選, 預設為True) — 是否對影像進行中心裁剪。如果輸入的尺寸在任何一邊小於crop_size,影像會先用 0 填充,然後再進行中心裁剪。可在preprocess中透過do_center_crop覆蓋。 - crop_size (
dict[str, int], 可選, 預設為{"height" -- 224, "width": 224}): 應用中心裁剪時期望的輸出尺寸。可在preprocess中透過crop_size覆蓋。 - rescale_factor (
int或float, 可選, 預設為1/255) — 如果重縮放影像,則使用此縮放因子。可在preprocess方法中透過rescale_factor引數覆蓋。 - do_rescale (
bool, 可選, 預設為True) — 是否按指定的縮放因子rescale_factor對影像進行重縮放。可在preprocess方法中透過do_rescale引數覆蓋。 - do_normalize (
bool, 可選, 預設為True) — 是否對影像進行歸一化。可在preprocess方法中透過do_normalize引數覆蓋。 - image_mean (
floatorlist[float], optional, defaults toIMAGENET_STANDARD_MEAN) — 用於影像歸一化的均值。這是一個浮點數或浮點數列表,其長度等於影像中的通道數。可以透過preprocess方法中的image_mean引數覆蓋此值。 - image_std (
floatorlist[float], optional, defaults toIMAGENET_STANDARD_STD) — 用於影像歸一化的標準差。這是一個浮點數或浮點數列表,其長度等於影像中的通道數。可以透過preprocess方法中的image_std引數覆蓋此值。
構建一個 DeiT 影像處理器。
preprocess
< source >( 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 = 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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = 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, optional, defaults toself.do_resize) — 是否調整影像大小。 - size (
dict[str, int], optional, defaults toself.size) —resize後的影像大小。 - resample (
PILImageResampling, optional, defaults toself.resample) — 用於調整影像大小的 PILImageResampling 過濾器,僅當do_resize設定為True時有效。 - do_center_crop (
bool, optional, defaults toself.do_center_crop) — 是否對影像進行中心裁剪。 - crop_size (
dict[str, int], optional, defaults toself.crop_size) — 中心裁剪後的影像大小。如果影像的一條邊小於crop_size,將用零進行填充,然後進行裁剪。 - do_rescale (
bool, optional, defaults toself.do_rescale) — 是否將影像值重新縮放到 [0 - 1] 之間。 - rescale_factor (
float, optional, defaults toself.rescale_factor) — 當do_rescale設定為True時,用於重新縮放影像的比例因子。 - do_normalize (
bool, optional, defaults toself.do_normalize) — 是否對影像進行歸一化。 - image_mean (
floatorlist[float], optional, defaults toself.image_mean) — 影像均值。 - image_std (
floatorlist[float], optional, defaults toself.image_std) — 影像標準差。 - return_tensors (
strorTensorType, optional) — 返回的張量型別。可以是以下之一:None: 返回一個np.ndarray列表。TensorType.TENSORFLOWor'tf': 返回一個tf.Tensor型別的批次。TensorType.PYTORCHor'pt': 返回一個torch.Tensor型別的批次。TensorType.NUMPYor'np': 返回一個np.ndarray型別的批次。TensorType.JAXor'jax': 返回一個jax.numpy.ndarray型別的批次。
- data_format (
ChannelDimensionorstr, optional, defaults toChannelDimension.FIRST) — 輸出影像的通道維度格式。可以是以下之一:ChannelDimension.FIRST: 影像格式為 (num_channels, height, width)。ChannelDimension.LAST: 影像格式為 (height, width, num_channels)。
- input_data_format (
ChannelDimensionorstr, optional) — 輸入影像的通道維度格式。如果未設定,則從輸入影像中推斷通道維度格式。可以是以下之一:"channels_first"orChannelDimension.FIRST: 影像格式為 (num_channels, height, width)。"channels_last"orChannelDimension.LAST: 影像格式為 (height, width, num_channels)。"none"orChannelDimension.NONE: 影像格式為 (height, width)。
預處理一張或一批影像。
DeiTImageProcessorFast
class transformers.DeiTImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
構建一個快速 Deit 影像處理器。
preprocess
< source >( 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, 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"orChannelDimension.FIRST: 影像格式為 (num_channels, height, width)。"channels_last"orChannelDimension.LAST: 影像格式為 (height, width, num_channels)。"none"orChannelDimension.NONE: 影像格式為 (height, width)。
- device (
torch.device, optional) — 處理影像的裝置。如果未設定,則從輸入影像中推斷裝置。 - disable_grouping (
bool, optional) — 是否停用按大小對影像進行分組,以便單獨處理而不是分批處理。如果為 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張量。
DeiTModel
class transformers.DeiTModel
< source >( config: DeiTConfig add_pooling_layer: bool = True use_mask_token: bool = False )
引數
- config (DeiTConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化不會載入與模型相關的權重,只會載入配置。請查閱 from_pretrained() 方法來載入模型權重。
- add_pooling_layer (
bool, optional, defaults toTrue) — 是否新增池化層。 - use_mask_token (
bool, optional, defaults toFalse) — 是否為掩碼影像建模使用掩碼標記。
一個基礎的 Deit 模型,輸出原始的隱藏狀態,沒有任何特定的頭部。
該模型繼承自 PreTrainedModel。請查閱超類文件以瞭解該庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
該模型也是 PyTorch 的 torch.nn.Module 子類。可以像常規的 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與常規用法和行為相關的事項。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.BoolTensor] = 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 interpolate_pos_encoding: bool = False ) → transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
引數
- pixel_values (
torch.Tensorof shape(batch_size, num_channels, image_size, image_size), optional) — 對應於輸入影像的張量。畫素值可以使用{image_processor_class}獲得。有關詳細資訊,請參閱{image_processor_class}.__call__({processor_class}使用{image_processor_class}處理影像)。 - bool_masked_pos (
torch.BoolTensorof shape(batch_size, num_patches), optional) — 布林型別的掩碼位置。指示哪些影像塊被掩蓋(1),哪些沒有被掩蓋(0)。 - head_mask (
torch.Tensorof shape(num_heads,)or(num_layers, num_heads), optional) — 用於使自注意力模組的選定頭部無效的掩碼。掩碼值在[0, 1]中選擇:- 1 表示頭部未被掩蓋,
- 0 表示頭部被掩蓋。
- output_attentions (
bool, optional) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的attentions。 - output_hidden_states (
bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的hidden_states。 - return_dict (
bool, 可選) — 是否返回 ModelOutput 而不是普通元組。 - interpolate_pos_encoding (
bool, 預設為False) — 是否對預訓練的位置編碼進行插值。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一個 transformers.modeling_outputs.BaseModelOutputWithPooling 或一個 torch.FloatTensor 的元組 (如果傳遞了 return_dict=False 或 config.return_dict=False),它包含根據配置 (DeiTConfig) 和輸入而定的各種元素。
-
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 後的注意力權重,用於計算自注意力頭中的加權平均值。
DeiTModel 的 forward 方法,重寫了 __call__ 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理前處理和後處理步驟,而後者會靜默地忽略它們。
DeiTForMaskedImageModeling
class transformers.DeiTForMaskedImageModeling
< 原始碼 >( config: DeiTConfig )
引數
- config (DeiTConfig) — 包含模型所有引數的模型配置類。使用配置檔案進行初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
DeiT 模型,頂部帶有一個解碼器用於掩碼影像建模,如 SimMIM 中所提出的。
請注意,我們在 examples directory 中提供了一個指令碼,用於在自定義資料上預訓練此模型。
該模型繼承自 PreTrainedModel。請查閱超類文件以瞭解該庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
該模型也是 PyTorch 的 torch.nn.Module 子類。可以像常規的 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與常規用法和行為相關的事項。
forward
< 原始碼 >( pixel_values: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.BoolTensor] = 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 interpolate_pos_encoding: bool = False ) → transformers.modeling_outputs.MaskedImageModelingOutput or tuple(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}處理影像)。 - bool_masked_pos (
torch.BoolTensor,形狀為(batch_size, num_patches)) — 布林掩碼位置。指示哪些影像塊被掩碼 (1),哪些沒有 (0)。 - 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 而不是普通的元組。 - interpolate_pos_encoding (
bool, 預設為False) — 是否對預訓練的位置編碼進行插值。
返回
transformers.modeling_outputs.MaskedImageModelingOutput 或 tuple(torch.FloatTensor)
一個 transformers.modeling_outputs.MaskedImageModelingOutput 或一個 torch.FloatTensor 的元組 (如果傳遞了 return_dict=False 或 config.return_dict=False),它包含根據配置 (DeiTConfig) 和輸入而定的各種元素。
- loss (
torch.FloatTensor,形狀為(1,), 可選, 當提供了bool_masked_pos時返回) — 重建損失。 - reconstruction (
torch.FloatTensor,形狀為(batch_size, num_channels, height, width)) — 重建/補全的影像。 - 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, patch_size, sequence_length)。經過注意力 softmax 後的注意力權重,用於在自注意力頭中計算加權平均。
DeiTForMaskedImageModeling 的 forward 方法,重寫了 __call__ 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理前處理和後處理步驟,而後者會靜默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, DeiTForMaskedImageModeling
>>> 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("facebook/deit-base-distilled-patch16-224")
>>> model = DeiTForMaskedImageModeling.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
>>> list(reconstructed_pixel_values.shape)
[1, 3, 224, 224]DeiTForImageClassification
class transformers.DeiTForImageClassification
< 原始碼 >( config: DeiTConfig )
引數
- config (DeiTConfig) — 包含模型所有引數的模型配置類。使用配置檔案進行初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
DeiT Transformer 模型,頂部帶有一個影像分類頭 (在 [CLS] 標記的最終隱藏狀態上加一個線性層),例如用於 ImageNet。
該模型繼承自 PreTrainedModel。請查閱超類文件以瞭解該庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
該模型也是 PyTorch 的 torch.nn.Module 子類。可以像常規的 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與常規用法和行為相關的事項。
forward
< 原始碼 >( pixel_values: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None 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 interpolate_pos_encoding: bool = False ) → transformers.modeling_outputs.ImageClassifierOutput 或 tuple(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 表示頭被掩碼。
- labels (
torch.LongTensor,形狀為(batch_size,), 可選) — 用於計算影像分類/迴歸損失的標籤。索引應在[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 而不是普通的元組。 - interpolate_pos_encoding (
bool, 預設為False) — 是否對預訓練的位置編碼進行插值。
返回
transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
一個 transformers.modeling_outputs.ImageClassifierOutput 或一個 torch.FloatTensor 的元組 (如果傳遞了 return_dict=False 或 config.return_dict=False),它包含根據配置 (DeiTConfig) 和輸入而定的各種元素。
-
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, sequence_length, hidden_size)。模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。 -
attentions (
tuple(torch.FloatTensor), 可選, 當傳遞output_attentions=True或config.output_attentions=True時返回) —torch.FloatTensor的元組 (每層一個),形狀為(batch_size, num_heads, patch_size, sequence_length)。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。
DeiTForImageClassification 的 forward 方法,重寫了 __call__ 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理前處理和後處理步驟,而後者會靜默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, DeiTForImageClassification
>>> import torch
>>> from PIL import Image
>>> import requests
>>> torch.manual_seed(3)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> # note: we are loading a DeiTForImageClassificationWithTeacher from the hub here,
>>> # so the head will be randomly initialized, hence the predictions will be random
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = DeiTForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = logits.argmax(-1).item()
>>> print("Predicted class:", model.config.id2label[predicted_class_idx])
Predicted class: Polaroid camera, Polaroid Land cameraDeiTForImageClassificationWithTeacher
class transformers.DeiTForImageClassificationWithTeacher
< 原始碼 >( config: DeiTConfig )
引數
- config (DeiTConfig) — 包含模型所有引數的模型配置類。使用配置檔案進行初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
DeiT Transformer 模型,頂部帶有影像分類頭 (一個線上性層上方的 [CLS] 標記的最終隱藏狀態,另一個線上性層上方的蒸餾標記的最終隱藏狀態),例如用於 ImageNet。
.. 警告:
此模型僅支援推理。尚不支援使用蒸餾(即帶教師模型)進行微調。
該模型繼承自 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 interpolate_pos_encoding: bool = False ) → transformers.models.deit.modeling_deit.DeiTForImageClassificationWithTeacherOutput 或 tuple(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 而不是普通的元組。 - interpolate_pos_encoding (
bool, 預設為False) — 是否對預訓練的位置編碼進行插值。
返回
transformers.models.deit.modeling_deit.DeiTForImageClassificationWithTeacherOutput 或 tuple(torch.FloatTensor)
一個 transformers.models.deit.modeling_deit.DeiTForImageClassificationWithTeacherOutput 或一個 torch.FloatTensor 的元組 (如果傳遞了 return_dict=False 或 config.return_dict=False),它包含根據配置 (DeiTConfig) 和輸入而定的各種元素。
-
logits (
torch.FloatTensor,形狀為(batch_size, config.num_labels)) — 作為 cls_logits 和 distillation 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)。模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。
-
attentions (
tuple[torch.FloatTensor], 可選, 當傳遞output_attentions=True或config.output_attentions=True時返回) —torch.FloatTensor的元組 (每層一個),形狀為(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。
DeiTForImageClassificationWithTeacher 的 forward 方法,重寫了 __call__ 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理前處理和後處理步驟,而後者會靜默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, DeiTForImageClassificationWithTeacher
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-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])
...TFDeiTModel
class transformers.TFDeiTModel
< 原始碼 >( config: DeiTConfig add_pooling_layer: bool = True use_mask_token: bool = False **kwargs )
引數
- config (DeiTConfig) — 包含模型所有引數的模型配置類。使用配置檔案進行初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
基礎的 DeiT Transformer 模型,輸出原始隱藏狀態,頂部沒有任何特定的頭。此模型是一個 TensorFlow keras.layers.Layer。像常規 TensorFlow 模組一樣使用它,並參考 TensorFlow 文件瞭解所有與通用用法和行為相關的事項。
呼叫
< 原始碼 >( pixel_values: tf.Tensor | None = None bool_masked_pos: tf.Tensor | None = None head_mask: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None interpolate_pos_encoding: bool = False training: bool = False ) → transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
引數
- pixel_values (
tf.Tensor,形狀為(batch_size, num_channels, height, width)) — 畫素值。畫素值可以使用 AutoImageProcessor 獲取。有關詳細資訊,請參閱 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor,形狀為(num_heads,)或(num_layers, num_heads), 可選) — 用於使自注意力模組的選定頭無效的掩碼。掩碼值在[0, 1]中選擇:- 1 表示頭未被掩碼,
- 0 表示頭被掩碼。
- output_attentions (
bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的attentions。 - output_hidden_states (
bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的hidden_states。 - interpolate_pos_encoding (
bool, 可選, 預設為False) — 是否對預訓練的位置編碼進行插值。 - return_dict (
bool, 可選) — 是否返回一個 ModelOutput 而不是普通的元組。
返回
transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
一個 transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或一個 tf.Tensor 的元組 (如果傳遞了 return_dict=False 或 config.return_dict=False),它包含根據配置 (DeiTConfig) 和輸入而定的各種元素。
-
last_hidden_state (
tf.Tensorof shape(batch_size, sequence_length, hidden_size)) — 模型最後一層輸出的隱藏狀態序列。 -
pooler_output (
tf.Tensor,形狀為(batch_size, hidden_size)) — 序列第一個標記(分類標記)的最後一層隱藏狀態,經過線性層和 Tanh 啟用函式進一步處理後的結果。線性層的權重是在預訓練期間從下一句預測(分類)目標中訓練得到的。此輸出通常不是輸入語義內容的良好摘要,通常最好對整個輸入序列的隱藏狀態進行平均或池化。
-
hidden_states (
tuple(tf.Tensor), 可選, 當傳遞output_hidden_states=True或config.output_hidden_states=True時返回) —tf.Tensor的元組 (一個用於嵌入層的輸出 + 每層一個輸出),形狀為(batch_size, sequence_length, hidden_size)。模型在每個層輸出的隱藏狀態加上初始嵌入輸出。
-
attentions (
tuple(tf.Tensor), 可選, 當傳遞output_attentions=True或config.output_attentions=True時返回) —tf.Tensor的元組 (每層一個),形狀為(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。
TFDeiTModel 的 forward 方法,重寫了 __call__ 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理前處理和後處理步驟,而後者會靜默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, TFDeiTModel
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = TFDeiTModel.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> inputs = image_processor(image, return_tensors="tf")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 198, 768]TFDeiTForMaskedImageModeling
class transformers.TFDeiTForMaskedImageModeling
< 原始碼 >( config: DeiTConfig )
引數
- config (DeiTConfig) — 包含模型所有引數的模型配置類。使用配置檔案進行初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
DeiT 模型,頂部帶有一個解碼器用於掩碼影像建模,如 SimMIM 中所提出的。此模型是一個 TensorFlow keras.layers.Layer。像常規 TensorFlow 模組一樣使用它,並參考 TensorFlow 文件瞭解所有與通用用法和行為相關的事項。
呼叫
< 原始碼 >( pixel_values: tf.Tensor | None = None bool_masked_pos: tf.Tensor | None = None head_mask: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None interpolate_pos_encoding: bool = False training: bool = False ) → transformers.modeling_tf_outputs.TFMaskedImageModelingOutput 或 tuple(tf.Tensor)
引數
- pixel_values (
tf.Tensor,形狀為(batch_size, num_channels, height, width)) — 畫素值。畫素值可以透過 AutoImageProcessor 獲取。詳見 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor,形狀為(num_heads,)或(num_layers, num_heads),可選) — 用於使自注意力模組中選定的頭無效的掩碼。掩碼值選自[0, 1]:- 1 表示頭未被遮蔽,
- 0 表示頭被遮蔽。
- output_attentions (
bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 `attentions`。 - output_hidden_states (
bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 `hidden_states`。 - interpolate_pos_encoding (
bool, 可選, 預設為False) — 是否對預訓練的位置編碼進行插值。 - return_dict (
bool, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。 - bool_masked_pos (
tf.Tensor,型別為 bool,形狀為(batch_size, num_patches)) — 布林型別的掩碼位置。指示哪些影像塊被掩碼 (1),哪些沒有 (0)。
返回
transformers.modeling_tf_outputs.TFMaskedImageModelingOutput 或 tuple(tf.Tensor)
一個 transformers.modeling_tf_outputs.TFMaskedImageModelingOutput 或一個 tf.Tensor 元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),包含各種元素,具體取決於配置(DeiTConfig)和輸入。
- loss (
tf.Tensor,形狀為(1,),可選,在提供bool_masked_pos時返回) — 重建損失。 - reconstruction (
tf.Tensor,形狀為(batch_size, num_channels, height, width)) — 重建/完成的影像。 - hidden_states (
tuple(tf.Tensor),可選,當傳遞output_hidden_states=True或當 config.output_hidden_states=True):tf.Tensor的元組(如果模型有嵌入層,則一個是嵌入層的輸出,另外每個階段的輸出各一個),形狀為(batch_size, sequence_length, hidden_size)。模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。- attentions (
tuple(tf.Tensor),可選,當傳遞output_attentions=True或當 config.output_attentions=True):tf.Tensor的元組(每層一個),形狀為(batch_size, num_heads, patch_size, sequence_length)。在注意力 softmax 之後的注意力權重,用於計算自注意力頭中的加權平均值。
TFDeiTForMaskedImageModeling 的前向方法,重寫了 `__call__` 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理前處理和後處理步驟,而後者會靜默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, TFDeiTForMaskedImageModeling
>>> import tensorflow as tf
>>> 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("facebook/deit-base-distilled-patch16-224")
>>> model = TFDeiTForMaskedImageModeling.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="tf").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = tf.cast(tf.random.uniform((1, num_patches), minval=0, maxval=2, dtype=tf.int32), tf.bool)
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
>>> list(reconstructed_pixel_values.shape)
[1, 3, 224, 224]TFDeiTForImageClassification
class transformers.TFDeiTForImageClassification
< 原始碼 >( config: DeiTConfig )
引數
- config (DeiTConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
DeiT Transformer 模型,頂部帶有一個影像分類頭 (在 [CLS] 標記的最終隱藏狀態上加一個線性層),例如用於 ImageNet。
這個模型是一個 TensorFlow keras.layers.Layer。像使用常規 TensorFlow 模組一樣使用它,並參考 TensorFlow 文件瞭解所有與常規用法和行為相關的事項。
呼叫
< 原始碼 >( pixel_values: tf.Tensor | None = None head_mask: tf.Tensor | None = None labels: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None interpolate_pos_encoding: bool = False training: bool = False ) → transformers.modeling_tf_outputs.TFImageClassifierOutput 或 tuple(tf.Tensor)
引數
- pixel_values (
tf.Tensor,形狀為(batch_size, num_channels, height, width)) — 畫素值。畫素值可以透過 AutoImageProcessor 獲取。詳見 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor,形狀為(num_heads,)或(num_layers, num_heads),可選) — 用於使自注意力模組中選定的頭無效的掩碼。掩碼值選自[0, 1]:- 1 表示頭未被遮蔽,
- 0 表示頭被遮蔽。
- output_attentions (
bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 `attentions`。 - output_hidden_states (
bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 `hidden_states`。 - interpolate_pos_encoding (
bool, 可選, 預設為False) — 是否對預訓練的位置編碼進行插值。 - return_dict (
bool, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。 - labels (
tf.Tensor,形狀為(batch_size,),可選) — 用於計算影像分類/迴歸損失的標籤。索引應在[0, ..., config.num_labels - 1]範圍內。如果config.num_labels == 1,則計算迴歸損失(均方損失),如果config.num_labels > 1,則計算分類損失(交叉熵)。
返回
transformers.modeling_tf_outputs.TFImageClassifierOutput 或 tuple(tf.Tensor)
一個 transformers.modeling_tf_outputs.TFImageClassifierOutput 或一個 tf.Tensor 元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),包含各種元素,具體取決於配置(DeiTConfig)和輸入。
-
loss (形狀為
(1,)的tf.Tensor,可選,當提供labels時返回) — 分類(如果 config.num_labels==1,則為迴歸)損失。 -
logits (
tf.Tensor,形狀為(batch_size, config.num_labels)) — 分類(或迴歸,如果 config.num_labels==1)分數(SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor),可選,當傳遞output_hidden_states=True或當config.output_hidden_states=True時返回) —tf.Tensor的元組(如果模型有嵌入層,則一個是嵌入層的輸出,另外每個階段的輸出各一個),形狀為(batch_size, sequence_length, hidden_size)。模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。 -
attentions (
tuple(tf.Tensor),可選,當傳遞output_attentions=True或當config.output_attentions=True時返回) —tf.Tensor的元組(每層一個),形狀為(batch_size, num_heads, patch_size, sequence_length)。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。
TFDeiTForImageClassification 的前向方法,重寫了 `__call__` 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理前處理和後處理步驟,而後者會靜默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, TFDeiTForImageClassification
>>> import tensorflow as tf
>>> from PIL import Image
>>> import requests
>>> keras.utils.set_random_seed(3)
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> # note: we are loading a TFDeiTForImageClassificationWithTeacher from the hub here,
>>> # so the head will be randomly initialized, hence the predictions will be random
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = TFDeiTForImageClassification.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> inputs = image_processor(images=image, return_tensors="tf")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = tf.math.argmax(logits, axis=-1)[0]
>>> print("Predicted class:", model.config.id2label[int(predicted_class_idx)])
Predicted class: little blue heron, Egretta caeruleaTFDeiTForImageClassificationWithTeacher
class transformers.TFDeiTForImageClassificationWithTeacher
< 原始碼 >( config: DeiTConfig )
引數
- config (DeiTConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
DeiT Transformer 模型,頂部帶有影像分類頭 (一個線上性層上方的 [CLS] 標記的最終隱藏狀態,另一個線上性層上方的蒸餾標記的最終隱藏狀態),例如用於 ImageNet。
.. 警告:
此模型僅支援推理。尚不支援使用蒸餾(即帶教師模型)進行微調。
這個模型是一個 TensorFlow keras.layers.Layer。像使用常規 TensorFlow 模組一樣使用它,並參考 TensorFlow 文件瞭解所有與常規用法和行為相關的事項。
呼叫
< 原始碼 >( pixel_values: tf.Tensor | None = None head_mask: tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None interpolate_pos_encoding: bool = False training: bool = False ) → transformers.models.deit.modeling_tf_deit.TFDeiTForImageClassificationWithTeacherOutput 或 tuple(tf.Tensor)
引數
- pixel_values (
tf.Tensor,形狀為(batch_size, num_channels, height, width)) — 畫素值。畫素值可以透過 AutoImageProcessor 獲取。詳見 DeiTImageProcessor.call()。 - head_mask (
tf.Tensor,形狀為(num_heads,)或(num_layers, num_heads),可選) — 用於使自注意力模組中選定的頭無效的掩碼。掩碼值選自[0, 1]:- 1 表示頭未被遮蔽,
- 0 表示頭被遮蔽。
- output_attentions (
bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 `attentions`。 - output_hidden_states (
bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 `hidden_states`。 - interpolate_pos_encoding (
bool, 可選, 預設為False) — 是否對預訓練的位置編碼進行插值。 - return_dict (
bool, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。
返回
transformers.models.deit.modeling_tf_deit.TFDeiTForImageClassificationWithTeacherOutput 或 tuple(tf.Tensor)
一個 transformers.models.deit.modeling_tf_deit.TFDeiTForImageClassificationWithTeacherOutput 或一個 tf.Tensor 元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),包含各種元素,具體取決於配置(DeiTConfig)和輸入。
- logits (
tf.Tensor,形狀為(batch_size, config.num_labels)) — 作為 cls_logits 和 distillation logits 平均值的預測分數。 - cls_logits (
tf.Tensor,形狀為(batch_size, config.num_labels)) — 分類頭的預測分數(即類標記最終隱藏狀態之上的線性層)。 - distillation_logits (
tf.Tensor,形狀為(batch_size, config.num_labels)) — 蒸餾頭的預測分數(即蒸餾標記最終隱藏狀態之上的線性層)。 - hidden_states (
tuple(tf.Tensor),可選,當傳遞output_hidden_states=True或當config.output_hidden_states=True時返回) —tf.Tensor的元組(一個是嵌入層的輸出 + 另一個是每層的輸出),形狀為(batch_size, sequence_length, hidden_size)。模型在每層輸出的隱藏狀態以及初始嵌入輸出。 - attentions (
tuple(tf.Tensor),可選,當傳遞output_attentions=True或當config.output_attentions=True時返回) —tf.Tensor的元組(每層一個),形狀為(batch_size, num_heads, sequence_length, sequence_length)。在注意力 softmax 之後的注意力權重,用於計算自注意力頭中的加權平均值。
TFDeiTForImageClassificationWithTeacher 的前向方法,重寫了 `__call__` 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理前處理和後處理步驟,而後者會靜默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, TFDeiTForImageClassificationWithTeacher
>>> import tensorflow as tf
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image"))
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> model = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224")
>>> inputs = image_processor(image, return_tensors="tf")
>>> logits = model(**inputs).logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = int(tf.math.argmax(logits, axis=-1))
>>> print(model.config.id2label[predicted_label])
tabby, tabby cat