Transformers 文件
MobileViT
並獲得增強的文件體驗
開始使用
MobileViT
概述
MobileViT 模型由 Sachin Mehta 和 Mohammad Rastegari 在MobileViT: 輕量級、通用型、移動友好的視覺 Transformer中提出。MobileViT 引入了一個新層,用 Transformer 的全域性處理取代了卷積的區域性處理。
論文摘要如下:
輕量級卷積神經網路 (CNN) 是移動視覺任務的事實標準。它們的空間歸納偏置使其能夠以更少的引數學習不同視覺任務的表示。然而,這些網路是空間區域性的。為了學習全域性表示,基於自注意力的視覺 Transformer (ViT) 被採用。與 CNN 不同,ViT 是重量級的。在本文中,我們提出了以下問題:是否有可能結合 CNN 和 ViT 的優點,為移動視覺任務構建一個輕量級、低延遲的網路?為此,我們引入了 MobileViT,一個用於移動裝置的輕量級通用視覺 Transformer。MobileViT 為 Transformer 的全域性資訊處理提供了一個不同的視角,即 Transformer 即卷積。我們的結果表明,MobileViT 在不同任務和資料集上顯著優於基於 CNN 和 ViT 的網路。在 ImageNet-1k 資料集上,MobileViT 以約 600 萬個引數實現了 78.4% 的 top-1 準確率,比 MobileNetv3(基於 CNN)和 DeIT(基於 ViT)在相似引數數量下分別高出 3.2% 和 6.2%。在 MS-COCO 目標檢測任務上,MobileViT 在相似引數數量下比 MobileNetv3 高出 5.7%。
此模型由matthijs貢獻。該模型的 TensorFlow 版本由sayakpaul貢獻。原始程式碼和權重可在此處找到。
使用技巧
MobileViT 更像一個 CNN 而不是 Transformer 模型。它不適用於序列資料,而是批處理影像。與 ViT 不同,它沒有嵌入。主幹模型輸出一個特徵圖。您可以參考本教程進行輕量級介紹。
可以使用 MobileViTImageProcessor 來準備影像供模型使用。請注意,如果您自行進行預處理,預訓練的檢查點期望影像採用 BGR 畫素順序(而非 RGB)。
可用的影像分類檢查點在 ImageNet-1k(也稱為 ILSVRC 2012,包含 130 萬張影像和 1,000 個類別)上進行了預訓練。
分割模型使用 DeepLabV3 頭。可用的語義分割檢查點在 PASCAL VOC 上進行了預訓練。
顧名思義,MobileViT 旨在行動電話上實現高效能和高效率。MobileViT 模型的 TensorFlow 版本與 TensorFlow Lite 完全相容。
您可以使用以下程式碼將 MobileViT 檢查點(無論是影像分類還是語義分割)轉換為生成 TensorFlow Lite 模型
from transformers import TFMobileViTForImageClassification
import tensorflow as tf
model_ckpt = "apple/mobilevit-xx-small"
model = TFMobileViTForImageClassification.from_pretrained(model_ckpt)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [
tf.lite.OpsSet.TFLITE_BUILTINS,
tf.lite.OpsSet.SELECT_TF_OPS,
]
tflite_model = converter.convert()
tflite_filename = model_ckpt.split("/")[-1] + ".tflite"
with open(tflite_filename, "wb") as f:
f.write(tflite_model)
生成的模型只有 **大約 1MB**,非常適合資源和網路頻寬受限的移動應用。
資源
一份官方 Hugging Face 和社群(用🌎表示)資源列表,幫助您開始使用 MobileViT。
- MobileViTForImageClassification 由此示例指令碼和notebook支援。
- 另請參閱:影像分類任務指南
語義分割
如果您有興趣在此處提交資源,請隨時開啟 Pull Request,我們將對其進行審查!該資源最好能展示一些新內容,而不是重複現有資源。
MobileViTConfig
class transformers.MobileViTConfig
< source >( num_channels = 3 image_size = 256 patch_size = 2 hidden_sizes = [144, 192, 240] neck_hidden_sizes = [16, 32, 64, 96, 128, 160, 640] num_attention_heads = 4 mlp_ratio = 2.0 expand_ratio = 4.0 hidden_act = 'silu' conv_kernel_size = 3 output_stride = 32 hidden_dropout_prob = 0.1 attention_probs_dropout_prob = 0.0 classifier_dropout_prob = 0.1 initializer_range = 0.02 layer_norm_eps = 1e-05 qkv_bias = True aspp_out_channels = 256 atrous_rates = [6, 12, 18] aspp_dropout_prob = 0.1 semantic_loss_ignore_index = 255 **kwargs )
引數
- num_channels (
int
, 可選, 預設為 3) — 輸入通道數。 - image_size (
int
, 可選, 預設為 256) — 每張影像的大小(解析度)。 - patch_size (
int
, 可選, 預設為 2) — 每個 patch 的大小(解析度)。 - hidden_sizes (
list[int]
, 可選, 預設為[144, 192, 240]
) — Transformer 編碼器每個階段的維度(隱藏層大小)。 - neck_hidden_sizes (
list[int]
, 可選, 預設為[16, 32, 64, 96, 128, 160, 640]
) — 主幹特徵圖的通道數。 - num_attention_heads (
int
, 可選, 預設為 4) — Transformer 編碼器中每個注意力層的注意力頭數量。 - mlp_ratio (
float
, 可選, 預設為 2.0) — MLP 輸出通道數與輸入通道數的比率。 - expand_ratio (
float
, 可選, 預設為 4.0) — MobileNetv2 層的擴充套件因子。 - hidden_act (
str
或function
, 可選, 預設為"silu"
) — Transformer 編碼器和卷積層中的非線性啟用函式(函式或字串)。 - conv_kernel_size (
int
, 可選, 預設為 3) — MobileViT 層中卷積核的大小。 - output_stride (
int
, 可選, 預設為 32) — 輸出空間解析度與輸入影像解析度的比率。 - hidden_dropout_prob (
float
, 可選, 預設為 0.1) — Transformer 編碼器中所有全連線層的 dropout 機率。 - attention_probs_dropout_prob (
float
, 可選, 預設為 0.0) — 注意力機率的 dropout 比率。 - classifier_dropout_prob (
float
, 可選, 預設為 0.1) — 附加分類器的 dropout 比率。 - initializer_range (
float
, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的截斷正態分佈初始化器的標準差。 - layer_norm_eps (
float
, 可選, 預設為 1e-05) — 層歸一化層使用的 epsilon 值。 - qkv_bias (
bool
, 可選, 預設為True
) — 是否為查詢、鍵和值新增偏置。 - aspp_out_channels (
int
, 可選, 預設為 256) — 用於語義分割的 ASPP 層中使用的輸出通道數。 - atrous_rates (
list[int]
, 可選, 預設為[6, 12, 18]
) — 用於語義分割的 ASPP 層中使用的膨脹(atrous)因子。 - aspp_dropout_prob (
float
, 可選, 預設為 0.1) — 用於語義分割的 ASPP 層的 dropout 比率。 - semantic_loss_ignore_index (
int
, 可選, 預設為 255) — 語義分割模型的損失函式忽略的索引。
這是配置類,用於儲存 MobileViTModel 的配置。它用於根據指定引數例項化 MobileViT 模型,定義模型架構。使用預設值例項化配置將產生類似於 MobileViT apple/mobilevit-small 架構的配置。
配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。
示例
>>> from transformers import MobileViTConfig, MobileViTModel
>>> # Initializing a mobilevit-small style configuration
>>> configuration = MobileViTConfig()
>>> # Initializing a model from the mobilevit-small style configuration
>>> model = MobileViTModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
MobileViTFeatureExtractor
預處理一批影像和可選的分割圖。
重寫 Preprocessor
類的 __call__
方法,以便影像和分割圖都可以作為位置引數傳入。
post_process_semantic_segmentation
< source >( outputs target_sizes: typing.Optional[list[tuple]] = None ) → semantic_segmentation
引數
- outputs (MobileViTForSemanticSegmentation) — 模型的原始輸出。
- target_sizes (
list[Tuple]
, 長度為batch_size
, 可選) — 對應於每個預測的請求最終尺寸(高度,寬度)的元組列表。如果未設定,則預測不會被調整大小。
返回
語義分割
list[torch.Tensor]
,長度為 batch_size
,其中每個專案是一個形狀為 (高度, 寬度) 的語義分割圖,對應於 target_sizes 條目(如果指定了 target_sizes
)。每個 torch.Tensor
的每個條目對應於一個語義類別 ID。
將 MobileViTForSemanticSegmentation 的輸出轉換為語義分割圖。僅支援 PyTorch。
MobileViTImageProcessor
class transformers.MobileViTImageProcessor
< source >( 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_center_crop: bool = True crop_size: typing.Optional[dict[str, int]] = None do_flip_channel_order: bool = True **kwargs )
引數
- do_resize (
bool
, optional, defaults toTrue
) — 是否將影像的(高度,寬度)尺寸調整為指定的size
。可以透過preprocess
方法中的do_resize
引數覆蓋。 - size (
dict[str, int]
optional, defaults to{"shortest_edge" -- 224}
): 控制調整大小後的輸出影像尺寸。可以透過preprocess
方法中的size
引數覆蓋。 - resample (
PILImageResampling
, optional, defaults toResampling.BILINEAR
) — 定義影像調整大小後使用的重取樣過濾器。可以透過preprocess
方法中的resample
引數覆蓋。 - do_rescale (
bool
, optional, defaults toTrue
) — 是否按指定的比例因子rescale_factor
重新縮放影像。可以透過preprocess
方法中的do_rescale
引數覆蓋。 - rescale_factor (
int
orfloat
, optional, defaults to1/255
) — 重新縮放影像時使用的比例因子。可以透過preprocess
方法中的rescale_factor
引數覆蓋。 - do_center_crop (
bool
, optional, defaults toTrue
) — 是否在中心裁剪輸入。如果輸入尺寸沿任何邊緣小於crop_size
,影像將用 0 填充,然後中心裁剪。可以透過preprocess
方法中的do_center_crop
引數覆蓋。 - crop_size (
dict[str, int]
, optional, defaults to{"height" -- 256, "width": 256}
): 應用中心裁剪時所需的輸出尺寸(size["height"], size["width"])
。可以透過preprocess
方法中的crop_size
引數覆蓋。 - do_flip_channel_order (
bool
, optional, defaults toTrue
) — 是否將顏色通道從 RGB 翻轉為 BGR。可以透過preprocess
方法中的do_flip_channel_order
引數覆蓋。
構造一個 MobileViT 影像處理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None 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_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_flip_channel_order: typing.Optional[bool] = 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
。 - segmentation_maps (
ImageInput
, optional) — 要預處理的分割圖。 - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否調整影像大小。 - size (
dict[str, int]
, optional, defaults toself.size
) — 調整大小後的影像尺寸。 - resample (
int
, optional, defaults toself.resample
) — 調整影像大小時使用的重取樣過濾器。可以是列舉PILImageResampling
之一,僅當do_resize
設定為True
時才有效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否按比例因子重新縮放影像。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
設定為True
,則按此比例因子重新縮放影像。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否中心裁剪影像。 - crop_size (
dict[str, int]
, optional, defaults toself.crop_size
) — 如果do_center_crop
設定為True
,則中心裁剪的尺寸。 - do_flip_channel_order (
bool
, optional, defaults toself.do_flip_channel_order
) — 是否翻轉影像的通道順序。 - return_tensors (
str
orTensorType
, optional) — 要返回的張量型別。可以是以下之一:- 未設定:返回
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 (
ChannelDimension
orstr
, optional, defaults toChannelDimension.FIRST
) — 輸出影像的通道維度格式。可以是以下之一:ChannelDimension.FIRST
:影像格式為(通道數,高度,寬度)。ChannelDimension.LAST
:影像格式為(高度,寬度,通道數)。
- input_data_format (
ChannelDimension
orstr
, optional) — 輸入影像的通道維度格式。如果未設定,將從輸入影像推斷通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為(通道數,高度,寬度)。"channels_last"
或ChannelDimension.LAST
:影像格式為(高度,寬度,通道數)。"none"
或ChannelDimension.NONE
:影像格式為(高度,寬度)。
預處理一張或一批影像。
post_process_semantic_segmentation
< source >( outputs target_sizes: typing.Optional[list[tuple]] = None ) → semantic_segmentation
引數
- outputs (MobileViTForSemanticSegmentation) — 模型的原始輸出。
- target_sizes (
list[Tuple]
of lengthbatch_size
, optional) — 與每個預測所需的最終大小(高度,寬度)相對應的元組列表。如果未設定,則預測將不會調整大小。
返回
語義分割
list[torch.Tensor]
,長度為 batch_size
,其中每個專案是一個形狀為 (高度, 寬度) 的語義分割圖,對應於 target_sizes 條目(如果指定了 target_sizes
)。每個 torch.Tensor
的每個條目對應於一個語義類別 ID。
將 MobileViTForSemanticSegmentation 的輸出轉換為語義分割圖。僅支援 PyTorch。
MobileViTModel
class transformers.MobileViTModel
< source >( config: MobileViTConfig expand_output: bool = True )
引數
- config (MobileViTConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法載入模型權重。
- expand_output (
bool
, optional, defaults toTrue
) — 是否使用 1x1 卷積擴充套件模型輸出。如果為True
,模型將應用額外的 1x1 卷積以將輸出通道從config.neck_hidden_sizes[5]
擴充套件到config.neck_hidden_sizes[6]
。
Mobilevit 裸模型,輸出原始隱藏狀態,頂部沒有特定頭部。
此模型繼承自 PreTrainedModel。有關庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等),請檢視超類文件。
此模型也是 PyTorch torch.nn.Module 的子類。請將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件中所有與通用用法和行為相關的內容。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 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}
處理影像)。 - output_hidden_states (
bool
, optional) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參見返回張量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是純元組。
返回
transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 tuple(torch.FloatTensor)
一個 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或一個 torch.FloatTensor
元組(如果傳遞 return_dict=False
或當 config.return_dict=False
時),其中包含根據配置 (MobileViTConfig) 和輸入的不同元素。
-
last_hidden_state (
torch.FloatTensor
, 形狀為(batch_size, num_channels, height, width)
) — 模型最後一層輸出的隱藏狀態序列。 -
pooler_output (
torch.FloatTensor
, 形狀為(batch_size, hidden_size)
) — 經過空間維度池化操作後的最後一層隱藏狀態。 -
hidden_states (
tuple(torch.FloatTensor)
, optional, 當傳遞output_hidden_states=True
或當config.output_hidden_states=True
時返回) —torch.FloatTensor
元組(如果模型具有嵌入層,則為一個嵌入層輸出,加上每個層的一個輸出),形狀為(batch_size, num_channels, height, width)
。模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。
MobileViTModel 的 forward 方法,重寫了 __call__
特殊方法。
儘管前向傳遞的配方需要在此函式中定義,但在此之後應呼叫 Module
例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則會默默地忽略它們。
MobileViTForImageClassification
class transformers.MobileViTForImageClassification
< source >( config: MobileViTConfig )
引數
- config (MobileViTConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法載入模型權重。
帶有影像分類頭的 MobileViT 模型(池化特徵頂部的線性層),例如用於 ImageNet。
此模型繼承自 PreTrainedModel。有關庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等),請檢視超類文件。
此模型也是 PyTorch torch.nn.Module 的子類。請將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件中所有與通用用法和行為相關的內容。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None labels: typing.Optional[torch.Tensor] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 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}
處理影像)。 - output_hidden_states (
bool
, optional) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參見返回張量下的hidden_states
。 - labels (
torch.LongTensor
, 形狀為(batch_size,)
, 可選) — 用於計算影像分類/迴歸損失的標籤。索引應在[0, ..., config.num_labels - 1]
範圍內。如果config.num_labels == 1
,則計算迴歸損失(均方損失)。如果config.num_labels > 1
,則計算分類損失(交叉熵)。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是純元組。
返回
transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
一個 transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或一個 torch.FloatTensor
元組(如果傳遞 return_dict=False
或當 config.return_dict=False
時),其中包含根據配置 (MobileViTConfig) 和輸入的不同元素。
- 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)
。模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。
MobileViTForImageClassification 的 forward 方法,重寫了 __call__
特殊方法。
儘管前向傳遞的配方需要在此函式中定義,但在此之後應呼叫 Module
例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則會默默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, MobileViTForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevit-small")
>>> model = MobileViTForImageClassification.from_pretrained("apple/mobilevit-small")
>>> 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])
...
MobileViTForSemanticSegmentation
class transformers.MobileViTForSemanticSegmentation
< source >( config: MobileViTConfig )
引數
- config (MobileViTConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請查閱 from_pretrained() 方法來載入模型權重。
MobileViT 模型,頂部帶有一個語義分割頭,例如用於 Pascal VOC。
此模型繼承自 PreTrainedModel。有關庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等),請檢視超類文件。
此模型也是 PyTorch torch.nn.Module 的子類。請將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件中所有與通用用法和行為相關的內容。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.SemanticSegmenterOutput 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, height, width)
的torch.LongTensor
,可選) — 用於計算損失的真實語義分割圖。索引應在[0, ..., config.num_labels - 1]
範圍內。如果config.num_labels > 1
,則計算分類損失(交叉熵)。 - output_hidden_states (
bool
,可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量中的hidden_states
。 - return_dict (
bool
,可選) — 是否返回 ModelOutput 而不是普通的元組。
返回
transformers.modeling_outputs.SemanticSegmenterOutput 或 tuple(torch.FloatTensor)
一個 transformers.modeling_outputs.SemanticSegmenterOutput 或一個 torch.FloatTensor
元組(如果傳入 return_dict=False
或當 config.return_dict=False
時),包含根據配置 (MobileViTConfig) 和輸入的不同元素。
-
loss (形狀為
(1,)
的torch.FloatTensor
,可選,當提供labels
時返回) — 分類損失(如果 config.num_labels==1,則為迴歸損失)。 -
logits (形狀為
(batch_size, config.num_labels, logits_height, logits_width)
的torch.FloatTensor
) — 每個畫素的分類分數。返回的 logits 不一定與作為輸入傳入的
pixel_values
具有相同的大小。這是為了避免兩次插值並在使用者需要將 logits 調整到原始影像大小時損失一些質量。您應始終檢查 logits 的形狀並根據需要進行調整。 -
hidden_states (
tuple(torch.FloatTensor)
,可選,當傳入output_hidden_states=True
或當config.output_hidden_states=True
時返回) —torch.FloatTensor
的元組(一個用於嵌入層的輸出(如果模型有嵌入層),+一個用於每一層的輸出),形狀為(batch_size, patch_size, hidden_size)
。模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。
-
attentions (
tuple(torch.FloatTensor)
,可選,當傳入output_attentions=True
或當config.output_attentions=True
時返回) —torch.FloatTensor
的元組(每一層一個),形狀為(batch_size, num_heads, patch_size, sequence_length)
。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。
MobileViTForSemanticSegmentation forward 方法,覆蓋了 __call__
特殊方法。
儘管前向傳遞的配方需要在此函式中定義,但在此之後應呼叫 Module
例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則會默默地忽略它們。
示例
>>> import requests
>>> import torch
>>> from PIL import Image
>>> from transformers import AutoImageProcessor, MobileViTForSemanticSegmentation
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-small")
>>> model = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-small")
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # logits are of shape (batch_size, num_labels, height, width)
>>> logits = outputs.logits
TFMobileViTModel
class transformers.TFMobileViTModel
< source >( config: MobileViTConfig expand_output: bool = True *inputs **kwargs )
引數
- config (MobileViTConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請查閱 from_pretrained() 方法來載入模型權重。
不帶任何特定頭部的裸 MobileViT 模型,輸出原始隱藏狀態。此模型繼承自 TFPreTrainedModel。查閱父類文件以獲取庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 keras.Model 子類。將其作為常規 TF 2.0 Keras 模型使用,並參考 TF 2.0 文件瞭解所有與通用使用和行為相關的事項。
transformers
中的 TensorFlow 模型和層接受兩種輸入格式
- 所有輸入作為關鍵字引數(如 PyTorch 模型),或
- 所有輸入作為第一個位置引數中的列表、元組或字典。
支援第二種格式的原因是 Keras 方法在向模型和層傳遞輸入時更傾向於這種格式。由於此支援,在使用 model.fit()
等方法時,一切都應該“正常工作”——只需以 model.fit()
支援的任何格式傳遞您的輸入和標籤即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二種格式,例如在使用 Keras Functional
API 建立自己的層或模型時,可以使用以下三種方法將所有輸入張量收集到第一個位置引數中:
- 一個只包含
pixel_values
的獨立張量:model(pixel_values)
- 一個長度可變的列表,其中包含一個或多個輸入張量,按文件字串中給定的順序排列:
model([pixel_values, attention_mask])
或model([pixel_values, attention_mask, token_type_ids])
- 一個字典,包含一個或多個與文件字串中給定的輸入名稱相關聯的輸入張量:
model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})
請注意,當透過 子類化 建立模型和層時,您無需擔心這些,因為您可以像傳遞給任何其他 Python 函式一樣傳遞輸入!
呼叫
< source >( pixel_values: tf.Tensor | None = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) → transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling or tuple(tf.Tensor)
引數
- pixel_values (
np.ndarray
,tf.Tensor
,list[tf.Tensor]
,dict[str, tf.Tensor]
或dict[str, np.ndarray]
,且每個示例的形狀必須為(batch_size, num_channels, height, width)
) — 畫素值。畫素值可以使用 AutoImageProcessor 獲取。有關詳細資訊,請參閱 MobileViTImageProcessor.call()。 - output_hidden_states (
bool
,可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量中的hidden_states
。此引數只能在 eager 模式下使用,在圖模式下將使用配置中的值。 - return_dict (
bool
,可選) — 是否返回 ModelOutput 而不是普通的元組。此引數可在 eager 模式下使用,在圖模式下該值將始終設定為 True。
返回
transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
一個 transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或一個 tf.Tensor
元組(如果傳入 return_dict=False
或當 config.return_dict=False
時),包含根據配置 (MobileViTConfig) 和輸入的不同元素。
-
last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
) — 模型最後一層輸出的隱藏狀態序列。 -
pooler_output (形狀為
(batch_size, hidden_size)
的tf.Tensor
) — 序列中第一個標記(分類標記)的最後一層隱藏狀態,透過線性層和 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 後的注意力權重,用於計算自注意力頭中的加權平均值。
TFMobileViTModel forward 方法,覆蓋了 __call__
特殊方法。
儘管前向傳遞的配方需要在此函式中定義,但在此之後應呼叫 Module
例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則會默默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, TFMobileViTModel
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevit-small")
>>> model = TFMobileViTModel.from_pretrained("apple/mobilevit-small")
>>> inputs = image_processor(image, return_tensors="tf")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 640, 8, 8]
TFMobileViTForImageClassification
class transformers.TFMobileViTForImageClassification
< source >( config: MobileViTConfig *inputs **kwargs )
引數
- config (MobileViTConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請查閱 from_pretrained() 方法來載入模型權重。
帶有影像分類頭的 MobileViT 模型(池化特徵頂部的線性層),例如用於 ImageNet。
此模型繼承自 TFPreTrainedModel。查閱父類文件以獲取庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 keras.Model 子類。將其作為常規 TF 2.0 Keras 模型使用,並參考 TF 2.0 文件瞭解所有與通用使用和行為相關的事項。
transformers
中的 TensorFlow 模型和層接受兩種輸入格式
- 所有輸入作為關鍵字引數(如 PyTorch 模型),或
- 所有輸入作為第一個位置引數中的列表、元組或字典。
支援第二種格式的原因是 Keras 方法在向模型和層傳遞輸入時更傾向於這種格式。由於此支援,在使用 model.fit()
等方法時,一切都應該“正常工作”——只需以 model.fit()
支援的任何格式傳遞您的輸入和標籤即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二種格式,例如在使用 Keras Functional
API 建立自己的層或模型時,可以使用以下三種方法將所有輸入張量收集到第一個位置引數中:
- 一個只包含
pixel_values
的獨立張量:model(pixel_values)
- 一個長度可變的列表,其中包含一個或多個輸入張量,按文件字串中給定的順序排列:
model([pixel_values, attention_mask])
或model([pixel_values, attention_mask, token_type_ids])
- 一個字典,包含一個或多個與文件字串中給定的輸入名稱相關聯的輸入張量:
model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})
請注意,當透過 子類化 建立模型和層時,您無需擔心這些,因為您可以像傳遞給任何其他 Python 函式一樣傳遞輸入!
呼叫
< source >( pixel_values: tf.Tensor | None = None output_hidden_states: Optional[bool] = None labels: tf.Tensor | None = None return_dict: Optional[bool] = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFImageClassifierOutputWithNoAttention
或 tuple(tf.Tensor)
引數
- pixel_values (
np.ndarray
,tf.Tensor
,list[tf.Tensor]
,dict[str, tf.Tensor]
或dict[str, np.ndarray]
,且每個示例的形狀必須為(batch_size, num_channels, height, width)
) — 畫素值。畫素值可以使用 AutoImageProcessor 獲取。有關詳細資訊,請參閱 MobileViTImageProcessor.call()。 - output_hidden_states (
bool
,可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量中的hidden_states
。此引數只能在 eager 模式下使用,在圖模式下將使用配置中的值。 - return_dict (
bool
,可選) — 是否返回 ModelOutput 而不是普通的元組。此引數可在 eager 模式下使用,在圖模式下該值將始終設定為 True。 - labels (形狀為
(batch_size,)
的tf.Tensor
,可選) — 用於計算影像分類/迴歸損失的標籤。索引應在[0, ..., config.num_labels - 1]
範圍內。如果config.num_labels == 1
,則計算迴歸損失(均方損失)。如果config.num_labels > 1
,則計算分類損失(交叉熵)。
返回
transformers.modeling_tf_outputs.TFImageClassifierOutputWithNoAttention
或 tuple(tf.Tensor)
一個 transformers.modeling_tf_outputs.TFImageClassifierOutputWithNoAttention
或一個 tf.Tensor
元組(如果傳入 return_dict=False
或當 config.return_dict=False
時),包含根據配置 (MobileViTConfig) 和輸入的不同元素。
- 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, num_channels, height, width)
。模型在每一階段輸出的隱藏狀態(也稱為特徵圖)。
TFMobileViTForImageClassification forward 方法,覆蓋了 __call__
特殊方法。
儘管前向傳遞的配方需要在此函式中定義,但在此之後應呼叫 Module
例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則會默默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, TFMobileViTForImageClassification
>>> 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("apple/mobilevit-small")
>>> model = TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-small")
>>> 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
TFMobileViTForSemanticSegmentation
class transformers.TFMobileViTForSemanticSegmentation
< source >( config: MobileViTConfig **kwargs )
引數
- config (MobileViTConfig) — 模型配置類,包含模型的所有引數。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請查閱 from_pretrained() 方法來載入模型權重。
MobileViT 模型,頂部帶有一個語義分割頭,例如用於 Pascal VOC。
此模型繼承自 TFPreTrainedModel。查閱父類文件以獲取庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 keras.Model 子類。將其作為常規 TF 2.0 Keras 模型使用,並參考 TF 2.0 文件瞭解所有與通用使用和行為相關的事項。
transformers
中的 TensorFlow 模型和層接受兩種輸入格式
- 所有輸入作為關鍵字引數(如 PyTorch 模型),或
- 所有輸入作為第一個位置引數中的列表、元組或字典。
支援第二種格式的原因是 Keras 方法在向模型和層傳遞輸入時更傾向於這種格式。由於此支援,在使用 model.fit()
等方法時,一切都應該“正常工作”——只需以 model.fit()
支援的任何格式傳遞您的輸入和標籤即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二種格式,例如在使用 Keras Functional
API 建立自己的層或模型時,可以使用以下三種方法將所有輸入張量收集到第一個位置引數中:
- 一個只包含
pixel_values
的獨立張量:model(pixel_values)
- 一個長度可變的列表,其中包含一個或多個輸入張量,按文件字串中給定的順序排列:
model([pixel_values, attention_mask])
或model([pixel_values, attention_mask, token_type_ids])
- 一個字典,包含一個或多個與文件字串中給定的輸入名稱相關聯的輸入張量:
model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})
請注意,當透過 子類化 建立模型和層時,您無需擔心這些,因為您可以像傳遞給任何其他 Python 函式一樣傳遞輸入!
呼叫
< source >( pixel_values: tf.Tensor | None = None labels: tf.Tensor | None = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) → transformers.modeling_tf_outputs.TFSemanticSegmenterOutputWithNoAttention
或 tuple(tf.Tensor)
引數
- pixel_values (
np.ndarray
,tf.Tensor
,list[tf.Tensor]
,dict[str, tf.Tensor]
或dict[str, np.ndarray]
,且每個示例的形狀必須為(batch_size, num_channels, height, width)
) — 畫素值。畫素值可以使用 AutoImageProcessor 獲取。有關詳細資訊,請參閱 MobileViTImageProcessor.call()。 - output_hidden_states (
bool
,可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量中的hidden_states
。此引數只能在 eager 模式下使用,在圖模式下將使用配置中的值。 - return_dict (
bool
,可選) — 是否返回 ModelOutput 而不是普通的元組。此引數可在 eager 模式下使用,在圖模式下該值將始終設定為 True。 - labels (形狀為
(batch_size, height, width)
的tf.Tensor
,可選) — 用於計算損失的真實語義分割圖。索引應在[0, ..., config.num_labels - 1]
範圍內。如果config.num_labels > 1
,則計算分類損失(交叉熵)。
返回
transformers.modeling_tf_outputs.TFSemanticSegmenterOutputWithNoAttention
或 tuple(tf.Tensor)
一個 transformers.modeling_tf_outputs.TFSemanticSegmenterOutputWithNoAttention
或一個 tf.Tensor
元組(如果傳入 return_dict=False
或當 config.return_dict=False
時),包含根據配置 (MobileViTConfig) 和輸入的不同元素。
-
loss (形狀為
(1,)
的tf.Tensor
,可選,當提供labels
時返回) — 分類(如果 config.num_labels==1,則為迴歸)損失。 -
logits (形狀為
(batch_size, config.num_labels, logits_height, logits_width)
的tf.Tensor
) — 每個畫素的分類分數。返回的 logits 不一定與作為輸入傳入的
pixel_values
具有相同的大小。這是為了避免兩次插值並在使用者需要將 logits 調整到原始影像大小時損失一些質量。您應始終檢查 logits 的形狀並根據需要進行調整。 -
hidden_states (
tuple(tf.Tensor)
,可選,當傳入output_hidden_states=True
或當config.output_hidden_states=True
時返回) —tf.Tensor
的元組(一個用於嵌入層的輸出(如果模型有嵌入層),+一個用於每一層的輸出),形狀為(batch_size, patch_size, hidden_size)
。模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。
TFMobileViTForSemanticSegmentation forward 方法,覆蓋了 __call__
特殊方法。
儘管前向傳遞的配方需要在此函式中定義,但在此之後應呼叫 Module
例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則會默默地忽略它們。
示例
>>> from transformers import AutoImageProcessor, TFMobileViTForSemanticSegmentation
>>> 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("apple/deeplabv3-mobilevit-small")
>>> model = TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-small")
>>> inputs = image_processor(images=image, return_tensors="tf")
>>> outputs = model(**inputs)
>>> # logits are of shape (batch_size, num_labels, height, width)
>>> logits = outputs.logits