Transformers 文档
视觉Transformer (ViT)
并获得增强的文档体验
开始使用
视觉Transformer (ViT)
概述
Vision Transformer (ViT) 模型由 Alexey Dosovitskiy、Lucas Beyer、Alexander Kolesnikov、Dirk Weissenborn、Xiaohua Zhai、Thomas Unterthiner、Mostafa Dehghani、Matthias Minderer、Georg Heigold、Sylvain Gelly、Jakob Uszkoreit 和 Neil Houlsby 在 An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale 中提出。 这是第一篇成功地在 ImageNet 上训练 Transformer 编码器,并与熟悉的卷积架构相比取得了非常好的结果的论文。
论文的摘要如下
虽然 Transformer 架构已成为自然语言处理任务的事实标准,但其在计算机视觉中的应用仍然有限。 在视觉领域,注意力要么与卷积网络结合应用,要么用于替换卷积网络的某些组件,同时保持其整体结构不变。 我们表明,对 CNN 的依赖不是必需的,直接应用于图像块序列的纯 Transformer 可以在图像分类任务上表现良好。 当在大量数据上进行预训练并转移到多个中小型图像识别基准(ImageNet、CIFAR-100、VTAB 等)时,Vision Transformer (ViT) 与最先进的卷积网络相比,获得了出色的结果,同时训练所需的计算资源也显着减少。

