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