Transformers 文档

LeViT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

LeViT

PyTorch

概述

LeViT 模型由 Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze 在 LeViT: Introducing Convolutions to Vision Transformers 中提出。LeViT 通过 Transformer 中分辨率递减的激活图和引入注意力偏差以整合位置信息等架构差异,提高了 Vision Transformer (ViT) 的性能和效率。

论文摘要如下:

我们设计了一个图像分类架构系列,旨在高速状态下优化精度和效率之间的权衡。我们的工作利用了最近在基于注意力的架构方面的发现,这些架构在高度并行处理硬件上具有竞争力。我们回顾了大量关于卷积神经网络的文献中的原则,并将其应用于 Transformer,特别是分辨率递减的激活图。我们还引入了注意力偏差,这是一种在视觉 Transformer 中整合位置信息的新方法。因此,我们提出了 LeViT:一种用于快速推理图像分类的混合神经网络。我们考虑了在不同硬件平台上的不同效率度量,以最好地反映各种应用场景。我们大量的实验经验性地验证了我们的技术选择,并表明它们适用于大多数架构。总的来说,LeViT 在速度/精度权衡方面显著优于现有的卷积网络和视觉 Transformer。例如,在 80% ImageNet top-1 精度下,LeViT 在 CPU 上比 EfficientNet 快 5 倍。

drawing LeViT 架构。摘自原始论文

该模型由 anugunj 贡献。原始代码可在 此处 找到。

使用技巧

  • 与 ViT 相比,LeViT 模型使用了一个额外的蒸馏头,以有效地从教师模型(在 LeViT 论文中是 ResNet 类似模型)中学习。蒸馏头通过反向传播在 ResNet 类似模型的监督下进行学习。它们还从卷积神经网络中汲取灵感,使用分辨率递减的激活图来提高效率。
  • 微调蒸馏模型有两种方式:(1) 经典方式,只在最终隐藏状态之上放置一个预测头,不使用蒸馏头;或者 (2) 同时在最终隐藏状态之上放置预测头和蒸馏头。在这种情况下,预测头使用预测头和真实标签之间的常规交叉熵进行训练,而蒸馏预测头使用硬蒸馏(蒸馏头预测和教师预测的标签之间的交叉熵)进行训练。在推理时,取两个头的平均预测作为最终预测。(2) 也称为“带蒸馏的微调”,因为它依赖于已在下游数据集上微调过的教师模型。在模型方面,(1) 对应于 LevitForImageClassification,(2) 对应于 LevitForImageClassificationWithTeacher
  • 所有发布的检查点均仅在 ImageNet-1k(也称为 ILSVRC 2012,包含 130 万张图像和 1,000 个类别)上进行预训练和微调。未使用任何外部数据。这与原始 ViT 模型形成对比,原始 ViT 模型使用 JFT-300M 数据集/Imagenet-21k 等外部数据进行预训练。
  • LeViT 的作者发布了 5 个经过训练的 LeViT 模型,你可以直接将其插入 LevitModelLevitForImageClassification。为了模拟在更大的数据集上进行训练(同时只使用 ImageNet-1k 进行预训练),使用了数据增强、优化和正则化等技术。可用的 5 种变体(所有均在 224x224 尺寸图像上训练)包括:*facebook/levit-128S*、*facebook/levit-128*、*facebook/levit-192*、*facebook/levit-256* 和 *facebook/levit-384*。请注意,应该使用 LevitImageProcessor 来准备图像供模型使用。
  • LevitForImageClassificationWithTeacher 目前仅支持推理,不支持训练或微调。
  • 你可以在此处查看关于推理以及在自定义数据上进行微调的演示笔记本(你可以将 ViTFeatureExtractor 替换为 LevitImageProcessor,并将 ViTForImageClassification 替换为 LevitForImageClassificationLevitForImageClassificationWithTeacher)。

资源

Hugging Face 官方和社区 (🌎 标记) 资源列表,助你快速开始使用 LeViT。

图像分类

如果您有兴趣在此处提交资源,请随时开启 Pull Request,我们将对其进行审查!该资源最好能展示一些新内容,而不是重复现有资源。

