Transformers 文档
MobileViT
并获得增强的文档体验
开始使用
MobileViT
概述
MobileViT 模型由 Sachin Mehta 和 Mohammad Rastegari 在 MobileViT: Light-weight, General-purpose, and Mobile-friendly Vision 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 准确率,对于相似数量的参数,这比基于 CNN 的 MobileNetv3 和基于 ViT 的 DeIT 高出 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)
生成的模型将只有大约 1 MB,使其非常适合资源和网络带宽可能受限的移动应用程序。
资源
官方 Hugging Face 和社区(🌎 表示)资源列表,可帮助您开始使用 MobileViT。
语义分割
如果您有兴趣提交资源以包含在此处,请随时打开 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
) — 是否为 queries, keys 和 values 添加偏置。 - aspp_out_channels (
int
, 可选, 默认为 256) — 用于语义分割的 ASPP 层中使用的输出通道数。 - atrous_rates (
List[int]
, 可选, 默认为[6, 12, 18]
) — 用于语义分割的 ASPP 层中使用的空洞率(atrous rate)。 - 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.List[typing.Tuple] = None ) → semantic_segmentation
参数
- outputs (MobileViTForSemanticSegmentation) — 模型的原始输出。
- target_sizes (长度为
batch_size
的List[Tuple]
, 可选) — 与每个预测请求的最终大小(高度,宽度)相对应的元组列表。如果未设置,则不会调整预测大小。
返回值
semantic_segmentation
长度为 batch_size
的 List[torch.Tensor]
, 其中每个项目是形状为 (height, width) 的语义分割图,对应于 target_sizes 条目(如果指定了 target_sizes
)。每个 torch.Tensor
的每个条目对应于一个语义类别 ID。
将 MobileViTForSemanticSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
MobileViTImageProcessor
class transformers.MobileViTImageProcessor
< source >( do_resize: bool = True size: typing.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.Dict[str, int] = None do_flip_channel_order: bool = True **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可以被preprocess
方法中的do_resize
参数覆盖。 - size (
Dict[str, int]
可选, 默认为{"shortest_edge" -- 224}
): 控制调整大小后输出图像的大小。可以被preprocess
方法中的size
参数覆盖。 - resample (
PILImageResampling
, 可选, 默认为Resampling.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: bool = None size: typing.Dict[str, int] = None resample: Resampling = None do_rescale: bool = None rescale_factor: float = None do_center_crop: bool = None crop_size: typing.Dict[str, int] = None do_flip_channel_order: 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) — 返回张量的类型。 可以是以下之一:- 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)。
- 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: typing.List[typing.Tuple] = None ) → semantic_segmentation
参数
- outputs (MobileViTForSemanticSegmentation) — 模型的原始输出。
- target_sizes (
List[Tuple]
of lengthbatch_size
, optional) — 对应于每个预测的请求最终尺寸(高度,宽度)的元组列表。 如果未设置,则不会调整预测大小。
返回值
semantic_segmentation
长度为 batch_size
的 List[torch.Tensor]
, 其中每个项目是形状为 (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: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
or 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 而不是纯元组。
返回值
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)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(如果模型具有嵌入层,则为嵌入的输出 + 每层输出一个),形状为(batch_size, num_channels, height, width)
。模型在每一层输出处的隐藏状态,加上可选的初始嵌入输出。
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: 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.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 前向方法,覆盖了 __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: 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 或 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 前向方法,覆盖了 __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 模型输出原始的隐藏状态,没有任何特定的 head 在顶部。此模型继承自 TFPreTrainedModel。查看超类文档以获取库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 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
。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通的元组。此参数可以在 eager 模式下使用,在 graph 模式下,该值将始终设置为 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 (形状为
(batch_size, sequence_length, hidden_size)
的tf.Tensor
) — 模型最后一层的输出处的隐藏状态序列。 -
pooler_output (形状为
(batch_size, hidden_size)
的tf.Tensor
) — 序列的第一个 token(分类 token)的最后一层隐藏状态,通过线性层和 Tanh 激活函数进一步处理。线性层权重在预训练期间从下一个句子预测(分类)目标中训练而来。此输出通常不是输入语义内容的良好摘要,对于整个输入序列,您通常最好对隐藏状态序列进行平均或池化。
-
hidden_states (
tuple(tf.Tensor)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(embeddings 的输出一个,每层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
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", 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。查看超类文档以获取库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 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
。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通的元组。此参数可以在 eager 模式下使用,在 graph 模式下,该值将始终设置为 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 (形状为
(batch_size, config.num_labels)
的tf.Tensor
) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。 - hidden_states (
tuple(tf.Tensor)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(embeddings 的输出一个,如果模型有 embedding 层,+ 每 stage 的输出一个),形状为(batch_size, num_channels, height, width)
。模型在每个 stage 输出处的隐藏状态(也称为特征图)。
TFMobileViTForImageClassification forward 方法,覆盖了 __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。查看超类文档以获取库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 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
。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 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 (形状为
(1,)
的tf.Tensor
, 可选, 当提供了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
的 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