Transformers 文档

LeViT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2021-04-02 发布,并于 2022-06-01 添加到 Hugging Face Transformers。

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 万张图像和 1000 个类别)上进行了预训练和微调。没有使用外部数据。这与原始 ViT 模型不同,后者使用了 JFT-300M 数据集/Imagenet-21k 等外部数据进行预训练。
  • LeViT 的作者发布了 5 个训练好的 LeViT 模型,您可以直接将它们集成到 LevitModelLevitForImageClassification 中。数据增强、优化和正则化等技术被用于模拟在更大数据集上的训练(尽管只使用了 ImageNet-1k 进行预训练)。可用的 5 个变体是(均在 224x224 图像尺寸下训练):facebook/levit-128Sfacebook/levit-128facebook/levit-192facebook/levit-256facebook/levit-384。请注意,应该使用 LevitImageProcessor 来准备模型输入图像。
  • LevitForImageClassificationWithTeacher 目前仅支持推理,不支持训练或微调。
  • 您可以在此处查看有关推理和自定义数据微调的演示笔记本(只需将 ViTImageProcessor 替换为 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, optional, 默认为 224) — 输入图像的大小。
  • num_channels (int, optional, 默认为 3) — 输入图像中的通道数。
  • kernel_size (int, optional, 默认为 3) — 初始卷积层的 patch embedding 的核大小。
  • stride (int, optional, 默认为 2) — 初始卷积层的 patch embedding 的步幅。
  • padding (int, optional, 默认为 1) — 初始卷积层的 patch embedding 的填充大小。
  • patch_size (int, optional, 默认为 16) — embeddings 的 patch 大小。
  • hidden_sizes (list[int], optional, 默认为 [128, 256, 384]) — Transformer 编码器中每个块的维度。
  • num_attention_heads (list[int], optional, 默认为 [4, 8, 12]) — Transformer 编码器中每个注意力层和每个块的注意力头数。
  • depths (list[int], optional, 默认为 [4, 4, 4]) — 每个编码器块中的层数。
  • key_dim (list[int], optional, 默认为 [16, 16, 16]) — 每个编码器块中 key 的大小。
  • drop_path_rate (int, optional, 默认为 0) — 随机深度中 dropout 的概率,用于 Transformer 编码器的块。
  • mlp_ratios (list[int], optional, 默认为 [2, 2, 2]) — 编码器块中 Mix FFNs 的隐藏层大小与输入层大小的比例。
  • attention_ratios (list[int], optional, 默认为 [2, 2, 2]) — 注意力层输出维度与输入维度之比。
  • initializer_range (float, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 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

LevitImageProcessor

class transformers.LevitImageProcessor

< >

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

参数

  • do_resize (bool, optional, 默认为 True) — 是否将输入图像的短边调整为 int(256/224 *size)。可以被 preprocess 方法中的 do_resize 参数覆盖。
  • size (dict[str, int], optional, 默认为 {"shortest_edge" -- 224}): 调整大小后的输出图像大小。如果 size 是一个包含“width”和“height”键的字典,则图像将被调整为 (size["height"], size["width"])。如果 size 是一个包含“shortest_edge”键的字典,则最短边值 c 将被重缩放到 int(c * (256/224))。图像的较短边将匹配此值,即如果 height > width,则图像将被重缩放到 (size["shortest_edge"] * height / width, size["shortest_edge"])。可以被 preprocess 方法中的 size 参数覆盖。
  • resample (PILImageResampling, optional, 默认为 Resampling.BICUBIC) — 如果调整图像大小,则使用的重采样过滤器。可以被 preprocess 方法中的 resample 参数覆盖。
  • do_center_crop (bool, optional, 默认为 True) — 是否将输入图像中心裁剪为 (crop_size["height"], crop_size["width"])。可以被 preprocess 方法中的 do_center_crop 参数覆盖。
  • crop_size (Dict, optional, 默认为 {"height" -- 224, "width": 224}): center_crop 后的期望图像大小。可以被 preprocess 方法中的 crop_size 参数覆盖。
  • do_rescale (bool, optional, 默认为 True) — 控制是否通过指定的比例 rescale_factor 来重缩放图像。可以被 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, optional, 默认为 1/255) — 如果重缩放图像,则使用的比例因子。可以被 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize (bool, optional, 默认为 True) — 控制是否对图像进行归一化。可以被 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (list[int], optional, 默认为 [0.485, 0.456, 0.406]) — 归一化图像时使用的均值。这是一个长度等于图像通道数的 float 或 float 列表。可以被 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (list[int], optional, 默认为 [0.229, 0.224, 0.225]) — 归一化图像时使用的标准差。这是一个长度等于图像通道数的 float 或 float 列表。可以被 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: bool | None = None size: dict[str, int] | None = None resample: PIL.Image.Resampling | None = None do_center_crop: bool | None = None crop_size: dict[str, int] | None = None do_rescale: bool | None = None rescale_factor: float | None = None do_normalize: bool | None = None image_mean: float | collections.abc.Iterable[float] | None = None image_std: float | collections.abc.Iterable[float] | None = None return_tensors: transformers.utils.generic.TensorType | None = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: str | transformers.image_utils.ChannelDimension | None = None )