LevitConfig

class transformers.LevitConfig

< >

( image_size = 224 num_channels = 3 kernel_size = 3 stride = 2 padding = 1 patch_size = 16 hidden_sizes = [128, 256, 384] num_attention_heads = [4, 8, 12] depths = [4, 4, 4] key_dim = [16, 16, 16] drop_path_rate = 0 mlp_ratio = [2, 2, 2] attention_ratio = [2, 2, 2] initializer_range = 0.02 **kwargs )

参数

  • image_size (int, 可选, 默认为 224) — 输入图像的大小。
  • num_channels (int, 可选, 默认为 3) — 输入图像中的通道数。
  • kernel_size (int, 可选, 默认为 3) — 补丁嵌入初始卷积层的核大小。
  • stride (int, 可选, 默认为 2) — 补丁嵌入初始卷积层的步幅大小。
  • padding (int, 可选, 默认为 1) — 补丁嵌入初始卷积层的填充大小。
  • patch_size (int, 可选, 默认为 16) — 嵌入的补丁大小。
  • hidden_sizes (list[int], 可选, 默认为 [128, 256, 384]) — 每个编码器块的维度。
  • num_attention_heads (list[int], 可选, 默认为 [4, 8, 12]) — Transformer 编码器每个块中每个注意力层的注意力头数量。
  • depths (list[int], 可选, 默认为 [4, 4, 4]) — 每个编码器块中的层数。
  • key_dim (list[int], 可选, 默认为 [16, 16, 16]) — 每个编码器块中键的维度。
  • drop_path_rate (int, 可选, 默认为 0) — Transformer 编码器块中使用的随机深度丢弃概率。
  • mlp_ratios (list[int], 可选, 默认为 [2, 2, 2]) — 编码器块中 Mix FFNs 的隐藏层大小与输入层大小的比例。
  • attention_ratios (list[int], 可选, 默认为 [2, 2, 2]) — 注意力层输出维度与输入维度之比。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。

这是存储 LevitModel 配置的配置类。它用于根据指定参数实例化 LeViT 模型,定义模型架构。使用默认值实例化配置将生成与 LeViT facebook/levit-128S 架构类似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关详细信息,请参阅 PretrainedConfig 的文档。

示例

>>> from transformers import LevitConfig, LevitModel

>>> # Initializing a LeViT levit-128S style configuration
>>> configuration = LevitConfig()

>>> # Initializing a model (with random weights) from the levit-128S style configuration
>>> model = LevitModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

LevitFeatureExtractor

class transformers.LevitFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

预处理单张或批量图像。

LevitImageProcessor

class transformers.LevitImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BICUBIC: 3> do_center_crop: bool = True crop_size: typing.Optional[dict[str, int]] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, collections.abc.Iterable[float], NoneType] = [0.485, 0.456, 0.406] image_std: typing.Union[float, collections.abc.Iterable[float], NoneType] = [0.229, 0.224, 0.225] **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将输入图像的最短边调整为 int(256/224 *size)。可以通过 preprocess 方法中的 do_resize 参数覆盖。
  • size (dict[str, int], 可选, 默认为 {"shortest_edge" -- 224}): 调整大小后的输出图像大小。如果 size 是一个包含 "width" 和 "height" 键的字典,图像将调整为 (size["height"], size["width"])。如果 size 是一个包含 "shortest_edge" 键的字典,最短边值 c 将按 int(c * (256/224)) 进行缩放。图像的较短边将与此值匹配,即,如果高度 > 宽度,则图像将缩放为 (size["shortest_egde"] * height / width, size["shortest_egde"])。可以通过 preprocess 方法中的 size 参数覆盖。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BICUBIC) — 如果调整图像大小,使用的重采样滤波器。可以通过 preprocess 方法中的 resample 参数覆盖。
  • do_center_crop (bool, 可选, 默认为 True) — 是否将输入图像中心裁剪为 (crop_size["height"], crop_size["width"])。可以通过 preprocess 方法中的 do_center_crop 参数覆盖。
  • crop_size (Dict, 可选, 默认为 {"height" -- 224, "width": 224}): center_crop 后所需的图像大小。可以通过 preprocess 方法中的 crop_size 参数覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 控制是否通过指定比例 rescale_factor 缩放图像。可以通过 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果缩放图像,使用的缩放因子。可以通过 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 控制是否对图像进行标准化。可以通过 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (list[int], 可选, 默认为 [0.485, 0.456, 0.406]) — 如果对图像进行标准化,使用的均值。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (list[int], 可选, 默认为 [0.229, 0.224, 0.225]) — 如果对图像进行标准化,使用的标准差。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_std 参数覆盖。

