Transformers 文档
EfficientFormer
并获得增强的文档体验
开始使用
EfficientFormer
此模型仅处于维护模式,我们不接受任何更改其代码的新PR。如果您在运行此模型时遇到任何问题,请重新安装支持此模型的最新版本:v4.40.2。您可以通过运行以下命令来实现:pip install -U transformers==4.40.2。
概述
EfficientFormer模型由Yanyu Li、Geng Yuan、Yang Wen、Eric Hu、Georgios Evangelidis、Sergey Tulyakov、Yanzhi Wang、Jian Ren在EfficientFormer:MobileNet速度的视觉Transformer中提出。EfficientFormer提出了一种维度一致的纯Transformer,可以在移动设备上运行,用于图像分类、目标检测和语义分割等密集预测任务。
论文摘要如下:
视觉Transformer(ViT)在计算机视觉任务中取得了快速进展,在各种基准测试中取得了令人鼓舞的结果。然而,由于参数数量庞大和模型设计(例如,注意力机制),基于ViT的模型通常比轻量级卷积网络慢数倍。因此,将ViT部署到实时应用中尤其具有挑战性,特别是在移动设备等资源受限的硬件上。最近的努力试图通过网络架构搜索或与MobileNet块的混合设计来降低ViT的计算复杂度,但推理速度仍不尽如人意。这导致了一个重要问题:Transformer能否像MobileNet一样快速运行并获得高性能?为了回答这个问题,我们首先重新审视了基于ViT的模型中使用的网络架构和运算符,并发现了低效的设计。然后,我们引入了一种维度一致的纯Transformer(不带MobileNet块)作为设计范例。最后,我们进行了延迟驱动的精简,得到了一系列最终模型,称为EfficientFormer。大量的实验表明EfficientFormer在移动设备上的性能和速度方面具有优越性。我们最快的模型EfficientFormer-L1在ImageNet-1K上实现了79.2%的top-1准确率,在iPhone 12上(使用CoreML编译)仅有1.6毫秒的推理延迟,其运行速度与MobileNetV2×1.4(1.6毫秒,74.7%的top-1)一样快,我们最大的模型EfficientFormer-L7在仅7.0毫秒的延迟下获得了83.3%的准确率。我们的工作证明,设计合理的Transformer可以在移动设备上实现极低的延迟,同时保持高性能。
该模型由novice03和Bearnardd贡献。原始代码可以在这里找到。此模型的TensorFlow版本由D-Roberts添加。
文档资源
EfficientFormerConfig
类 transformers.EfficientFormerConfig
< 源 >( depths: list = [3, 2, 6, 4] hidden_sizes: list = [48, 96, 224, 448] downsamples: list = [True, True, True, True] dim: int = 448 key_dim: int = 32 attention_ratio: int = 4 resolution: int = 7 num_hidden_layers: int = 5 num_attention_heads: int = 8 mlp_expansion_ratio: int = 4 hidden_dropout_prob: float = 0.0 patch_size: int = 16 num_channels: int = 3 pool_size: int = 3 downsample_patch_size: int = 3 downsample_stride: int = 2 downsample_pad: int = 1 drop_path_rate: float = 0.0 num_meta3d_blocks: int = 1 distillation: bool = True use_layer_scale: bool = True layer_scale_init_value: float = 1e-05 hidden_act: str = 'gelu' initializer_range: float = 0.02 layer_norm_eps: float = 1e-12 image_size: int = 224 batch_norm_eps: float = 1e-05 **kwargs )
参数
- depths (
List(int), 可选, 默认为[3, 2, 6, 4]) — 每个阶段的深度。 - hidden_sizes (
List(int), 可选, 默认为[48, 96, 224, 448]) — 每个阶段的维度。 - downsamples (
List(bool), 可选, 默认为[True, True, True, True]) — 是否在两个阶段之间对输入进行下采样。 - dim (
int, 可选, 默认为 448) — Meta3D层中的通道数 - key_dim (
int, 可选, 默认为 32) — meta3D块中键的大小。 - attention_ratio (
int, 可选, 默认为 4) — MSHA块中查询和值维度与键维度的比率 - resolution (
int, 可选, 默认为 7) — 每个块的大小。 - num_hidden_layers (
int, 可选, 默认为 5) — Transformer编码器中的隐藏层数。 - num_attention_heads (
int, 可选, 默认为 8) — 3D MetaBlock中每个注意力层中的注意力头数。 - mlp_expansion_ratio (
int, 可选, 默认为 4) — MLP隐藏维度与其输入维度之比。 - hidden_dropout_prob (
float, 可选, 默认为 0.1) — 嵌入和编码器中所有全连接层的dropout概率。 - patch_size (
int, 可选, 默认为 16) — 每个补丁的大小(分辨率)。 - num_channels (
int, 可选, 默认为 3) — 输入通道数。 - pool_size (
int, 可选, 默认为 3) — 池化层的内核大小。 - downsample_patch_size (
int, 可选, 默认为 3) — 下采样层中补丁的大小。 - downsample_stride (
int, 可选, 默认为 2) — 下采样层中卷积核的步长。 - downsample_pad (
int, 可选, 默认为 1) — 下采样层中的填充。 - drop_path_rate (
int, 可选, 默认为 0) — DropPath中dropout概率增加的速率。 - num_meta3d_blocks (
int, 可选, 默认为 1) — 最后一个阶段中3D MetaBlock的数量。 - distillation (
bool, 可选, 默认为True) — 是否添加蒸馏头。 - use_layer_scale (
bool, 可选, 默认为True) — 是否缩放token mixer的输出。 - layer_scale_init_value (
float, 可选, 默认为 1e-5) — token mixer输出的缩放因子。 - hidden_act (
str或function, 可选, 默认为"gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"、"relu"、"selu"和"gelu_new"。 - initializer_range (
float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。 - layer_norm_eps (
float, 可选, 默认为 1e-12) — 层归一化层使用的epsilon。 - image_size (
int, 可选, 默认为224) — 每张图片的大小(分辨率)。
这是用于存储EfficientFormerModel配置的配置类。它用于根据指定的参数实例化一个EfficientFormer模型,定义模型架构。使用默认值实例化配置将产生与EfficientFormer snap-research/efficientformer-l1架构类似的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。有关更多信息,请参阅PretrainedConfig的文档。
示例
>>> from transformers import EfficientFormerConfig, EfficientFormerModel
>>> # Initializing a EfficientFormer efficientformer-l1 style configuration
>>> configuration = EfficientFormerConfig()
>>> # Initializing a EfficientFormerModel (with random weights) from the efficientformer-l3 style configuration
>>> model = EfficientFormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configEfficientFormer图像处理器
类 transformers.EfficientFormerImageProcessor
< 源 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BICUBIC: 3> do_center_crop: bool = True do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 crop_size: typing.Optional[dict[str, int]] = None do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None **kwargs )
参数
- do_resize (
bool, 可选, 默认为True) — 是否将图像的(高度,宽度)尺寸调整为指定的(size["height"], size["width"])。可以通过preprocess方法中的do_resize参数覆盖。 - size (
dict, 可选, 默认为{"height": 224, "width": 224}):调整大小后输出图像的尺寸。可以通过preprocess方法中的size参数覆盖。 - resample (
PILImageResampling, 可选, 默认为PILImageResampling.BILINEAR) — 如果调整图像大小,使用的重采样滤波器。可以通过preprocess方法中的resample参数覆盖。 - do_center_crop (
bool, 可选, 默认为True) — 是否将图像中心裁剪为指定的crop_size。可以通过preprocess方法中的do_center_crop覆盖。 - crop_size (
dict[str, int]可选, 默认为 224) — 应用center_crop后输出图像的尺寸。可以通过preprocess方法中的crop_size覆盖。 - do_rescale (
bool, 可选, 默认为True) — 是否按指定的rescale_factor缩放图像。可以通过preprocess方法中的do_rescale参数覆盖。 - rescale_factor (
int或float, 可选, 默认为1/255) — 如果缩放图像,使用的缩放因子。可以通过preprocess方法中的rescale_factor参数覆盖。 - do_normalize — 是否对图像进行归一化。可以通过
preprocess方法中的do_normalize参数覆盖。 - image_mean (
float或list[float], 可选, 默认为IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,使用的均值。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过preprocess方法中的image_mean参数覆盖。 - image_std (
float或list[float], 可选, 默认为IMAGENET_STANDARD_STD) — 如果对图像进行归一化,使用的标准差。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过preprocess方法中的image_std参数覆盖。
构建EfficientFormer图像处理器。
预处理
< 源 >( 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[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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )
参数
- images (
ImageInput) — 要预处理的图像。期望单个或批量图像,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False。 - do_resize (
bool, 可选, 默认为self.do_resize) — 是否调整图像大小。 - size (
dict[str, int], 可选, 默认为self.size) — 字典格式为{"height": h, "width": w},指定调整大小后输出图像的尺寸。 - resample (
PILImageResampling过滤器, 可选, 默认为self.resample) — 如果调整图像大小,则使用的PILImageResampling过滤器,例如PILImageResampling.BILINEAR。仅当do_resize设置为True时才生效。 - do_center_crop (
bool, 可选, 默认为self.do_center_crop) — 是否对图像进行中心裁剪。 - do_rescale (
bool, 可选, 默认为self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。 - rescale_factor (
float, 可选, 默认为self.rescale_factor) — 如果do_rescale设置为True,则按此缩放因子对图像进行缩放。 - crop_size (
dict[str, int], 可选, 默认为self.crop_size) — 中心裁剪的尺寸。仅当do_center_crop设置为True时才生效。 - do_normalize (
bool, 可选, 默认为self.do_normalize) — 是否对图像进行归一化。 - image_mean (
float或list[float], 可选, 默认为self.image_mean) — 如果do_normalize设置为True,则使用的图像均值。 - image_std (
float或list[float], 可选, 默认为self.image_std) — 如果do_normalize设置为True,则使用的图像标准差。 - return_tensors (
str或TensorType, 可选) — 返回张量的类型。可以是以下之一:- 未设置:返回
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 (
ChannelDimension或str, 可选, 默认为ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。"channels_last"或ChannelDimension.LAST:图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension或str, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"或ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。"channels_last"或ChannelDimension.LAST:图像格式为 (height, width, num_channels)。"none"或ChannelDimension.NONE:图像格式为 (height, width)。
预处理一张或一批图像。
EfficientFormer模型
class transformers.EfficientFormerModel
< 来源 >( config: EfficientFormerConfig )
参数
- config (EfficientFormerConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。
EfficientFormer 模型变压器,输出原始隐藏状态,顶部没有任何特定头部。此模型是 PyTorch nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。
前向传播
< 来源 >( pixel_values: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)的torch.FloatTensor) — 像素值。像素值可以通过 ViTImageProcessor 获取。有关详细信息,请参阅 ViTImageProcessor.preprocess()。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是纯元组。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或 config.return_dict=False),包含根据配置 (EfficientFormerConfig) 和输入而定的各种元素。
-
last_hidden_state (
torch.FloatTensor, 形状为(batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (形状为
(batch_size, hidden_size)的torch.FloatTensor) — 序列中第一个标记(分类标记)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 家族模型,这会在经过线性层和 tanh 激活函数处理后返回分类标记。线性层权重在预训练期间通过下一句预测(分类)目标进行训练。 -
hidden_states (
tuple(torch.FloatTensor), 可选, 当传递output_hidden_states=True或config.output_hidden_states=True时返回) —torch.FloatTensor元组(如果模型有嵌入层,则一个用于嵌入层的输出,加上每个层的一个输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), 可选, 当传递output_attentions=True或config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
EfficientFormerModel 的前向传播方法,重写了 __call__ 特殊方法。
虽然必须在此函数中定义前向传播的配方,但之后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, EfficientFormerModel
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("snap-research/efficientformer-l1-300")
>>> model = EfficientFormerModel.from_pretrained("snap-research/efficientformer-l1-300")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 49, 448]EfficientFormerForImageClassification
class transformers.EfficientFormerForImageClassification
< 来源 >( config: EfficientFormerConfig )
参数
- config (EfficientFormerConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。
EfficientFormer 模型变压器,顶部带有图像分类头部(在 [CLS] 标记的最终隐藏状态顶部的一个线性层),例如用于 ImageNet。
此模型是 PyTorch nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。
前向传播
< 来源 >( pixel_values: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)的torch.FloatTensor) — 像素值。像素值可以通过 ViTImageProcessor 获取。有关详细信息,请参阅 ViTImageProcessor.preprocess()。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是纯元组。 - labels (形状为
(batch_size,)的torch.LongTensor, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]之间。如果config.num_labels == 1,则计算回归损失(均方损失),如果config.num_labels > 1,则计算分类损失(交叉熵)。
返回
transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或 config.return_dict=False),包含根据配置 (EfficientFormerConfig) 和输入而定的各种元素。
-
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, sequence_length, hidden_size)。模型在每个阶段输出的隐藏状态(也称为特征图)。 -
attentions (
tuple(torch.FloatTensor), 可选, 当传递output_attentions=True或config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, patch_size, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
EfficientFormerForImageClassification 的前向传播方法,重写了 __call__ 特殊方法。
虽然必须在此函数中定义前向传播的配方,但之后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, EfficientFormerForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("snap-research/efficientformer-l1-300")
>>> model = EfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300")
>>> 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])
Egyptian catEfficientFormerForImageClassificationWithTeacher
class transformers.EfficientFormerForImageClassificationWithTeacher
< 来源 >( config: EfficientFormerConfig )
参数
- config (EfficientFormerConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。
EfficientFormer 模型变压器,顶部带有图像分类头部(在 [CLS] 标记的最终隐藏状态顶部的一个线性层和在蒸馏标记的最终隐藏状态顶部的一个线性层),例如用于 ImageNet。
此模型仅支持推理。目前不支持带蒸馏的微调(即带教师)。
此模型是 PyTorch nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。
前向传播
< 来源 >( pixel_values: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.deprecated.efficientformer.modeling_efficientformer.EfficientFormerForImageClassificationWithTeacherOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)的torch.FloatTensor) — 像素值。像素值可以通过 ViTImageProcessor 获取。有关详细信息,请参阅 ViTImageProcessor.preprocess()。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是纯元组。
返回
transformers.models.deprecated.efficientformer.modeling_efficientformer.EfficientFormerForImageClassificationWithTeacherOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.deprecated.efficientformer.modeling_efficientformer.EfficientFormerForImageClassificationWithTeacherOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或 config.return_dict=False),包含根据配置 (EfficientFormerConfig) 和输入而定的各种元素。
- logits (形状为
(batch_size, config.num_labels)的torch.FloatTensor) — 作为 cls_logits 和蒸馏 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)。模型在每个层输出的隐藏状态,加上初始嵌入输出。 - attentions (
tuple(torch.FloatTensor), 可选, 当传递output_attentions=True或config.output_attentions=True时返回) —torch.FloatTensor元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均。
EfficientFormerForImageClassificationWithTeacher 的前向传播方法,重写了 __call__ 特殊方法。
虽然必须在此函数中定义前向传播的配方,但之后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, EfficientFormerForImageClassificationWithTeacher
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("snap-research/efficientformer-l1-300")
>>> model = EfficientFormerForImageClassificationWithTeacher.from_pretrained("snap-research/efficientformer-l1-300")
>>> 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])
Egyptian catTFEfficientFormerModel
class transformers.TFEfficientFormerModel
< 来源 >( config: EfficientFormerConfig **kwargs )
参数
- config (EfficientFormerConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。
EfficientFormer 模型变压器,输出原始隐藏状态,顶部没有任何特定头部。此模型是 TensorFlow keras.layers.Layer。将其作为常规 TensorFlow 模块使用,并参考 TensorFlow 文档中所有与一般用法和行为相关的事项。
调用
< 来源 >( pixel_values: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None training: bool = False ) → transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
参数
- pixel_values ((形状为
(batch_size, num_channels, height, width)的tf.Tensor) — 像素值。像素值可以通过 AutoImageProcessor 获取。有关详细信息,请参阅 EfficientFormerImageProcessor.call()。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是纯元组。
返回
transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或一个 tf.Tensor 元组(如果传递了 return_dict=False 或 config.return_dict=False),包含根据配置 (EfficientFormerConfig) 和输入而定的各种元素。
-
last_hidden_state (
tf.Tensorof shape(batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (形状为
(batch_size, hidden_size)的tf.Tensor) — 序列中第一个标记(分类标记)的最后一层隐藏状态,经由线性层和 Tanh 激活函数进一步处理。线性层权重在预训练期间通过下一句预测(分类)目标进行训练。此输出通常不是输入语义内容的良好摘要,通常最好对整个输入序列的隐藏状态进行平均或池化。
-
hidden_states (
tuple(tf.Tensor), 可选, 当传入output_hidden_states=True或config.output_hidden_states=True时返回) —tf.Tensor的元组(一个用于嵌入层输出 + 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor), 可选, 当传入output_attentions=True或config.output_attentions=True时返回) —tf.Tensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFEfficientFormerModel 的前向传播方法,覆盖了 __call__ 特殊方法。
虽然必须在此函数中定义前向传播的配方,但之后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFEfficientFormerModel
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("snap-research/efficientformer-l1-300")
>>> model = TFEfficientFormerModel.from_pretrained("snap-research/efficientformer-l1-300")
>>> inputs = image_processor(image, return_tensors="tf")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 49, 448]TFEfficientFormerForImageClassification
class transformers.TFEfficientFormerForImageClassification
< source >( config: EfficientFormerConfig )
参数
- config (EfficientFormerConfig) — 模型配置类,包含模型的所有参数。用配置文件初始化不会加载与模型关联的权重,只会加载配置。要加载模型权重,请查看 from_pretrained() 方法。
EfficientFormer 模型转换器,在池化后的最后一个隐藏状态之上带有一个图像分类头,例如用于 ImageNet。
此模型是一个 TensorFlow keras.layers.Layer。将其用作常规的 TensorFlow 模块,并参考 TensorFlow 文档了解所有与通用用法和行为相关的事项。
调用
< source >( pixel_values: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None labels: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None training: bool = False ) → transformers.modeling_tf_outputs.TFImageClassifierOutput 或 tuple(tf.Tensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)的tf.Tensor) — 像素值。像素值可以使用 AutoImageProcessor 获取。详情请参阅 EfficientFormerImageProcessor.call()。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。更多详情请参阅返回张量下的attentions。 - output_hidden_states (
bool, 可选) — 是否返回所有层的隐藏状态。更多详情请参阅返回张量下的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而非普通元组。 - labels (形状为
(batch_size,)的tf.Tensor, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。如果config.num_labels == 1,则计算回归损失(均方损失),如果config.num_labels > 1,则计算分类损失(交叉熵)。
返回
transformers.modeling_tf_outputs.TFImageClassifierOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFImageClassifierOutput 或一个 tf.Tensor 的元组(如果传入 return_dict=False 或当 config.return_dict=False 时),根据配置(EfficientFormerConfig)和输入包含各种元素。
-
loss (形状为
(1,)的tf.Tensor,可选,当提供labels时返回) — 分类(如果 config.num_labels==1,则为回归)损失。 -
logits (
tf.Tensor,形状为(batch_size, config.num_labels)) — 分类(或回归,如果 config.num_labels==1)分数(SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor), 可选, 当传入output_hidden_states=True或config.output_hidden_states=True时返回) —tf.Tensor的元组(一个用于嵌入层输出,如果模型有嵌入层,+ 一个用于每个阶段的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个阶段输出的隐藏状态(也称为特征图)。 -
attentions (
tuple(tf.Tensor), 可选, 当传入output_attentions=True或config.output_attentions=True时返回) —tf.Tensor的元组(每个层一个),形状为(batch_size, num_heads, patch_size, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
TFEfficientFormerForImageClassification 的前向传播方法,覆盖了 __call__ 特殊方法。
虽然必须在此函数中定义前向传播的配方,但之后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFEfficientFormerForImageClassification
>>> import tensorflow as tf
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image"))
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("snap-research/efficientformer-l1-300")
>>> model = TFEfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300")
>>> inputs = image_processor(image, return_tensors="tf")
>>> logits = model(**inputs).logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = int(tf.math.argmax(logits, axis=-1))
>>> print(model.config.id2label[predicted_label])
LABEL_281TFEfficientFormerForImageClassificationWithTeacher
class transformers.TFEfficientFormerForImageClassificationWithTeacher
< source >( config: EfficientFormerConfig )
参数
- config (EfficientFormerConfig) — 模型配置类,包含模型的所有参数。用配置文件初始化不会加载与模型关联的权重,只会加载配置。要加载模型权重,请查看 from_pretrained() 方法。
EfficientFormer 模型转换器,在顶部带有图像分类头(在最终隐藏状态之上有一个线性层,在蒸馏标记的最终隐藏状态之上有一个线性层),例如用于 ImageNet。
.. 警告:: 此模型仅支持推理。尚不支持带有蒸馏的微调(即带有教师模型)。
此模型是一个 TensorFlow keras.layers.Layer。将其用作常规的 TensorFlow 模块,并参考 TensorFlow 文档了解所有与通用用法和行为相关的事项。
调用
< source >( pixel_values: typing.Optional[tensorflow.python.framework.tensor.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None training: bool = False ) → transformers.models.deprecated.efficientformer.modeling_tf_efficientformer.TFEfficientFormerForImageClassificationWithTeacherOutput 或 tuple(tf.Tensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)的tf.Tensor) — 像素值。像素值可以使用 AutoImageProcessor 获取。详情请参阅 EfficientFormerImageProcessor.call()。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。更多详情请参阅返回张量下的attentions。 - output_hidden_states (
bool, 可选) — 是否返回所有层的隐藏状态。更多详情请参阅返回张量下的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而非普通元组。
返回
transformers.models.deprecated.efficientformer.modeling_tf_efficientformer.TFEfficientFormerForImageClassificationWithTeacherOutput 或 tuple(tf.Tensor)
一个 transformers.models.deprecated.efficientformer.modeling_tf_efficientformer.TFEfficientFormerForImageClassificationWithTeacherOutput 或一个 tf.Tensor 的元组(如果传入 return_dict=False 或当 config.return_dict=False 时),根据配置(EfficientFormerConfig)和输入包含各种元素。
TFEfficientFormerForImageClassificationWithTeacher 的前向传播方法,覆盖了 __call__ 特殊方法。
虽然必须在此函数中定义前向传播的配方,但之后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
- 输出类型为 EfficientFormerForImageClassificationWithTeacher。 logits (形状为
(batch_size, config.num_labels)的tf.Tensor) — 作为 cls_logits 和蒸馏 logits 平均值的预测分数。 cls_logits (形状为(batch_size, config.num_labels)的tf.Tensor) — 分类头(即在类标记的最终隐藏状态之上的线性层)的预测分数。 distillation_logits (形状为(batch_size, config.num_labels)的tf.Tensor) — 蒸馏头(即在蒸馏标记的最终隐藏状态之上的线性层)的预测分数。 hidden_states (tuple(tf.Tensor), 可选, 当传入output_hidden_states=True或config.output_hidden_states=True时返回) —tf.Tensor的元组(一个用于嵌入层输出 + 一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态加上初始嵌入输出。 attentions (tuple(tf.Tensor), 可选, 当传入output_attentions=True或config.output_attentions=True时返回) —tf.Tensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
示例
>>> from transformers import AutoImageProcessor, TFEfficientFormerForImageClassificationWithTeacher
>>> import tensorflow as tf
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image"))
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("snap-research/efficientformer-l1-300")
>>> model = TFEfficientFormerForImageClassificationWithTeacher.from_pretrained("snap-research/efficientformer-l1-300")
>>> inputs = image_processor(image, return_tensors="tf")
>>> logits = model(**inputs).logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = int(tf.math.argmax(logits, axis=-1))
>>> print(model.config.id2label[predicted_label])
LABEL_281