Transformers 文档
Vision Transformer (ViT)
并获得增强的文档体验
开始使用
该模型于 2020-10-22 发布,并于 2021-04-01 添加到 Hugging Face Transformers。
Vision Transformer (ViT)
Vision Transformer (ViT) 是一种适用于计算机视觉任务的 Transformer 模型。图像被分割成固定大小的小块,这些小块像自然语言处理中的词语一样被视为一个 token 序列。与卷积架构相比,ViT 在预训练时所需的资源更少,并且其在大数据集上的性能可以迁移到较小规模的下游任务中。
您可以在 Google 组织下找到所有原始的 ViT 检查点。
点击右侧边栏的 ViT 模型,了解更多关于如何将 ViT 应用于不同计算机视觉任务的示例。
下面的示例演示了如何使用 Pipeline 或 AutoModel 类来对图像进行分类。
import torch
from transformers import pipeline
pipeline = pipeline(
task="image-classification",
model="google/vit-base-patch16-224",
dtype=torch.float16,
device=0
)
pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")注意事项
- 监督预训练可以获得最佳结果,并且在微调时,使用分辨率高于 224x224 的图像可能会更好。
- 使用 ViTImageProcessorFast 来调整(或重缩放)和归一化图像以达到预期尺寸。
- 补丁和图像的分辨率体现在检查点名称中。例如,google/vit-base-patch16-224,代表一个 base-sized 架构,其补丁分辨率为 16x16,微调分辨率为 224x224。
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, optional, defaults to 768) — Transformer 编码器和池化层的维度。 - num_hidden_layers (
int, optional, defaults to 12) — Transformer 编码器中的隐藏层数量。 - num_attention_heads (
int, optional, defaults to 12) — Transformer 编码器中每个注意力层的注意力头数量。 - intermediate_size (
int, optional, defaults to 3072) — Transformer 编码器中“中间”(即前馈)层的维度。 - hidden_act (
str或function, optional, defaults to"gelu") — 编码器和池化层中的非线性激活函数(函数或字符串)。如果为字符串,支持"gelu"、"relu"、"selu"和"gelu_new"。 - hidden_dropout_prob (
float, optional, defaults to 0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float, optional, defaults to 0.0) — 注意力概率的 dropout 率。 - initializer_range (
float, optional, defaults to 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float, optional, defaults to 1e-12) — 层归一化层使用的 epsilon。 - image_size (
int, optional, defaults to 224) — 每个图像的大小(分辨率)。 - patch_size (
int, optional, defaults to 16) — 每个补丁的大小(分辨率)。 - num_channels (
int, optional, defaults to 3) — 输入通道数。 - qkv_bias (
bool, optional, defaults toTrue) — 是否为查询、键和值添加偏置。 - encoder_stride (
int, 可选, 默认为16) — 用于在掩码图像建模的解码器头部中增加空间分辨率的因子。 - pooler_output_size (
int, 可选) — 池化层的维度。如果为 None,则默认为hidden_size。 - pooler_act (
str, 可选, 默认为"tanh") — 池化层要使用的激活函数。
这是用于存储 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.configViTImageProcessor
class transformers.ViTImageProcessor
< source >( do_resize: bool = True size: dict[str, int] | None = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: int | float = 0.00392156862745098 do_normalize: bool = True image_mean: float | list[float] | None = None image_std: float | list[float] | None = None do_convert_rgb: bool | None = None **kwargs )
参数
- do_resize (
bool, 可选, 默认为True) — 是否将图像的 (height, width) 尺寸调整为指定的(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: bool | None = None size: dict[str, int] | None = None resample: PIL.Image.Resampling | None = None do_rescale: bool | None = None rescale_factor: float | None = None do_normalize: bool | None = None image_mean: float | list[float] | None = None image_std: float | list[float] | None = None return_tensors: str | transformers.utils.generic.TensorType | None = None data_format: str | transformers.image_utils.ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: str | transformers.image_utils.ChannelDimension | None = None do_convert_rgb: bool | None = 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.PYTORCH或'pt':返回torch.Tensor类型的批次。TensorType.NUMPY或'np':返回np.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 (
ChannelDimensionorstr, optional) — 输入图像的通道维度格式。如果未设置,则根据输入图像推断通道维度格式。可以是以下之一:"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, optional, defaults toself.do_convert_rgb) — 是否将图像转换为 RGB。
预处理一张或一批图像。
ViTImageProcessorFast
class transformers.ViTImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] )
构造一个快速的 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']] *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 张量。
ViTModel
class transformers.ViTModel
< source >( config: ViTConfig add_pooling_layer: bool = True use_mask_token: bool = False )
参数
- config (ViTConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
- add_pooling_layer (
bool, optional, 默认为True) — 是否添加池化层 - use_mask_token (
bool, optional, 默认为False) — 是否使用掩码令牌进行掩码图像建模。
The bare Vit Model outputting raw hidden-states without any specific head on top.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( pixel_values: torch.Tensor | None = None bool_masked_pos: torch.BoolTensor | None = None interpolate_pos_encoding: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.BaseModelOutputWithPooling or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), optional) — 输入图像对应的张量。可以通过 ViTImageProcessorFast 获取像素值。详情请参阅 ViTImageProcessorFast.call() (processor_class使用 ViTImageProcessorFast 来处理图像)。 - bool_masked_pos (
torch.BoolTensor, shape(batch_size, num_patches), optional) — 布尔掩码位置。指示哪些块被掩码(1)而哪些未被掩码(0)。 - interpolate_pos_encoding (
bool, optional) — 是否插值预训练的位置编码。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.BaseModelOutputWithPooling or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (ViTConfig) and inputs.
-
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), optional, 当传递output_hidden_states=True或当config.output_hidden_states=True时返回) —torch.FloatTensor的元组(一个用于嵌入层的输出,如果模型有嵌入层;+一个用于每个层的输出),形状为(batch_size, sequence_length, hidden_size)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor), optional, 当传递output_attentions=True或当config.output_attentions=True时返回) —torch.FloatTensor的元组(每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
The ViTModel forward method, overrides the __call__ special method。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
ViTForMaskedImageModeling
class transformers.ViTForMaskedImageModeling
< source >( config: ViTConfig )
参数
- config (ViTConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
ViT Model with a decoder on top for masked image modeling, as proposed in SimMIM.
请注意,我们在 examples directory 中提供了一个脚本,用于在自定义数据上预训练此模型。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( pixel_values: torch.Tensor | None = None bool_masked_pos: torch.BoolTensor | None = None interpolate_pos_encoding: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.MaskedImageModelingOutput or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), optional) — 输入图像对应的张量。可以通过 ViTImageProcessorFast 获取像素值。详情请参阅 ViTImageProcessorFast.call() (processor_class使用 ViTImageProcessorFast 来处理图像)。 - bool_masked_pos (
torch.BoolTensor, shape(batch_size, num_patches)) — 布尔掩码位置。指示哪些块被掩码(1)而哪些未被掩码(0)。 - interpolate_pos_encoding (
bool, optional) — 是否插值预训练的位置编码。
返回
transformers.modeling_outputs.MaskedImageModelingOutput or tuple(torch.FloatTensor)
A transformers.modeling_outputs.MaskedImageModelingOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (ViTConfig) and inputs.
- loss (
torch.FloatTensor, shape(1,), optional, 当提供bool_masked_pos时返回) — 重建损失。 - reconstruction (
torch.FloatTensor, shape(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), optional, 当传递output_attentions=True或当 config.output_attentions=True): Tuple oftorch.FloatTensor(每个层一个) of shape(batch_size, num_heads, patch_size, sequence_length)。注意力权重在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
The ViTForMaskedImageModeling forward method, overrides the __call__ special method。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, ViTForMaskedImageModeling
>>> import torch
>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> 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 Model transformer with an image classification head on top (a linear layer on top of the final hidden state of the [CLS] token) e.g. for ImageNet.
Note that it’s possible to fine-tune ViT on higher resolution images than the ones it has been trained on, by setting
interpolate_pos_encodingtoTruein the forward of the model. This will interpolate the pre-trained position embeddings to the higher resolution.
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( pixel_values: torch.Tensor | None = None labels: torch.Tensor | None = None interpolate_pos_encoding: bool | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) → transformers.modeling_outputs.ImageClassifierOutput or tuple(torch.FloatTensor)
参数
- pixel_values (
torch.Tensor, shape(batch_size, num_channels, image_size, image_size), optional) — 输入图像对应的张量。可以通过 ViTImageProcessorFast 获取像素值。详情请参阅 ViTImageProcessorFast.call() (processor_class使用 ViTImageProcessorFast 来处理图像)。 - labels (
torch.LongTensor, shape(batch_size,), optional) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。如果config.num_labels == 1,则计算回归损失(均方损失);如果config.num_labels > 1,则计算分类损失(交叉熵)。 - interpolate_pos_encoding (
bool, optional) — 是否插值预训练的位置编码。
返回
transformers.modeling_outputs.ImageClassifierOutput 或 tuple(torch.FloatTensor)
A transformers.modeling_outputs.ImageClassifierOutput or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (ViTConfig) and inputs.
-
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=True或当config.output_hidden_states=True时返回) — 形状为(batch_size, sequence_length, hidden_size)的torch.FloatTensor元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 每个阶段的输出)。模型在每个阶段输出的隐藏状态(也称为特征图)。 -
attentions (
tuple(torch.FloatTensor), optional, 当传入output_attentions=True或当config.output_attentions=True时返回) — 形状为(batch_size, num_heads, patch_size, sequence_length)的torch.FloatTensor元组(每个层一个)。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
The ViTForImageClassification forward method, overrides the __call__ special method。
虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用
Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, ViTForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> 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])
...