构建一个 LeViT 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, collections.abc.Iterable[float], NoneType] = None image_std: typing.Union[float, collections.abc.Iterable[float], NoneType] = None return_tensors: typing.Optional[transformers.utils.generic.TensorType] = 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
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 self.size) — 调整大小后的输出图像大小。如果 size 是一个包含 "width" 和 "height" 键的字典,图像将调整为 (height, width)。如果 size 是一个包含 "shortest_edge" 键的字典,最短边值 c 将按 int(c * (256/224)) 进行缩放。图像的较短边将与此值匹配,即,如果高度 > 宽度,则图像将缩放为 (size * height / width, size)。
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BICUBIC) — 调整图像大小时使用的重采样滤波器。
  • do_center_crop (bool, 可选, 默认为 self.do_center_crop) — 是否中心裁剪图像。
  • crop_size (dict[str, int], 可选, 默认为 self.crop_size) — 中心裁剪后输出图像的大小。将图像裁剪为 (crop_size[“height”], crop_size[“width”])。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否通过 rescaling_factor 缩放图像像素值——通常缩放到 0 和 1 之间的值。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 缩放图像像素值的因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否通过 image_meanimage_std 规范化图像像素值。
  • image_mean (floatlist[float], 可选, 默认为 self.image_mean) — 用于规范化图像像素值的平均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 用于规范化图像像素值的标准差。
  • return_tensors (strTensorType, 可选) — 返回张量的类型。可以是以下之一:
    • 未设置:返回 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 (strChannelDimension, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。
    • "none"ChannelDimension.NONE:图像为 (height, width) 格式。

预处理一个或一批图像,以用作 LeViT 模型的输入。

LevitImageProcessorFast

class transformers.LevitImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )

构造一个快速 Levit 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) <class 'transformers.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
  • do_resize (bool, 可选) — 是否调整图像大小。
  • size (dict[str, int], 可选) — 描述模型的最大输入尺寸。
  • default_to_square (bool, 可选) — 当调整大小(如果 size 是整数)时,是否默认调整为方形图像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举 PILImageResampling 之一。仅当 do_resize 设置为 True 时才有效。
  • do_center_crop (bool, 可选) — 是否中心裁剪图像。
  • crop_size (dict[str, int], 可选) — 应用 center_crop 后输出图像的大小。
  • do_rescale (bool, 可选) — 是否缩放图像。
  • rescale_factor (Union[int, float, NoneType]) — 如果 do_rescale 设置为 True,则按此缩放因子调整图像大小。
  • do_normalize (bool, 可选) — 是否规范化图像。
  • image_mean (Union[float, list[float], NoneType]) — 用于规范化的图像均值。仅当 do_normalize 设置为 True 时才有效。
  • image_std (Union[float, list[float], NoneType]) — 用于规范化的图像标准差。仅当 do_normalize 设置为 True 时才有效。
  • do_convert_rgb (bool, 可选) — 是否将图像转换为 RGB。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果设置为 `pt`,则返回堆叠的张量;否则返回张量列表。
  • data_format (~image_utils.ChannelDimension, 可选) — 输出图像的通道维度格式。仅支持 ChannelDimension.FIRST。为与慢速处理器兼容而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension, NoneType]) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。
    • "none"ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (torch.device, 可选) — 处理图像的设备。如果未设置,则从输入图像推断设备。
  • disable_grouping (bool, 可选) — 是否禁用按大小对图像进行分组,以单独而不是分批处理它们。如果为 None,则如果图像在 CPU 上,则设置为 True,否则设置为 False。此选择基于经验观察,详情如下:https://github.com/huggingface/transformers/pull/38157

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

