Transformers 文档
金字塔视觉Transformer (PVT)
并获取增强的文档体验
开始使用
金字塔视觉Transformer (PVT)
概述
PVT 模型在 Pyramid Vision Transformer: A Versatile Backbone for Dense Prediction without Convolutions 中提出,作者是 Wenhai Wang, Enze Xie, Xiang Li, Deng-Ping Fan, Kaitao Song, Ding Liang, Tong Lu, Ping Luo, Ling Shao。PVT 是一种视觉 transformer,它利用金字塔结构使其成为密集预测任务的有效骨干网络。具体来说,它允许使用更精细的输入(每个补丁 4 x 4 像素),同时随着 Transformer 的加深而缩小序列长度 - 从而降低计算成本。此外,还使用空间缩减注意力 (SRA) 层来进一步减少学习高分辨率特征时的资源消耗。
论文摘要如下:
虽然卷积神经网络 (CNN) 在计算机视觉领域取得了巨大成功,但这项工作研究了一种更简单、无卷积的骨干网络,可用于许多密集预测任务。与最近提出的专门为图像分类设计的 Vision Transformer (ViT) 不同,我们推出了金字塔视觉 Transformer (PVT),它克服了将 Transformer 移植到各种密集预测任务的困难。与当前最先进的技术相比,PVT 有几个优点。与 ViT 通常产生低分辨率输出并产生高计算和内存成本不同,PVT 不仅可以在图像的密集分区上进行训练以实现高输出分辨率(这对于密集预测非常重要),而且还使用渐进式收缩金字塔来减少大型特征图的计算。PVT 继承了 CNN 和 Transformer 的优点,使其成为各种无卷积视觉任务的统一骨干网络,其中它可以直接替代 CNN 骨干网络。我们通过广泛的实验验证了 PVT,结果表明它可以提高许多下游任务的性能,包括物体检测、实例和语义分割。例如,在参数数量相当的情况下,PVT+RetinaNet 在 COCO 数据集上实现了 40.4 AP,比 ResNet50+RetinNet (36.3 AP) 高出 4.1 个绝对 AP(见图 2)。我们希望 PVT 可以作为像素级预测的替代且有用的骨干网络,并促进未来的研究。
- ImageNet-1K 上的 PVTv1
模型变体 | 尺寸 | Acc@1 | 参数 (M) |
---|---|---|---|
PVT-Tiny | 224 | 75.1 | 13.2 |
PVT-Small | 224 | 79.8 | 24.5 |
PVT-Medium | 224 | 81.2 | 44.2 |
PVT-Large | 224 | 81.7 | 61.4 |
PvtConfig
class transformers.PvtConfig
< source >( image_size: int = 224 num_channels: int = 3 num_encoder_blocks: int = 4 depths: typing.List[int] = [2, 2, 2, 2] sequence_reduction_ratios: typing.List[int] = [8, 4, 2, 1] hidden_sizes: typing.List[int] = [64, 128, 320, 512] patch_sizes: typing.List[int] = [4, 2, 2, 2] strides: typing.List[int] = [4, 2, 2, 2] num_attention_heads: typing.List[int] = [1, 2, 5, 8] mlp_ratios: typing.List[int] = [8, 8, 4, 4] hidden_act: typing.Mapping[str, typing.Callable] = 'gelu' hidden_dropout_prob: float = 0.0 attention_probs_dropout_prob: float = 0.0 initializer_range: float = 0.02 drop_path_rate: float = 0.0 layer_norm_eps: float = 1e-06 qkv_bias: bool = True num_labels: int = 1000 **kwargs )
参数
- image_size (
int
, optional, 默认为 224) — 输入图像尺寸 - num_channels (
int
, optional, 默认为 3) — 输入通道数。 - num_encoder_blocks (
int
, optional, 默认为 4) — 编码器块的数量(即 Mix Transformer 编码器中的阶段)。 - depths (
List[int]
, optional, 默认为[2, 2, 2, 2]
) — 每个编码器块中的层数。 - sequence_reduction_ratios (
List[int]
, optional, 默认为[8, 4, 2, 1]
) — 每个编码器块中的序列缩减率。 - hidden_sizes (
List[int]
, optional, 默认为[64, 128, 320, 512]
) — 每个编码器块的维度。 - patch_sizes (
List[int]
, optional, 默认为[4, 2, 2, 2]
) — 每个编码器块之前的补丁大小。 - strides (
List[int]
, optional, 默认为[4, 2, 2, 2]
) — 每个编码器块之前的步幅。 - num_attention_heads (
List[int]
, optional, 默认为[1, 2, 5, 8]
) — Transformer 编码器中每个块的每个注意力层中的注意力头数。 - mlp_ratios (
List[int]
, optional, 默认为[8, 8, 4, 4]
) — 编码器块中 Mix FFN 的隐藏层大小与输入层大小之比。 - hidden_act (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
、"relu"
、"selu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, 可选, 默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, 可选, 默认为 0.0) — attention 概率的 dropout 比率。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - drop_path_rate (
float
, 可选, 默认为 0.0) — Transformer 编码器块中使用的随机深度 dropout 概率。 - layer_norm_eps (
float
, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon 值。 - qkv_bias (
bool
, 可选, 默认为True
) — 是否应向 queries、keys 和 values 添加可学习的偏置。 - num_labels (‘int’, 可选, 默认为 1000) — 类别的数量。
这是用于存储 PvtModel 配置的配置类。它用于根据指定的参数实例化 Pvt 模型,定义模型架构。使用默认值实例化配置将产生类似于 Pvt Xrenya/pvt-tiny-224 架构的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import PvtModel, PvtConfig
>>> # Initializing a PVT Xrenya/pvt-tiny-224 style configuration
>>> configuration = PvtConfig()
>>> # Initializing a model from the Xrenya/pvt-tiny-224 style configuration
>>> model = PvtModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
PvtImageProcessor
class transformers.PvtImageProcessor
< 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 **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_DEFAULT_MEAN
) — 如果标准化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认为IMAGENET_DEFAULT_STD
) — 如果标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_std
参数覆盖。
构建 PVT 图像处理器。
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 )
参数
- 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
滤波器,如果do_resize
设置为True
,则用于调整图像大小,例如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
, 可选) — 返回张量的类型。可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- 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)。
预处理图像或批量图像。
PvtForImageClassification
class transformers.PvtForImageClassification
< source >( config: PvtConfig )
参数
- config (~PvtConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
Pvt 模型转换器,顶部带有图像分类头([CLS] 标记的最终隐藏状态之上的线性层),例如用于 ImageNet。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] 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
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 PvtImageProcessor.call()。 - 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
时),包含各种元素,具体取决于配置 (PvtConfig) 和输入。
-
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 之后的注意力权重,用于计算自注意力头中的加权平均值。
PvtForImageClassification forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, PvtForImageClassification
>>> 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("Zetatech/pvt-tiny-224")
>>> model = PvtForImageClassification.from_pretrained("Zetatech/pvt-tiny-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])
tabby, tabby cat
PvtModel
class transformers.PvtModel
< source >( config: PvtConfig )
参数
- config (~PvtConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
裸 Pvt 编码器,输出原始隐藏状态,顶部没有任何特定的头。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。
forward
< source >( pixel_values: FloatTensor output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 像素值。像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参阅 PvtImageProcessor.call()。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutput 或一个 torch.FloatTensor
元组 (如果传递了 return_dict=False
,或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (PvtConfig) 和输入。
-
last_hidden_state (
torch.FloatTensor
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出的隐藏状态序列。 -
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 之后的注意力权重,用于计算自注意力头中的加权平均值。
PvtModel 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数内定义,但应该在此之后调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, PvtModel
>>> 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("Zetatech/pvt-tiny-224")
>>> model = PvtModel.from_pretrained("Zetatech/pvt-tiny-224")
>>> 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, 50, 512]