Transformers documentation
LeViT
该模型于 2021-04-02 在 HF papers 上发布,并于 2022-06-01 贡献至 Hugging Face Transformers。
LeViT
概述
LeViT 模型由 Ben Graham、Alaaeldin El-Nouby、Hugo Touvron、Pierre Stock、Armand Joulin、Hervé Jégou 和 Matthijs Douze 在 LeViT: Introducing Convolutions to Vision Transformers 中提出。LeViT 通过若干架构改进提升了 Vision Transformer (ViT) 的性能与效率,例如在 Transformer 中使用分辨率递减的激活图,以及引入注意力偏置以整合位置信息。
该论文的摘要如下:
我们设计了一系列图像分类架构,旨在高速推理场景下优化精度与效率之间的权衡。我们的工作利用了基于注意力的架构的最新研究成果,这类架构在高度并行的处理硬件上具有竞争力。我们重新审视了卷积神经网络广泛文献中的原则,并将其应用于 Transformer,特别是采用分辨率递减的激活图。我们还引入了注意力偏置(attention bias),这是一种在视觉 Transformer 中整合位置信息的新方法。因此,我们提出了 LeViT:一种用于快速推理图像分类的混合神经网络。我们考虑了不同硬件平台上的不同效率度量,以最好地反映广泛的应用场景。我们的大量实验从经验上验证了我们的技术选择,并表明它们适用于大多数架构。总体而言,LeViT 在速度/精度权衡方面显著优于现有的卷积神经网络和视觉 Transformer。例如,在达到 80% 的 ImageNet top-1 精度时,LeViT 在 CPU 上的速度是 EfficientNet 的 5 倍。
LeViT Architecture. Taken from the original paper. 使用技巧
- 与 ViT 相比,LeViT 模型使用了一个额外的蒸馏头,以便有效地从教师模型(在 LeViT 论文中,该教师模型是一个类似 ResNet 的模型)中学习。该蒸馏头在类似 ResNet 的模型的监督下,通过反向传播进行训练。此外,它们还从卷积神经网络中汲取灵感,使用分辨率逐渐降低的激活图来提高效率。
- 微调蒸馏模型有两种方式:(1)采用经典方式,仅在最终隐藏状态之上放置一个预测头,而不使用蒸馏头;或(2)在最终隐藏状态之上同时放置预测头和蒸馏头。在这种情况下,预测头通过预测头输出与真实标签之间的常规交叉熵进行训练,而蒸馏预测头则通过硬蒸馏(蒸馏头输出与教师模型预测标签之间的交叉熵)进行训练。在推理时,取两个头预测的平均值作为最终预测。(2)也被称为“带蒸馏的微调”,因为它依赖于一个已在下游数据集上完成微调的教师模型。就模型而言,(1)对应于 LevitForImageClassification,(2)对应于 LevitForImageClassificationWithTeacher。
- 所有发布的检查点均仅在 ImageNet-1k(也称为 ILSVRC 2012,包含 130 万张图像和 1,000 个类别)上进行了预训练和微调。未使用任何外部数据。这与原始 ViT 模型不同,后者在预训练时使用了 JFT-300M 数据集/Imagenet-21k 等外部数据。
- LeViT 的作者发布了 5 个经过训练的 LeViT 模型,您可以直接将其用于 LevitModel 或 LevitForImageClassification。 为了模拟在更大规模数据集上的训练,使用了数据增强、优化和正则化等技术 (尽管仅使用 ImageNet-1k 进行预训练)。可用的 5 个变体如下(均在 224x224 大小的图像上训练):facebook/levit-128S、facebook/levit-128、facebook/levit-192、facebook/levit-256 和 facebook/levit-384。请注意,应使用 LevitImageProcessor 来 为模型准备图像。
- LevitForImageClassificationWithTeacher 目前仅支持推理,不支持训练或微调。
- 您可以在此处查看有关推理以及在自定义数据上进行微调的演示笔记本 here(只需将 ViTImageProcessor 替换为 LevitImageProcessor,并将 ViTForImageClassification 替换为 LevitForImageClassification 或 LevitForImageClassificationWithTeacher 即可)。
资源
以下是来自 Hugging Face 官方和社区(以 🌎 标识)的资源列表,可帮助您快速上手 LeViT。
- LevitForImageClassification 受此 notebook 支持。
- 另请参阅:图像分类任务指南
如果您有兴趣提交资源以收录在此处,请随时发起 Pull Request,我们将对其进行审核!理想情况下,该资源应展示一些新内容,而不是重复现有资源。
LevitConfig
class transformers.LevitConfig
< 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 = Noneimage_size: int | list[int] | tuple[int, int] = 224num_channels: int = 3kernel_size: int = 3stride: int = 2padding: int = 1patch_size: int | list[int] | tuple[int, int] = 16hidden_sizes: list[int] | tuple[int, ...] = (128, 256, 384)num_attention_heads: list[int] | tuple[int, ...] = (4, 8, 12)depths: list[int] | tuple[int, ...] = (4, 4, 4)key_dim: list[int] | tuple[int, ...] = (16, 16, 16)drop_path_rate: int = 0mlp_ratio: list[int] | tuple[int, ...] = (2, 2, 2)attention_ratio: list[int] | tuple[int, ...] = (2, 2, 2)initializer_range: float = 0.02 )
参数
- image_size (
Union[int, list[int], tuple[int, int]],可选,默认为224) — 每张图片的尺寸(分辨率)。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - kernel_size (
int,可选,默认为3) — 卷积核的大小。 - stride (
int,可选,默认为 2) — 用于 patch embedding 初始卷积层的步幅大小。 - padding (
int,可选,默认为 1) — 用于 patch embedding 初始卷积层的填充大小。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为16) — 每个 patch 的大小(分辨率)。 - hidden_sizes (
Union[list[int], tuple[int, ...]],可选,默认为(128, 256, 384)) — 模型每个阶段的维度(隐藏层大小)。 - num_attention_heads (
Union[list[int], tuple[int, ...]],可选,默认为(4, 8, 12)) — Transformer 解码器中每个注意力层的注意力头数量。 - depths (
Union[list[int], tuple[int, ...]],可选,默认为(4, 4, 4)) — Transformer 中每一层的深度。 - key_dim (
list[int],可选,默认为[16, 16, 16]) — 每个编码器块中 key 的维度大小。 - drop_path_rate (
int,可选,默认为0) — 用于 patch 融合的 drop path 比率。 - mlp_ratio (
Union[list[int], tuple[int, ...]],可选,默认为(2, 2, 2)) — MLP 隐藏层维度与嵌入维度的比例。 - attention_ratio (
list[int],可选,默认为[2, 2, 2]) — 注意力层输出维度与输入维度的比例。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
这是用于存储 LevitModel 配置的类。它根据指定的参数实例化 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.configLevitImageProcessor
class transformers.LevitImageProcessor
< source >( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )
参数
- 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' -- 224, 'width': 224}): 应用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,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
构建一个 LevitImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~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。 - image_like_kwargs (
dict[str, Any], 可选) — 用于额外图像类输入的开发者标志,这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如,preprocess(images, masks=masks)是首选方式,但对于某些模型会导致参数优先级问题。在这种情况下,可以改用preprocess(images, image_like_inputs={"masks": masks})。 - 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
预处理一张图像或一批图像。
LevitImageProcessorPil
class transformers.LevitImageProcessorPil
< source >( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )
参数
- 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' -- 224, 'width': 224}): 应用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,可选,默认为True) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.485, 0.456, 0.406]) — 用于归一化的图像均值。仅当do_normalize设置为True时生效。 - image_std (
Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为[0.229, 0.224, 0.225]) — 用于归一化的图像标准差。仅当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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
构建一个 LevitImageProcessor 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~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。 - image_like_kwargs (
dict[str, Any], 可选) — 用于额外图像类输入的开发者标志,这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如,preprocess(images, masks=masks)是首选方式,但对于某些模型会导致参数优先级问题。在这种情况下,可以改用preprocess(images, image_like_inputs={"masks": masks})。 - 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
返回值
~image_processing_base.BatchFeature
- data (
dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。 - tensor_type (
Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
预处理一张图像或一批图像。
LevitModel
class transformers.LevitModel
< source >( config: LevitConfig )
参数
- config (LevitConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
未添加任何特定头部的裸 Levit 模型,直接输出原始隐藏状态。
该模型继承自 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.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 LevitImageProcessor 获取像素值。有关详细信息,请参阅 LevitImageProcessor.call()(processor_class使用 LevitImageProcessor 处理图像)。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
BaseModelOutputWithPoolingAndNoAttention 或 tuple(torch.Tensor)
BaseModelOutputWithPoolingAndNoAttention 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(LevitConfig)和输入而定的各种元素。
LevitModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, num_channels, height, width)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output(形状为
(batch_size, hidden_size)的torch.Tensor)— 在空间维度上执行池化操作后的最后一层隐藏状态。hidden_states (
tuple(torch.Tensor),可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, num_channels, height, width)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
LevitForImageClassification
class transformers.LevitForImageClassification
< source >( config: LevitConfig )
参数
- config (LevitConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Levit 模型,顶部带有图像分类头(在池化特征之上添加一个线性层),例如用于 ImageNet。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → ImageClassifierOutputWithNoAttention or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 LevitImageProcessor 获取像素值。有关详细信息,请参阅 LevitImageProcessor.call()(processor_class使用 LevitImageProcessor 处理图像)。 - labels(形状为
(batch_size,)的torch.LongTensor,可选)— 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。如果config.num_labels == 1,则计算回归损失(均方损失);如果config.num_labels > 1,则计算分类损失(交叉熵)。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
ImageClassifierOutputWithNoAttention 或 tuple(torch.Tensor)
一个 ImageClassifierOutputWithNoAttention 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(LevitConfig)和输入。
LevitForImageClassification 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
- loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 - logits(形状为
(batch_size, config.num_labels)的torch.Tensor)— 分类(或当 config.num_labels==1 时为回归)得分(SoftMax 之前)。 - hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个阶段输出的一个张量),形状为(batch_size, num_channels, height, width)。模型在每个阶段输出处的隐藏状态(也称为特征图)。
示例:
>>> 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
< source >( config: LevitConfig )
参数
- config (LevitConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
LeViT 模型,顶部带有图像分类头(在最终隐藏状态之上添加一个线性层,并在蒸馏令牌的最终隐藏状态之上添加一个线性层),例如用于 ImageNet。.. warning:: 该模型仅支持推理。尚不支持使用蒸馏(即使用教师模型)进行微调。
该模型继承自 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 ) → LevitForImageClassificationWithTeacherOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 LevitImageProcessor 获取像素值。有关详细信息,请参阅 LevitImageProcessor.call()(processor_class使用 LevitImageProcessor 处理图像)。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
LevitForImageClassificationWithTeacherOutput 或 tuple(torch.Tensor)
LevitForImageClassificationWithTeacherOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(LevitConfig)和输入。
LevitForImageClassificationWithTeacher 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
logits(形状为
(batch_size, config.num_labels)的torch.Tensor)— 预测分数,为cls_logits和distillation_logits的平均值。cls_logits(形状为
(batch_size, config.num_labels)的torch.Tensor)— 分类头(即位于 class token 最终隐藏状态之上的线性层)的预测分数。distillation_logits(形状为
(batch_size, config.num_labels)的torch.Tensor)— 蒸馏头的预测分数(即位于蒸馏 token 最终隐藏状态之上的线性层)。hidden_states (
tuple[torch.Tensor],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
示例:
>>> 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])
...