LevitModel

class transformers.LevitModel

< >

( config )

参数

  • config (LevitModel) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,只加载配置。有关加载模型权重,请查看 from_pretrained() 方法。

裸 Levit 模型,输出原始隐藏状态,顶部没有任何特定头部。

此模型继承自 PreTrainedModel。有关库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等),请查看超类文档。

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。

前向传播

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor, 形状为 (batch_size, num_channels, image_size, image_size), 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参见 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention 或一个 torch.FloatTensor 元组(如果传入 return_dict=False 或当 config.return_dict=False 时),包含根据配置 (LevitConfig) 和输入的不同元素。

  • 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)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

LevitModel 的前向传播方法,覆盖了 __call__ 特殊方法。

虽然前向传播的配方需要在该函数中定义,但在此之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。

示例

LevitForImageClassification

class transformers.LevitForImageClassification

< >

( config )

参数

  • config (LevitForImageClassification) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,只加载配置。有关加载模型权重,请查看 from_pretrained() 方法。

带图像分类头(在池化特征之上有一个线性层)的 Levit 模型,例如用于 ImageNet。

此模型继承自 PreTrainedModel。有关库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等),请查看超类文档。

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。

前向传播

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor, 形状为 (batch_size, num_channels, image_size, image_size), 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参见 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • labels (torch.LongTensor, 形状为 (batch_size,), 可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方误差损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

一个 transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或一个 torch.FloatTensor 元组(如果传入 return_dict=False 或当 config.return_dict=False 时),包含根据配置 (LevitConfig) 和输入的不同元素。

  • 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)。模型在每个阶段输出的隐藏状态(也称为特征图)。

LevitForImageClassification 的前向传播方法,覆盖了 __call__ 特殊方法。

虽然前向传播的配方需要在该函数中定义,但在此之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。

示例

>>> from transformers import AutoImageProcessor, LevitForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/levit-128S")
>>> model = LevitForImageClassification.from_pretrained("facebook/levit-128S")

>>> 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])
...

LevitForImageClassificationWithTeacher

class transformers.LevitForImageClassificationWithTeacher

< >

( config )

参数

带图像分类头(在最终隐藏状态之上有一个线性层,在蒸馏 token 的最终隐藏状态之上有一个线性层)的 LeViT 模型转换器,例如用于 ImageNet。..警告::此模型仅支持推理。尚不支持带蒸馏(即带教师)的微调。

此模型继承自 PreTrainedModel。有关库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等),请查看超类文档。

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。

前向传播

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.levit.modeling_levit.LevitForImageClassificationWithTeacherOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获得。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

transformers.models.levit.modeling_levit.LevitForImageClassificationWithTeacherOutputtuple(torch.FloatTensor)

一个 transformers.models.levit.modeling_levit.LevitForImageClassificationWithTeacherOutput 或一个 torch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),根据配置(LevitConfig)和输入包含各种元素。

  • logits (torch.FloatTensor,形状为 (batch_size, config.num_labels)) — 作为 cls_logitsdistillation_logits 平均值的预测分数。

  • cls_logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类头部(即类标记最终隐藏状态顶部线性层)的预测分数。

  • distillation_logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 蒸馏头部(即蒸馏标记最终隐藏状态顶部线性层)的预测分数。

  • hidden_states (tuple[torch.FloatTensor]可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+一个用于每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

LevitForImageClassificationWithTeacher 的前向方法,覆盖了 __call__ 特殊方法。

虽然前向传播的配方需要在该函数中定义,但在此之后应该调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。

示例

>>> from transformers import AutoImageProcessor, LevitForImageClassificationWithTeacher
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("facebook/levit-128S")
>>> model = LevitForImageClassificationWithTeacher.from_pretrained("facebook/levit-128S")

>>> 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])
...
< > 在 GitHub 上更新