Transformers documentation
MobileViT
该模型于 2021-10-05 在 HF papers 上发布,并于 2022-06-29 贡献至 Hugging Face Transformers。
MobileViT
MobileViT 是一种面向移动设备的轻量级视觉 Transformer,它将 CNN 的高效性与归纳偏置同 Transformer 的全局上下文建模能力相结合。它将 Transformer 视为卷积操作,从而避免了标准 ViT 高昂的计算开销,实现了全局信息的处理。

您可以在 Apple 组织下找到所有原始的 MobileViT 检查点。
- 该模型由 matthijs 贡献。
点击右侧边栏中的 MobileViT 模型,以查看更多将 MobileViT 应用于不同视觉任务的示例。
下面的示例演示了如何使用 Pipeline 和 AutoModel 类进行[图像分类]。
from transformers import pipeline
classifier = pipeline(
task="image-classification",
model="apple/mobilevit-small",
device=0,
)
preds = classifier("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")
print(f"Prediction: {preds}\n")import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, MobileViTForImageClassification
image_processor = AutoImageProcessor.from_pretrained(
"apple/mobilevit-small",
use_fast=True,
)
model = MobileViTForImageClassification.from_pretrained("apple/mobilevit-small", device_map="auto")
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.no_grad():
logits = model(**inputs).logits
predicted_class_id = logits.argmax(dim=-1).item()
class_labels = model.config.id2label
predicted_class_label = class_labels[predicted_class_id]
print(f"The predicted class label is:{predicted_class_label}")备注
- 它不处理顺序数据,而是专为图像任务设计的。
- 特征图被直接用于替代 token 嵌入。
- 使用 MobileViTImageProcessor 对图像进行预处理。
- 如果使用自定义预处理,请确保图像为 BGR 格式(而非 RGB),以符合预训练权重的要求。
- 分类模型在 ImageNet-1k 上进行预训练。
- 分割模型使用 DeepLabV3 头,并在 PASCAL VOC 上进行了预训练。
MobileViTConfig
class transformers.MobileViTConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonenum_channels: int = 3image_size: int | list[int] | tuple[int, int] = 256patch_size: int | list[int] | tuple[int, int] = 2hidden_sizes: list[int] | tuple[int, ...] = (144, 192, 240)neck_hidden_sizes: list[int] | tuple[int, ...] = (16, 32, 64, 96, 128, 160, 640)num_attention_heads: int = 4mlp_ratio: float = 2.0expand_ratio: float = 4.0hidden_act: str = 'silu'conv_kernel_size: int = 3output_stride: int = 32hidden_dropout_prob: float | int = 0.1attention_probs_dropout_prob: float | int = 0.0classifier_dropout_prob: float | int = 0.1initializer_range: float = 0.02layer_norm_eps: float = 1e-05qkv_bias: bool = Trueaspp_out_channels: int = 256atrous_rates: list[int] | tuple[int, ...] = (6, 12, 18)aspp_dropout_prob: float | int = 0.1semantic_loss_ignore_index: int = 255 )
参数
- num_channels (
int,可选,默认为3) — 输入通道的数量。 - image_size (
Union[int, list[int], tuple[int, int]],可选,默认为256) — 每张图片的尺寸(分辨率)。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为2) — 每个 patch 的大小(分辨率)。 - hidden_sizes (
Union[list[int], tuple[int, ...]],可选,默认为(144, 192, 240)) — 模型每个阶段的维度(隐藏层大小)。 - 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) — 用于设置扩展输出维度的扩展比例 - hidden_act (
str,可选,默认为silu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - conv_kernel_size (
int,可选,默认为3) — 卷积核的大小。 - output_stride (
int,可选,默认为32) — 输入与输出特征图的空间分辨率之比。 - hidden_dropout_prob (
Union[float, int],可选,默认为0.1) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - classifier_dropout_prob (
Union[float, int],可选,默认为0.1) — 分类器的 dropout 比率。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - 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 层的膨胀(空洞)卷积因子。 - aspp_dropout_prob (
float,可选,默认值为 0.1) — 用于语义分割的 ASPP 层的 dropout 比率。 - semantic_loss_ignore_index (
int,可选,默认为255) — 语义分割模型的损失函数中忽略的索引。
这是用于存储 MobileViTModel 配置的类。它根据指定的参数实例化 Mobilevit 模型,并定义模型架构。使用默认值实例化配置将得到与 google/mobilenet_v2_1.0_224 类似的配置。
配置对象继承自 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.configMobileViTImageProcessor
class transformers.MobileViTImageProcessor
< source >( **kwargs: *<class 'transformers.models.mobilevit.image_processing_mobilevit.MobileVitImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为None) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'shortest_edge' -- 224}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 256, 'width': 256}): 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为None) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选,默认为True) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - do_flip_channel_order (
bool,kwargs,可选,默认为self.do_flip_channel_order) — 是否将颜色通道从 RGB 翻转为 BGR,或反之。 - do_reduce_labels (
bool,kwargs,可选,默认为self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。
构建一个 MobileViTImageProcessor 图像处理器。
预处理
< 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**kwargs: *<class 'transformers.models.mobilevit.image_processing_mobilevit.MobileVitImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - segmentation_maps (
ImageInput,可选) — 要预处理的分割图。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - do_flip_channel_order (
bool,kwargs,可选,默认为self.do_flip_channel_order) — 是否将颜色通道从 RGB 翻转为 BGR,或反之。 - do_reduce_labels (
bool,kwargs,可选,默认为self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_semantic_segmentation
< source >( outputstarget_sizes: list[tuple[int, int]] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]
参数
- outputs (MobileViTForSemanticSegmentation) — 模型的原始输出。
- target_sizes (
list[tuple[int, int]], 可选) — 一个元组列表,对应每个预测所需的最终尺寸(高度、宽度)。 - return_segmentation_scores (
bool,可选,默认为False) — 是否随分割图一起返回分割分数。当True时,返回列表中的每个元素都是一个SemanticSegmentationPostProcessorOutput,包含字段segmentation(类别 ID,形状为(height, width))和segmentation_scores(形状为(num_classes, height, width))。
返回值
list[torch.Tensor] 或 list[SemanticSegmentationPostProcessorOutput]
当 return_segmentation_scores=False(默认值)时,返回一个长度为 batch_size 的列表,其中每个元素都是形状为 (height, width) 的分割图,包含类别 ID。当 return_segmentation_scores=True 时,返回一个 SemanticSegmentationPostProcessorOutput 列表,包含字段 segmentation(类别 ID,形状为 (height, width))和 segmentation_scores(形状为 (num_classes, height, width))。在这两种情况下,(height, width) 对应于目标尺寸(如果指定了 target_sizes)。
将 MobileViTForSemanticSegmentation 的输出转换为语义分割图。
MobileViTImageProcessorPil
class transformers.MobileViTImageProcessorPil
< source >( **kwargs: *<class 'transformers.models.mobilevit.image_processing_pil_mobilevit.MobileVitImageProcessorKwargs'> )
参数
- do_convert_rgb (
bool,kwargs,可选,默认为None) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选,默认为True) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'shortest_edge' -- 224}): 描述输入到模型的最大尺寸。 - default_to_square (
bool,kwargs,可选,默认为False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为{'height' -- 256, 'width': 256}): 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时才会生效。 - do_rescale (
bool,kwargs,可选,默认为True) — 是否对图像进行重新缩放。 - rescale_factor (
float,kwargs,可选,默认为0.00392156862745098) — 当do_rescale设置为True时,用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选,默认为None) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选,默认为True) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - do_flip_channel_order (
bool,kwargs,可选,默认为self.do_flip_channel_order) — 是否将颜色通道从 RGB 翻转为 BGR,或反之。 - do_reduce_labels (
bool,kwargs,可选,默认为self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。
构建一个 MobileViTImageProcessor 图像处理器。
预处理
< 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**kwargs: *<class 'transformers.models.mobilevit.image_processing_pil_mobilevit.MobileVitImageProcessorKwargs'> ) → ~image_processing_base.BatchFeature
参数
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — 要预处理的图像。期望输入单张图像或一批图像,其像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - segmentation_maps (
ImageInput,可选) — 要预处理的分割图。 - do_convert_rgb (
bool,kwargs,可选) — 是否将图像转换为 RGB。 - do_resize (
bool,kwargs,可选) — 是否调整图像大小。 - size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。 - default_to_square (
bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。 - crop_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用center_crop后输出图像的尺寸。 - resample (
Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling中的一个值。仅当do_resize设置为True时生效。 - do_rescale (
bool,kwargs,可选) — 是否对图像进行重新缩放。 - rescale_factor (
float, kwargs, 可选) — 如果do_rescale设置为True,则用于对图像进行缩放的缩放因子。 - do_normalize (
bool,kwargs,可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当do_normalize设置为True时生效。 - do_pad (
bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。 - pad_size (
Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的{"height": int, "width" int}尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size,图像将被填充到批次中最大的高度和宽度。仅在do_pad=True.时应用。 - do_center_crop (
bool,kwargs,可选) — 是否对图像进行中心裁剪。 - data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持ChannelDimension.FIRST。为兼容旧版处理器而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。"channels_last"或ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。"none"或ChannelDimension.NONE:图像为 (height, width) 格式。
- device (
Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。 - return_tensors (
Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为'pt',则返回堆叠的张量,否则返回张量列表。 - disable_grouping (
bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157 - image_seq_length (
int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。 - do_flip_channel_order (
bool,kwargs,可选,默认为self.do_flip_channel_order) — 是否将颜色通道从 RGB 翻转为 BGR,或反之。 - do_reduce_labels (
bool,kwargs,可选,默认为self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
post_process_semantic_segmentation
< source >( outputstarget_sizes: list[tuple[int, int]] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]
参数
- outputs (MobileViTForSemanticSegmentation) — 模型的原始输出。
- target_sizes (
list[tuple[int, int]], 可选) — 一个元组列表,对应每个预测所需的最终尺寸(高度、宽度)。 - return_segmentation_scores (
bool,可选,默认为False) — 是否随分割图一起返回分割分数。当True时,返回列表中的每个元素都是一个SemanticSegmentationPostProcessorOutput,包含字段segmentation(类别 ID,形状为(height, width))和segmentation_scores(形状为(num_classes, height, width))。
返回值
list[torch.Tensor] 或 list[SemanticSegmentationPostProcessorOutput]
当 return_segmentation_scores=False(默认值)时,返回一个长度为 batch_size 的列表,其中每个元素都是形状为 (height, width) 的分割图,包含类别 ID。当 return_segmentation_scores=True 时,返回一个 SemanticSegmentationPostProcessorOutput 列表,包含字段 segmentation(类别 ID,形状为 (height, width))和 segmentation_scores(形状为 (num_classes, height, width))。在这两种情况下,(height, width) 对应于目标尺寸(如果指定了 target_sizes)。
将 MobileViTForSemanticSegmentation 的输出转换为语义分割图。
MobileViTModel
class transformers.MobileViTModel
< source >( config: MobileViTConfigexpand_output: bool = True )
参数
- config (MobileViTConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
- expand_output (
bool,可选,默认为True) — 是否使用 1x1 卷积来扩展模型的输出。如果为True,模型将应用一个额外的 1x1 卷积,将输出通道数从config.neck_hidden_sizes[5]扩展到config.neck_hidden_sizes[6]。
未添加任何特定头部的裸 Mobilevit 模型,输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 MobileViTImageProcessor 获取像素值。有关详细信息,请参阅 MobileViTImageProcessor.call()(processor_class使用 MobileViTImageProcessor 处理图像)。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
BaseModelOutputWithPoolingAndNoAttention 或 tuple(torch.FloatTensor)
BaseModelOutputWithPoolingAndNoAttention 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(MobileViTConfig)和输入而定的各种元素。
MobileViTModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, num_channels, height, width)的torch.FloatTensor)— 模型最后一层输出的隐藏状态序列。pooler_output(形状为
(batch_size, hidden_size)的torch.FloatTensor)— 在空间维度上执行池化操作后的最后一层隐藏状态。hidden_states (
tuple(torch.FloatTensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.FloatTensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, num_channels, height, width)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
MobileViTForImageClassification
class transformers.MobileViTForImageClassification
< source >( config: MobileViTConfig )
参数
- config (MobileViTConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
带有图像分类头(在池化特征之上添加一个线性层)的 MobileViT 模型,例如用于 ImageNet。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonelabels: typing.Optional[torch.Tensor] = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 MobileViTImageProcessor 获取像素值。有关详细信息,请参阅 MobileViTImageProcessor.call()(processor_class使用 MobileViTImageProcessor 处理图像)。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - labels(形状为
(batch_size,)的torch.LongTensor,可选)— 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。如果config.num_labels == 1,则计算回归损失(均方损失);如果config.num_labels > 1,则计算分类损失(交叉熵)。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
一个 ImageClassifierOutputWithNoAttention 或 torch.FloatTensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(MobileViTConfig)和输入。
MobileViTForImageClassification 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- loss (
torch.FloatTensor,形状为(1,),可选,当提供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)。模型在每个阶段输出处的隐藏状态(也称为特征图)。
示例:
>>> 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("google/mobilenet_v2_1.0_224")
>>> model = MobileViTForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...MobileViTForSemanticSegmentation
class transformers.MobileViTForSemanticSegmentation
< source >( config: MobileViTConfig )
参数
- config (MobileViTConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
带有语义分割头的 MobileViT 模型,例如用于 Pascal VOC。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → SemanticSegmenterOutput or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 MobileViTImageProcessor 获取像素值。有关详细信息,请参阅 MobileViTImageProcessor.call()(processor_class使用 MobileViTImageProcessor 处理图像)。 - 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 而不是普通元组。
返回值
SemanticSegmenterOutput 或 tuple(torch.FloatTensor)
SemanticSegmenterOutput 或 torch.FloatTensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(MobileViTConfig)和输入。
MobileViTForSemanticSegmentation 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.FloatTensor,形状为(1,),可选,当提供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 之后的权重,用于在自注意力头中计算加权平均值。
示例:
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch
>>> from PIL import Image
>>> from transformers import AutoImageProcessor, MobileViTForSemanticSegmentation
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> 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