MobileViT
概述
MobileViT 模型由 Sachin Mehta 和 Mohammad Rastegari 在论文MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision Transformer中提出。MobileViT 引入了一个新层,用 transformers 的全局处理取代卷积中的局部处理。
论文摘要如下:
轻量级卷积神经网络 (CNN) 是移动视觉任务的事实标准。它们在空间上的归纳偏置使它们能够以更少的参数学习不同视觉任务的表示。然而,这些网络在空间上是局部的。为了学习全局表示,已经采用了基于自注意力机制的视觉 Transformer (ViT)。与 CNN 不同,ViT 是重量级的。在本文中,我们提出以下问题:是否有可能结合 CNN 和 ViT 的优势,为移动视觉任务构建一个轻量级和低延迟的网络?为此,我们推出了 MobileViT,这是一款用于移动设备的轻量级通用视觉 transformer。MobileViT 为使用 transformers 进行全局信息处理提供了一种不同的视角,即 transformers 作为卷积。我们的结果表明,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 万张图像和 1000 个类别)。
分割模型使用 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
< 源代码 >( 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
, optional, 默认为 3) — 输入通道的数量。 - image_size (
int
, optional, 默认为 256) — 每张图像的大小(分辨率)。 - patch_size (
int
, optional, 默认为 2) — 每个 patch 的大小(分辨率)。 - hidden_sizes (
List[int]
, optional, 默认为[144, 192, 240]
) — 每个阶段 Transformer 编码器的维度(隐藏大小)。 - neck_hidden_sizes (
List[int]
, optional, 默认为[16, 32, 64, 96, 128, 160, 640]
) — 骨干网络特征图的通道数。 - num_attention_heads (
int
, optional, 默认为 4) — Transformer 编码器中每个注意力层的注意力头数。 - mlp_ratio (
float
, optional, 默认为 2.0) — MLP 输出中的通道数与输入中的通道数之比。 - expand_ratio (
float
, optional, 默认为 4.0) — MobileNetv2 层的扩展因子。 - hidden_act (
str
或function
, optional, 默认为"silu"
) — Transformer 编码器和卷积层中的非线性激活函数(函数或字符串)。 - conv_kernel_size (
int
, optional, 默认为 3) — MobileViT 层中卷积核的大小。 - output_stride (
int
, optional, 默认为 32) — 输出的空间分辨率与输入图像分辨率之比。 - hidden_dropout_prob (
float
, optional, 默认为 0.1) — Transformer 编码器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, optional, 默认为 0.0) — 注意力概率的 dropout 比率。 - classifier_dropout_prob (
float
, optional, 默认为 0.1) — 附加分类器的 dropout 比率。 - initializer_range (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, optional, defaults to 1e-05) — 层归一化层使用的 epsilon 值。 - qkv_bias (
bool
, optional, defaults toTrue
) — 是否向 queries, keys 和 values 添加偏置。 - aspp_out_channels (
int
, optional, defaults to 256) — 用于语义分割的 ASPP 层中使用的输出通道数。 - atrous_rates (
List[int]
, optional, defaults to[6, 12, 18]
) — 用于语义分割的 ASPP 层中使用的空洞率(atrous rate)因子列表。 - aspp_dropout_prob (
float
, optional, defaults to 0.1) — 用于语义分割的 ASPP 层的 dropout 比率。 - semantic_loss_ignore_index (
int
, optional, defaults to 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: List = None ) → semantic_segmentation
参数
- outputs (MobileViTForSemanticSegmentation) — 模型的原始输出。
- target_sizes (
List[Tuple]
of lengthbatch_size
, optional) — 对应于每个预测请求的最终尺寸(高度,宽度)的元组列表。如果未设置,则不会调整预测大小。
返回值
semantic_segmentation
List[torch.Tensor]
,长度为 batch_size
,其中每个项目是形状为 (height, width) 的语义分割图,对应于 target_sizes
条目(如果指定了 target_sizes
)。每个 torch.Tensor
的每个条目对应于一个语义类别 ID。
将 MobileViTForSemanticSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
MobileViTImageProcessor
class transformers.MobileViTImageProcessor
< source >( do_resize: bool = True size: Dict = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: Union = 0.00392156862745098 do_center_crop: bool = True crop_size: Dict = 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: Union segmentation_maps: Union = None do_resize: bool = None size: Dict = None resample: Resampling = None do_rescale: bool = None rescale_factor: float = None do_center_crop: bool = None crop_size: Dict = None do_flip_channel_order: bool = None return_tensors: Union = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None )
参数
- images (
ImageInput
) — 要预处理的图像。 接受像素值范围为 0 到 255 的单张或批量图像。 如果传入像素值在 0 到 1 之间的图像,请设置do_rescale=False
。 - segmentation_maps (
ImageInput
, optional) — 要预处理的分割图。(可选参数) - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小。(可选参数,默认为self.do_resize
) - size (
Dict[str, int]
, optional, defaults toself.size
) — 调整大小后图像的尺寸。(可选参数,默认为self.size
) - resample (
int
, optional, defaults toself.resample
) — 如果调整图像大小,则使用的重采样滤波器。 可以是枚举类型PILImageResampling
之一。 仅当do_resize
设置为True
时有效。(可选参数,默认为self.resample
) - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否通过重缩放因子来重缩放图像。(可选参数,默认为self.do_rescale
) - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则用于重缩放图像的重缩放因子。(可选参数,默认为self.rescale_factor
) - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。(可选参数,默认为self.do_center_crop
) - crop_size (
Dict[str, int]
, optional, defaults toself.crop_size
) — 如果do_center_crop
设置为True
,则中心裁剪的尺寸。(可选参数,默认为self.crop_size
) - do_flip_channel_order (
bool
, optional, defaults toself.do_flip_channel_order
) — 是否翻转图像的通道顺序。(可选参数,默认为self.do_flip_channel_order
) - return_tensors (
str
orTensorType
, optional) — 要返回的张量类型。 可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
:返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
:返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
:返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
:返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
orstr
, optional, defaults toChannelDimension.FIRST
) — 输出图像的通道维度格式。 可以是以下之一:ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。
ChannelDimension.FIRST
) - input_data_format (
ChannelDimension
orstr
, optional) — 输入图像的通道维度格式。 如果未设置,则通道维度格式将从输入图像中推断。 可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理单张或批量图像。
post_process_semantic_segmentation
< source >( outputs target_sizes: List = None ) → semantic_segmentation
参数
- outputs (MobileViTForSemanticSegmentation) — 模型的原始输出。
- target_sizes (
List[Tuple]
of lengthbatch_size
, optional) — 对应于每个预测的请求最终尺寸(高度,宽度)的元组列表。 如果未设置,则不会调整预测大小。(可选参数,列表长度为batch_size
)
返回值
semantic_segmentation
List[torch.Tensor]
,长度为 batch_size
,其中每个项目是形状为 (height, width) 的语义分割图,对应于 target_sizes
条目(如果指定了 target_sizes
)。每个 torch.Tensor
的每个条目对应于一个语义类别 ID。
将 MobileViTForSemanticSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
MobileViTModel
class transformers.MobileViTModel
< source >( config: MobileViTConfig expand_output: bool = True )
参数
- config (MobileViTConfig) — 具有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
裸 MobileViT 模型输出原始隐藏状态,顶部没有任何特定的头部。 此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( pixel_values: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。 像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 MobileViTImageProcessor.call() 。 - 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
of shape(batch_size, num_channels, height, width)
) — 模型最后一层输出端的隐藏状态序列。 -
pooler_output (
torch.FloatTensor
of shape(batch_size, hidden_size)
) — 对空间维度进行池化操作后的最后一层隐藏状态。 -
hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —torch.FloatTensor
的元组(如果模型具有嵌入层,则为嵌入输出的元组 + 每层输出的元组),形状为(batch_size, num_channels, height, width)
。(可选参数,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回)模型在每一层输出端的隐藏状态,以及可选的初始嵌入输出。
MobileViTModel 前向方法,覆盖了 __call__
特殊方法。
尽管前向传递的步骤需要在该函数中定义,但应该在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, MobileViTModel
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("apple/mobilevit-small")
>>> model = MobileViTModel.from_pretrained("apple/mobilevit-small")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 640, 8, 8]
MobileViTForImageClassification
class transformers.MobileViTForImageClassification
< source >( config: MobileViTConfig )
参数
- config (MobileViTConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
带有图像分类头的 MobileViT 模型(池化特征之上的线性层),例如用于 ImageNet。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( pixel_values: Optional = None output_hidden_states: Optional = None labels: Optional = None return_dict: Optional = None ) → transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参见 MobileViTImageProcessor.call()。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - labels (
torch.LongTensor
,形状为(batch_size,)
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
中。 如果config.num_labels == 1
,则计算回归损失(均方误差损失)。 如果config.num_labels > 1
,则计算分类损失(交叉熵)。
返回值
transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 torch.FloatTensor
的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (MobileViTConfig) 和输入。
- loss (
torch.FloatTensor
,形状为(1,)
,可选,当提供labels
时返回) — 分类(或如果 config.num_labels==1 则为回归)损失。 - logits (
torch.FloatTensor
,形状为(batch_size, config.num_labels)
) — 分类(或如果 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", trust_remote_code=True)
>>> 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])
tabby, tabby cat
MobileViTForSemanticSegmentation
class transformers.MobileViTForSemanticSegmentation
< source >( config: MobileViTConfig )
参数
- config (MobileViTConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
带有语义分割头的 MobileViT 模型,例如用于 Pascal VOC。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( pixel_values: Optional = None labels: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → transformers.modeling_outputs.SemanticSegmenterOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参见 MobileViTImageProcessor.call()。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - labels (
torch.LongTensor
,形状为(batch_size, height, width)
, 可选) — 用于计算损失的真实语义分割图。索引应在[0, ..., config.num_labels - 1]
中。如果config.num_labels > 1
,则计算分类损失(交叉熵)。
返回值
transformers.modeling_outputs.SemanticSegmenterOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.SemanticSegmenterOutput 或 torch.FloatTensor
的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (MobileViTConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为(1,)
,可选,当提供labels
时返回) — 分类(或如果 config.num_labels==1 则为回归)损失。 -
logits (
torch.FloatTensor
,形状为(batch_size, config.num_labels, logits_height, logits_width)
) — 每个像素的分类分数。返回的 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 函数一样传递输入!
call
< 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 或 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
。 此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 此参数可以在即时模式下使用,在图模式下,该值将始终设置为 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
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出端的隐藏状态序列。 -
pooler_output (
tf.Tensor
,形状为(batch_size, hidden_size)
) — 序列的第一个 token(分类 token)的最后一层隐藏状态,通过线性层和 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 前向方法覆盖了 __call__
特殊方法。
尽管前向传递的步骤需要在该函数中定义,但应该在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFMobileViTModel
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> 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 函数一样传递输入!
call
< 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
。 此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 此参数可以在即时模式下使用,在图模式下,该值将始终设置为 True。 - labels (
tf.Tensor
,形状为(batch_size,)
, 可选) — 用于计算图像分类/回归损失的标签。 索引应在[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 (
tf.Tensor
,形状为(1,)
, 可选,当提供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 前向方法覆盖了 __call__
特殊方法。
尽管前向传递的步骤需要在该函数中定义,但应该在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFMobileViTForImageClassification
>>> import tensorflow as tf
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> 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 函数一样传递输入!
call
< 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
。 此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 此参数可以在即时模式下使用,在图模式下,该值将始终设置为 True。 - labels (
tf.Tensor
,形状为(batch_size, height, width)
, 可选) — 用于计算损失的地面实况语义分割图。 索引应在[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 (
tf.Tensor
,形状为(1,)
, 可选,当提供labels
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 -
logits (
tf.Tensor
,形状为(batch_size, config.num_labels, logits_height, logits_width)
) — 每个像素的分类分数。返回的 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 前向方法覆盖了 __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