参数

  • images (ImageInput) — 要预处理的图像或图像批次。期望值为 0 到 255 之间的单个图像或图像批次。如果传入像素值在 0 到 1 之间的图像,请将 do_rescale 设置为 False
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], optional, defaults to self.size) — 调整后的输出图像大小。如果 size 是一个包含“width”和“height”键的字典,则图像将被调整到 (height, width)。如果 size 是一个包含“shortest_edge”键的字典,则最短边值 c 会被缩放到 int(c * (256/224))。图像的较小边将匹配此值,即如果 height > width,则图像将被缩放到 (size * height / width, size)。
  • resample (PILImageResampling, optional, defaults to PILImageResampling.BICUBIC) — 调整图像大小时使用的重采样过滤器。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否进行中心裁剪。
  • crop_size (dict[str, int], optional, defaults to self.crop_size) — 中心裁剪后的输出图像大小。裁剪图像为 (crop_size[“height”], crop_size[“width”])。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像像素值乘以 rescaling_factor - 通常到 0 到 1 之间。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 缩放图像像素值的因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否通过 image_meanimage_std 来标准化图像像素值。
  • image_mean (float or list[float], optional, defaults to self.image_mean) — 用于标准化图像像素值的均值。
  • image_std (float or list[float], optional, defaults to self.image_std) — 用于标准化图像像素值的标准差。
  • return_tensors (str or TensorType, optional) — 要返回的张量类型。可以是以下之一:
    • 未设置:返回 np.ndarray 的列表。
    • TensorType.PYTORCH'pt':返回 torch.Tensor 类型的批次。
    • TensorType.NUMPY'np':返回 np.ndarray 类型的批次。
  • data_format (str or ChannelDimension, optional, defaults to ChannelDimension.FIRST) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
  • input_data_format (ChannelDimension or str, optional) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "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.processing_utils.ImagesKwargs] )

构造一个快速的 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.processing_utils.ImagesKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list, list, list]) — 要预处理的图像。期望单个或批次的图像,像素值范围为 0 到 255。如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • do_convert_rgb (bool | None.do_convert_rgb) — 是否将图像转换为 RGB。
  • do_resize (bool | None.do_resize) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 描述模型的最大输入尺寸。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 应用 center_crop 后的输出图像大小。
  • resample (Annotated[Union[PILImageResampling, int, NoneType], None]) — 如果调整图像大小,则使用的重采样过滤器。可以是枚举值 PILImageResampling 之一。仅当 do_resize 设置为 True 时才有效。
  • do_rescale (bool | None.do_rescale) — 是否缩放图像。
  • rescale_factor (float | None.rescale_factor) — 如果将 do_rescale 设置为 True,则用于缩放图像的缩放因子。
  • do_normalize (bool | None.do_normalize) — 是否标准化图像。
  • image_mean (float | list[float] | tuple[float, ...] | None.image_mean) — 用于标准化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (float | list[float] | tuple[float, ...] | None.image_std) — 用于标准化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool | None.do_pad) — 是否填充图像。填充是按批次中的最大尺寸进行的,或者按每张图像的固定方形尺寸进行的。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 要将图像填充到的尺寸({"height": int, "width": int})。必须大于预处理时提供的任何图像尺寸。如果未提供 pad_size,则图像将被填充到批次中的最大高度和宽度。仅当 do_pad=True 时应用。
  • do_center_crop (bool | None.do_center_crop) — 是否进行中心裁剪。
  • data_format (str | ~image_utils.ChannelDimension | None.data_format) — 仅支持 ChannelDimension.FIRST。为了与旧版处理器兼容而添加。
  • input_data_format (str | ~image_utils.ChannelDimension | None.input_data_format) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "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]) — 要处理图像的设备。如果未设置,则从输入图像推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None]) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool | None.disable_grouping) — 是否禁用按大小对图像进行分组以单独处理它们而不是批量处理。如果为 None,则如果图像在 CPU 上,则设置为 True,否则设置为 False。此选择基于经验观察,详见: https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int | None.image_seq_length) — 输入中每张图像要使用的图像 token 数量。为了向后兼容而添加,但将来应作为处理器属性设置。

返回

<class 'transformers.image_processing_base.BatchFeature'>

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

LevitModel

class transformers.LevitModel

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

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

LeViT 模型,输出原始隐藏状态,顶部没有特定的头。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.FloatTensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) — 输入图像对应的张量。像素值可以通过 LevitImageProcessorFast 获取。有关详细信息,请参阅 LevitImageProcessorFast.call()processor_class 使用 LevitImageProcessorFast 来处理图像)。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

根据配置(LevitConfig)和输入,返回一个 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontorch.FloatTensor 的元组(如果传入 return_dict=False 或当 config.return_dict=False)。

  • 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=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每层的一个输出),形状为 (batch_size, num_channels, height, width)

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

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

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

LevitForImageClassification

class transformers.LevitForImageClassification

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

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

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

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.FloatTensor | None = None labels: torch.LongTensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)

参数

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

返回

transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)

一个 transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontorch.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), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每阶段的一个输出),形状为 (batch_size, num_channels, height, width)。模型在每个阶段输出的隐藏状态(也称为特征图)。

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

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 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 model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

LeViT 模型,顶部带有图像分类头(最终隐藏状态上的一个线性层,以及蒸馏 token 的最终隐藏状态上的一个线性层),例如用于 ImageNet。 .. warning:: 此模型仅支持推理。目前不支持通过蒸馏(即与教师模型一起)进行微调。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: torch.FloatTensor | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.models.levit.modeling_levit.LevitForImageClassificationWithTeacherOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) — 对应输入图像的张量。像素值可以通过 LevitImageProcessorFast 获取。有关详细信息,请参阅 LevitImageProcessorFast.call()processor_class 使用 LevitImageProcessorFast 来处理图像)。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回的张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回一个 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 of shape (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] | None.hidden_states, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(一个用于嵌入的输出,如果模型有嵌入层,+ 每个层的输出),形状为 (batch_size, sequence_length, hidden_size)

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

transformers.LevitForImageClassificationWithTeacher 的 forward 方法,重写了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.