继原始 Vision Transformer 之后,已经完成了一些后续工作
DeiT(数据高效图像 Transformer)由 Facebook AI 提出。 DeiT 模型是经过提炼的视觉 Transformer。 DeiT 的作者还发布了更有效训练的 ViT 模型,您可以直接将其插入 ViTModel 或 ViTForImageClassification。 有 4 种变体可用(3 种不同尺寸):facebook/deit-tiny-patch16-224、facebook/deit-small-patch16-224、facebook/deit-base-patch16-224 和 facebook/deit-base-patch16-384。 请注意,应使用 DeiTImageProcessor 以准备模型的图像。
BEiT(图像 Transformer 的 BERT 预训练)由 Microsoft Research 提出。 BEiT 模型使用受 BERT(掩码图像建模)启发并基于 VQ-VAE 的自监督方法,优于有监督预训练的视觉 Transformer。
DINO(一种用于视觉 Transformer 自监督训练的方法)由 Facebook AI 提出。 使用 DINO 方法训练的视觉 Transformer 显示出卷积模型中未见的非常有趣的特性。 它们能够分割对象,而无需经过任何训练。 DINO 检查点可以在 hub 上找到。
MAE(掩码自动编码器)由 Facebook AI 提出。 通过预训练视觉 Transformer 以重建大部分(75%)掩码补丁的像素值(使用非对称编码器-解码器架构),作者表明,这种简单的方法在微调后优于有监督的预训练。
此模型由 nielsr 贡献。 原始代码(用 JAX 编写)可以在此处找到。
请注意,我们转换了 Ross Wightman 的 timm 库中的权重,他已经将权重从 JAX 转换为 PyTorch。 功劳归于他!
使用技巧
- 为了将图像馈送到 Transformer 编码器,每个图像被分成一系列固定大小的非重叠补丁,然后进行线性嵌入。 添加一个 [CLS] 令牌以用作整个图像的表示,该表示可用于分类。 作者还添加了绝对位置嵌入,并将生成的向量序列馈送到标准 Transformer 编码器。
- 由于 Vision Transformer 期望每个图像具有相同的大小(分辨率),因此可以使用 ViTImageProcessor 来调整大小(或重新缩放)并标准化模型的图像。
- 在预训练或微调期间使用的补丁分辨率和图像分辨率都反映在每个检查点的名称中。 例如,
google/vit-base-patch16-224
指的是基本大小的架构,补丁分辨率为 16x16,微调分辨率为 224x224。 所有检查点都可以在 hub 上找到。 - 可用的检查点要么 (1) 仅在 ImageNet-21k(包含 1400 万张图像和 21k 个类别的集合)上进行预训练,要么 (2) 也在 ImageNet(也称为 ILSVRC 2012,包含 130 万张图像和 1,000 个类别的集合)上进行微调。
- Vision Transformer 使用 224x224 的分辨率进行预训练。 在微调期间,使用比预训练更高的分辨率通常是有益的 (Touvron et al., 2019), (Kolesnikov et al., 2020)。 为了以更高的分辨率进行微调,作者根据预训练位置嵌入在原始图像中的位置对其进行 2D 插值。
- 最佳结果是通过有监督的预训练获得的,这在 NLP 中并非如此。 作者还使用自监督预训练目标(即掩码补丁预测,受掩码语言建模的启发)进行了实验。 通过这种方法,较小的 ViT-B/16 模型在 ImageNet 上实现了 79.9% 的准确率,比从头开始训练提高了 2%,但仍落后于有监督预训练 4%。
使用缩放点积注意力 (SDPA)
PyTorch 包括一个原生的缩放点积注意力 (SDPA) 运算符,作为 torch.nn.functional
的一部分。 此函数包含多种实现,可以根据输入和使用的硬件应用这些实现。 有关更多信息,请参阅官方文档或 GPU 推理页面。
当实现可用时,torch>=2.1.1
默认使用 SDPA,但您也可以在 from_pretrained()
中设置 attn_implementation="sdpa"
以显式请求使用 SDPA。
from transformers import ViTForImageClassification
model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224", attn_implementation="sdpa", torch_dtype=torch.float16)
...
为了获得最佳加速,我们建议以半精度加载模型(例如 torch.float16
或 torch.bfloat16
)。
在本地基准测试(A100-40GB、PyTorch 2.3.0、OS Ubuntu 22.04)和 google/vit-base-patch16-224
模型上,我们看到了推理期间的以下加速。
批大小 | 平均推理时间 (ms),eager 模式 | 平均推理时间 (ms),sdpa 模型 | 加速,Sdpa / Eager (x) |
---|---|---|---|
1 | 7 | 6 | 1.17 |
2 | 8 | 6 | 1.33 |
4 | 8 | 6 | 1.33 |
8 | 8 | 6 | 1.33 |
资源
有关推理以及在自定义数据上微调 ViT 的演示 notebook 可以在此处找到。 官方 Hugging Face 和社区(🌎 表示)资源的列表,可帮助您开始使用 ViT。 如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核! 该资源最好展示一些新的东西,而不是重复现有资源。
ViTForImageClassification
由以下内容支持
- 一篇关于如何使用 Hugging Face Transformers 微调 ViT 以进行图像分类的博文
- 一篇关于使用 Hugging Face Transformers 和
Keras
进行图像分类的博文 - 一个关于使用 Hugging Face Transformers 微调以进行图像分类的 notebook
- 一个关于如何使用 Hugging Face Trainer 在 CIFAR-10 上微调 Vision Transformer的 notebook
- 一个关于如何使用 PyTorch Lightning 在 CIFAR-10 上微调 Vision Transformer的 notebook
⚗️ 优化
- 一篇关于如何使用 Optimum 通过量化加速 Vision Transformer (ViT)的博文
⚡️ 推理
- 一个关于 Google Brain 的 Vision Transformer (ViT) HuggingFace 版本的快速演示的 notebook
🚀 部署
- 一篇关于在 Hugging Face 中使用 TF Serving 部署 Tensorflow 视觉模型的博文
- 一篇关于在 Vertex AI 上部署 Hugging Face ViT的博文
- 一篇关于在 Kubernetes 上使用 TF Serving 部署 Hugging Face ViT的博文
ViTConfig
class transformers.ViTConfig
< source >( hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-12 image_size = 224 patch_size = 16 num_channels = 3 qkv_bias = True encoder_stride = 16 pooler_output_size = None pooler_act = 'tanh' **kwargs )
参数
- hidden_size (
int
, 可选, 默认为 768) — 编码器层和池化器层的维度大小。 - num_hidden_layers (
int
, 可选, 默认为 12) — Transformer 编码器中的隐藏层数。 - num_attention_heads (
int
, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数。 - intermediate_size (
int
, 可选, 默认为 3072) — Transformer 编码器中“中间”层(即,前馈层)的维度大小。 - hidden_act (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
,"relu"
,"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, 可选, 默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, 可选, 默认为 1e-12) — layer normalization 层使用的 epsilon 值。 - image_size (
int
, 可选, 默认为 224) — 每张图像的大小(分辨率)。 - patch_size (
int
, 可选, 默认为 16) — 每个图像块的大小(分辨率)。 - num_channels (
int
, 可选, 默认为 3) — 输入通道数。 - qkv_bias (
bool
, 可选, 默认为True
) — 是否向 queries, keys 和 values 添加偏置。 - encoder_stride (
int
, 可选, 默认为 16) — 用于掩码图像建模的解码器头中,空间分辨率的增加因子。 - pooler_output_size (
int
, 可选) — 池化器层的维度大小。如果为 None,则默认为hidden_size
。 - pooler_act (
str
, 可选, 默认为"tanh"
) — 池化器使用的激活函数。Flax 和 Pytorch 支持 ACT2FN 的键,Tensorflow 支持 https://tensorflowcn.cn/api_docs/python/tf/keras/activations 中的元素。
这是用于存储 ViTModel 配置的配置类。它用于根据指定的参数实例化 ViT 模型,定义模型架构。使用默认值实例化配置将产生与 ViT google/vit-base-patch16-224 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import ViTConfig, ViTModel
>>> # Initializing a ViT vit-base-patch16-224 style configuration
>>> configuration = ViTConfig()
>>> # Initializing a model (with random weights) from the vit-base-patch16-224 style configuration
>>> model = ViTModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
ViTFeatureExtractor
预处理图像或一批图像。
ViTImageProcessor
class transformers.ViTImageProcessor
< source >( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: typing.Optional[bool] = None **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高度,宽度)尺寸调整为指定的(size["height"], size["width"])
。可以被preprocess
方法中的do_resize
参数覆盖。 - size (
dict
, 可选, 默认为{"height" -- 224, "width": 224}
): 调整大小后输出图像的尺寸。可以被preprocess
方法中的size
参数覆盖。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BILINEAR
) — 如果调整图像大小,则使用的重采样滤波器。可以被preprocess
方法中的resample
参数覆盖。 - do_rescale (
bool
, 可选, 默认为True
) — 是否按指定的比例rescale_factor
缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果缩放图像,则使用的比例因子。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, 可选, 默认为True
) — 是否对图像进行归一化。可以被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
参数覆盖。 - do_convert_rgb (
bool
, 可选) — 是否将图像转换为 RGB 格式。
构建 ViT 图像处理器。
preprocess
< source >( 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.Dict[str, int] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.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 do_convert_rgb: typing.Optional[bool] = None )
参数
- 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_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否将图像值缩放到 [0 - 1] 之间。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为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)。
- do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。
预处理单张或批量图像。
ViTImageProcessorFast
class transformers.ViTImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
参数
- do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否将图像的 (height, width) 尺寸调整为指定的size
。可以被preprocess
方法中的do_resize
参数覆盖。 - size (
dict
, 可选, 默认为self.size
) — 调整大小后输出图像的大小。可以被preprocess
方法中的size
参数覆盖。 - default_to_square (
bool
, 可选, 默认为self.default_to_square
) — 如果 size 是整数,调整大小时是否默认为方形图像。 - resample (
PILImageResampling
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样过滤器。 仅当do_resize
设置为True
时才有效。 可以被preprocess
方法中的resample
参数覆盖。 - do_center_crop (
bool
, 可选, 默认为self.do_center_crop
) — 是否将图像中心裁剪为指定的crop_size
。可以被preprocess
方法中的do_center_crop
覆盖。 - crop_size (
Dict[str, int]
可选, 默认为self.crop_size
) — 应用center_crop
后输出图像的大小。可以被preprocess
方法中的crop_size
覆盖。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否按照指定的比例rescale_factor
缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, optional, defaults toself.rescale_factor
) — 如果要缩放图像,则使用的缩放因子。仅当do_rescale
设置为True
时才生效。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行标准化。可以被preprocess
方法中的do_normalize
参数覆盖。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, optional, defaults toself.image_mean
) — 如果要标准化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_mean
参数覆盖。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, optional, defaults toself.image_std
) — 如果要标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_std
参数覆盖。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, optional, defaults toself.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, optional, defaults toself.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, optional, defaults toself.data_format
) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, optional, defaults toself.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 (
torch.device
, optional, defaults toself.device
) — 处理图像的设备。如果未设置,则设备从输入图像推断。
构建一个快速的 ViT 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
参数
- images (
ImageInput
) — 要预处理的图像。期望是单个或一批像素值范围为 0 到 255 的图像。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, optional, defaults toself.size
) — 描述模型的最大输入尺寸。 - resample (
PILImageResampling
或InterpolationMode
, optional, defaults toself.resample
) — 如果调整图像大小,则使用的重采样过滤器。可以是枚举类型PILImageResampling
之一。仅当do_resize
设置为True
时才生效。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, optional, defaults toself.crop_size
) — 应用center_crop
后输出图像的大小。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否缩放图像。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则用于缩放图像的缩放因子。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否标准化图像。 - image_mean (
float
或List[float]
, optional, defaults toself.image_mean
) — 用于标准化的图像均值。仅当do_normalize
设置为True
时才生效。 - image_std (
float
或List[float]
, optional, defaults toself.image_std
) — 用于标准化的图像标准差。仅当do_normalize
设置为True
时才生效。 - do_convert_rgb (
bool
, optional, defaults toself.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, optional, defaults toself.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, optional, defaults toself.data_format
) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
或str
, optional, defaults toself.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 (
torch.device
, optional, defaults toself.device
) — 处理图像的设备。如果未设置,则设备从输入图像推断。
预处理单张或批量图像。
ViTModel
class transformers.ViTModel
< source >( config: ViTConfig add_pooling_layer: bool = True use_mask_token: bool = False )
参数
- config (ViTConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
不带任何特定头部输出原始隐藏状态的裸 ViT 模型 Transformer。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 ViTImageProcessor.call()。 - head_mask (
torch.FloatTensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 用于 nullify 自注意力模块中选定 head 的掩码。在[0, 1]
中选择的掩码值:- 1 表示 head 未被掩蔽,
- 0 表示 head 被掩蔽。
- output_attentions (
bool
,可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的hidden_states
。 - interpolate_pos_encoding (
bool
,可选) — 是否插值预训练的位置编码。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。 - bool_masked_pos (
torch.BoolTensor
,形状为(batch_size, num_patches)
,可选) — 布尔掩码位置。指示哪些 patch 被掩蔽 (1) 和哪些未被掩蔽 (0)。
返回值
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
transformers.modeling_outputs.BaseModelOutputWithPooling 或 torch.FloatTensor
的元组(如果传递 return_dict=False
或当 config.return_dict=False
时),包括取决于配置 (ViTConfig) 和输入的各种元素。
-
last_hidden_state (
torch.FloatTensor
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出处的隐藏状态序列。 -
pooler_output (
torch.FloatTensor
,形状为(batch_size, hidden_size)
) — 序列的第一个 token(分类 token)的最后一层隐藏状态,在通过用于辅助预训练任务的层进一步处理之后。 例如,对于 BERT 系列模型,这返回通过线性层和 tanh 激活函数处理后的分类 token。 线性层权重从预训练期间的下一句预测(分类)目标中训练得出。 -
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 之后的注意力权重,用于计算自注意力头中的加权平均值。
ViTModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, ViTModel
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> model = ViTModel.from_pretrained("google/vit-base-patch16-224-in21k")
>>> 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, 197, 768]
ViTForMaskedImageModeling
class transformers.ViTForMaskedImageModeling
< source >( config: ViTConfig )
参数
- config (ViTConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
ViT 模型,顶部带有用于掩码图像建模的解码器,如 SimMIM 中提出的那样。
请注意,我们在 示例目录 中提供了一个脚本,用于在自定义数据上预训练此模型。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = None bool_masked_pos: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.MaskedImageModelingOutput
或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 ViTImageProcessor.call()。 - head_mask (
torch.FloatTensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 用于 nullify 自注意力模块中选定 head 的掩码。在[0, 1]
中选择的掩码值:- 1 表示 head 未被掩蔽,
- 0 表示 head 被掩蔽。
- output_attentions (
bool
,可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的hidden_states
。 - interpolate_pos_encoding (
bool
,可选) — 是否插值预训练的位置编码。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。 - bool_masked_pos (
torch.BoolTensor
,形状为(batch_size, num_patches)
) — 布尔掩码位置。指示哪些 patch 被掩蔽 (1) 和哪些未被掩蔽 (0)。
返回值
transformers.modeling_outputs.MaskedImageModelingOutput
或 tuple(torch.FloatTensor)
transformers.modeling_outputs.MaskedImageModelingOutput
或 torch.FloatTensor
的元组(如果传递 return_dict=False
或当 config.return_dict=False
时),包括取决于配置 (ViTConfig) 和输入的各种元素。
- loss (
torch.FloatTensor
,形状为(1,)
,可选,当提供bool_masked_pos
时返回) — 重建损失。 - reconstruction (
torch.FloatTensor
,形状为(batch_size, num_channels, height, width)
) — 重建/完成的图像。 - 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 之后的注意力权重,用于计算自注意力头中的加权平均值。
ViTForMaskedImageModeling forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, ViTForMaskedImageModeling
>>> import torch
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> model = ViTForMaskedImageModeling.from_pretrained("google/vit-base-patch16-224-in21k")
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
>>> list(reconstructed_pixel_values.shape)
[1, 3, 224, 224]
ViTForImageClassification
class transformers.ViTForImageClassification
< source >( config: ViTConfig )
参数
- config (ViTConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
ViT 模型转换器,顶部带有一个图像分类头([CLS] 标记的最终隐藏状态之上的线性层),例如用于 ImageNet。
请注意,可以通过在模型的前向传播中将 interpolate_pos_encoding
设置为 True
,在比 ViT 训练时更高分辨率的图像上微调 ViT。这将把预训练的位置嵌入插值到更高的分辨率。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: 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
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 ViTImageProcessor.call()。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的torch.FloatTensor
, 可选) — 用于置空自注意力模块中选定头的掩码。掩码值在[0, 1]
中选择:- 1 表示头是未被掩蔽的,
- 0 表示头是被掩蔽的。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回的张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回的张量下的hidden_states
。 - interpolate_pos_encoding (
bool
, 可选) — 是否对预训练的位置编码进行插值。 - 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
时),其中包含各种元素,具体取决于配置 (ViTConfig) 和输入。
-
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 之后的注意力权重,用于计算自注意力头中的加权平均值。
ViTForImageClassification 的前向传播方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, ViTForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
>>> model = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
Egyptian cat
TFViTModel
class transformers.TFViTModel
< source >( config: ViTConfig *inputs add_pooling_layer = True **kwargs )
参数
- config (ViTConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
裸 ViT 模型转换器,输出原始隐藏状态,顶部没有任何特定的头。
此模型继承自 TFPreTrainedModel。查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档,了解与常规用法和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种格式作为输入
- 将所有输入作为关键字参数(如 PyTorch 模型),或者
- 将所有输入作为第一个位置参数中的列表、元组或字典。
支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit()
等方法时,事情应该“正常工作” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如在使用 Keras Functional
API 创建您自己的层或模型时,可以使用以下三种可能性来收集第一个位置参数中的所有输入张量
- 仅包含
pixel_values
且不包含其他内容的单个张量:model(pixel_values)
- 一个长度可变的列表,其中包含一个或多个输入张量,顺序与文档字符串中给出的顺序相同:
model([pixel_values, attention_mask])
或model([pixel_values, attention_mask, token_type_ids])
- 一个字典,其中包含一个或多个与文档字符串中给出的输入名称关联的输入张量:
model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})
请注意,当使用 子类化 创建模型和层时,您无需担心这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< source >( pixel_values: TFModelInputType | None = None head_mask: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None interpolate_pos_encoding: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) → transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或 tuple(tf.Tensor)
参数
- pixel_values (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
或Dict[str, np.ndarray]
并且每个示例必须具有形状(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 ViTImageProcessor.call()。 - head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的np.ndarray
或tf.Tensor
, 可选) — 用于置空自注意力模块中选定头的掩码。掩码值在[0, 1]
中选择:- 1 表示头是未被掩蔽的,
- 0 表示头是被掩蔽的。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回的张量下的attentions
。 此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回的张量下的hidden_states
。 此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - interpolate_pos_encoding (
bool
, 可选) — 是否插值预训练的位置编码。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是一个普通的元组。此参数可以在 eager 模式下使用,在 graph 模式下,该值将始终设置为 True。 - training (
bool
, 可选, 默认为 `False“) — 是否在训练模式下使用模型(某些模块,如 dropout 模块,在训练和评估之间有不同的行为)。
返回值
transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling or tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFBaseModelOutputWithPooling 或一个 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含取决于配置 (ViTConfig) 和输入的各种元素。
-
last_hidden_state (
tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出处的隐藏状态序列。 -
pooler_output (
tf.Tensor
,形状为(batch_size, hidden_size)
) — 序列的第一个 token(分类 token)的最后一层隐藏状态,通过一个线性层和一个 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 之后的注意力权重,用于计算自注意力头中的加权平均值。
The TFViTModel 的 forward 方法,重写了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFViTModel
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> model = TFViTModel.from_pretrained("google/vit-base-patch16-224-in21k")
>>> inputs = image_processor(image, return_tensors="tf")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 197, 768]
TFViTForImageClassification
类 transformers.TFViTForImageClassification
< 源码 >( config: ViTConfig *inputs **kwargs )
参数
- config (ViTConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
ViT 模型转换器,顶部带有一个图像分类头([CLS] 标记的最终隐藏状态之上的线性层),例如用于 ImageNet。
请注意,可以通过在模型的前向传播中将 interpolate_pos_encoding
设置为 True
,在比 ViT 训练时更高分辨率的图像上微调 ViT。这将把预训练的位置嵌入插值到更高的分辨率。
此模型继承自 TFPreTrainedModel。查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档,了解与常规用法和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种格式作为输入
- 将所有输入作为关键字参数(如 PyTorch 模型),或者
- 将所有输入作为第一个位置参数中的列表、元组或字典。
支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit()
等方法时,事情应该“正常工作” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如在使用 Keras Functional
API 创建您自己的层或模型时,可以使用以下三种可能性来收集第一个位置参数中的所有输入张量
- 仅包含
pixel_values
且不包含其他内容的单个张量:model(pixel_values)
- 一个长度可变的列表,其中包含一个或多个输入张量,顺序与文档字符串中给出的顺序相同:
model([pixel_values, attention_mask])
或model([pixel_values, attention_mask, token_type_ids])
- 一个字典,其中包含一个或多个与文档字符串中给出的输入名称关联的输入张量:
model({"pixel_values": pixel_values, "token_type_ids": token_type_ids})
请注意,当使用 子类化 创建模型和层时,您无需担心这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< 源码 >( pixel_values: TFModelInputType | None = None head_mask: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None interpolate_pos_encoding: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFSequenceClassifierOutput or tuple(tf.Tensor)
参数
- pixel_values (
np.ndarray
,tf.Tensor
,List[tf.Tensor]
`Dict[str, tf.Tensor]
或Dict[str, np.ndarray]
并且每个示例都必须具有形状(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 ViTImageProcessor.call()。 - head_mask (
np.ndarray
或tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使自注意力模块的选定 head 无效的掩码。掩码值在[0, 1]
中选择:- 1 表示 head 未被掩盖,
- 0 表示 head 被掩盖。
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的 attention tensors。有关更多详细信息,请参阅返回的 tensors 下的attentions
。此参数只能在 eager 模式下使用,在 graph 模式下,将使用 config 中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。此参数只能在 eager 模式下使用,在 graph 模式下,将使用 config 中的值。 - interpolate_pos_encoding (
bool
, 可选) — 是否插值预训练的位置编码。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是一个普通的元组。此参数可以在 eager 模式下使用,在 graph 模式下,该值将始终设置为 True。 - training (
bool
, 可选, 默认为 `False“) — 是否在训练模式下使用模型(某些模块,如 dropout 模块,在训练和评估之间有不同的行为)。 - labels (
tf.Tensor
或np.ndarray
,形状为(batch_size,)
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
中。如果config.num_labels == 1
,则计算回归损失(均方误差损失);如果config.num_labels > 1
,则计算分类损失(交叉熵损失)。
返回值
transformers.modeling_tf_outputs.TFSequenceClassifierOutput or tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFSequenceClassifierOutput 或一个 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含取决于配置 (ViTConfig) 和输入的各种元素。
-
loss (
tf.Tensor
,形状为(batch_size, )
, 可选, 当提供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, sequence_length, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
The TFViTForImageClassification 的 forward 方法,重写了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, TFViTForImageClassification
>>> import tensorflow as tf
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
>>> model = TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224")
>>> 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])
Egyptian cat
FlaxVitModel
类 transformers.FlaxViTModel
< 源码 >( config: ViTConfig input_shape = None seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (ViTConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
- dtype (
jax.numpy.dtype
, 可选, 默认为jax.numpy.float32
) — 计算的数据类型。可以是jax.numpy.float32
、jax.numpy.float16
(在 GPU 上) 和jax.numpy.bfloat16
(在 TPU 上) 之一。这可以用于在 GPU 或 TPU 上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定计算的 dtype,并不影响模型参数的 dtype。
裸 ViT 模型转换器,输出原始隐藏状态,顶部没有任何特定的头。
此模型继承自 FlaxPreTrainedModel。查看超类文档,了解库为其所有模型实现的通用方法(例如,从 PyTorch 模型下载、保存和转换权重)
此模型也是 flax.linen.Module 的子类。将其用作常规的 Flax linen Module,并参阅 Flax 文档,了解与通用用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< 源码 >( pixel_values params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPooling or tuple(torch.FloatTensor)
返回值
transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPooling or tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPooling 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含取决于配置 (<class 'transformers.models.vit.configuration_vit.ViTConfig'>
) 和输入的各种元素。
-
last_hidden_state (
jnp.ndarray
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出处的隐藏状态序列。 -
pooler_output (
jnp.ndarray
,形状为(batch_size, hidden_size)
) — 序列的第一个 token(分类 token)的最后一层隐藏状态,通过一个线性层和一个 Tanh 激活函数进一步处理。线性层权重在预训练期间从下一句预测(分类)目标中训练。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
元组(一个用于嵌入的输出 + 一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态,加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
The FlaxViTPreTrainedModel
的 forward 方法,重写了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, FlaxViTModel
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
>>> model = FlaxViTModel.from_pretrained("google/vit-base-patch16-224-in21k")
>>> inputs = image_processor(images=image, return_tensors="np")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
FlaxViTForImageClassification
class transformers.FlaxViTForImageClassification
< source >( config: ViTConfig input_shape = None seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (ViTConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
- dtype (
jax.numpy.dtype
, 可选, 默认为jax.numpy.float32
) — 计算的数据类型。可以是jax.numpy.float32
,jax.numpy.float16
(在 GPU 上) 和jax.numpy.bfloat16
(在 TPU 上) 之一。这可以用于在 GPU 或 TPU 上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定计算的 dtype,不影响模型参数的 dtype。
ViT 模型转换器,顶部带有一个图像分类头([CLS] 标记的最终隐藏状态之上的线性层),例如用于 ImageNet。
此模型继承自 FlaxPreTrainedModel。查看超类文档,了解库为其所有模型实现的通用方法(例如,从 PyTorch 模型下载、保存和转换权重)
此模型也是 flax.linen.Module 的子类。将其用作常规的 Flax linen Module,并参阅 Flax 文档,了解与通用用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( pixel_values params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput or tuple(torch.FloatTensor)
返回值
transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput or tuple(torch.FloatTensor)
A transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput 或 torch.FloatTensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.vit.configuration_vit.ViTConfig'>
) 和输入。
-
logits (
jnp.ndarray
形状为(batch_size, config.num_labels)
) — 分类(或回归,如果 config.num_labels==1)分数(在 SoftMax 之前)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
元组(一个用于嵌入的输出 + 一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态,加上初始嵌入输出。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每一层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
The FlaxViTPreTrainedModel
的 forward 方法,重写了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, FlaxViTForImageClassification
>>> from PIL import Image
>>> import jax
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
>>> model = FlaxViTForImageClassification.from_pretrained("google/vit-base-patch16-224")
>>> inputs = image_processor(images=image, return_tensors="np")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_class_idx = jax.numpy.argmax(logits, axis=-1)
>>> print("Predicted class:", model.config.id2label[predicted_class_idx.item()])