Transformers 文档

金字塔视觉Transformer (PVT)

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

金字塔视觉Transformer (PVT)

PyTorch

概述

PVT 模型由 Wenhai Wang、Enze Xie、Xiang Li、Deng-Ping Fan、Kaitao Song、Ding Liang、Tong Lu、Ping Luo、Ling Shao 在 《金字塔视觉Transformer:一个用于密集预测的通用骨干网络,无需卷积》中提出。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+RetinaNet(36.3 AP)高出 4.1 绝对 AP(参见图 2)。我们希望 PVT 能够作为像素级预测的替代和有用的骨干网络,并促进未来的研究。

此模型由 Xrenya 贡献。原始代码可在此处找到。

  • 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

transformers.PvtConfig

< >

( image_size: int = 224 num_channels: int = 3 num_encoder_blocks: int = 4 depths: list = [2, 2, 2, 2] sequence_reduction_ratios: list = [8, 4, 2, 1] hidden_sizes: list = [64, 128, 320, 512] patch_sizes: list = [4, 2, 2, 2] strides: list = [4, 2, 2, 2] num_attention_heads: list = [1, 2, 5, 8] mlp_ratios: list = [8, 8, 4, 4] hidden_act: Mapping = '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, 可选, 默认为 224) — 输入图像大小
  • num_channels (int, 可选, 默认为 3) — 输入通道数。
  • num_encoder_blocks (int, 可选, 默认为 4) — 编码器块的数量(即 Mix Transformer 编码器中的阶段)。
  • depths (list[int], 可选, 默认为 [2, 2, 2, 2]) — 每个编码器块中的层数。
  • sequence_reduction_ratios (list[int], 可选, 默认为 [8, 4, 2, 1]) — 每个编码器块中的序列缩减比率。
  • hidden_sizes (list[int], 可选, 默认为 [64, 128, 320, 512]) — 每个编码器块的维度。
  • patch_sizes (list[int], 可选, 默认为 [4, 2, 2, 2]) — 每个编码器块前的补丁大小。
  • strides (list[int], 可选, 默认为 [4, 2, 2, 2]) — 每个编码器块前的步幅。
  • num_attention_heads (list[int], 可选, 默认为 [1, 2, 5, 8]) — Transformer 编码器每个块中每个注意力层的注意力头数量。
  • mlp_ratios (list[int], 可选, 默认为 [8, 8, 4, 4]) — 编码器块中 Mix FFNs 的隐藏层大小与输入层大小的比率。
  • hidden_act (strfunction, 可选, 默认为 "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) — 用于初始化所有权重矩阵的截断正态分布初始化器的标准差。
  • drop_path_rate (float, 可选, 默认为 0.0) — Transformer 编码器块中用于随机深度的 dropout 概率。
  • layer_norm_eps (float, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon 值。
  • qkv_bias (bool, 可选, 默认为 True) — 是否为查询、键和值添加可学习的偏置。
  • 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

transformers.PvtImageProcessor

< >

( do_resize: bool = True size: typing.Optional[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, 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, 可选, 默认为 Resampling.BILINEAR) — 如果调整图像大小,要使用的重采样过滤器。可以通过 preprocess 方法中的 resample 参数覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 rescale_factor 缩放图像。可以通过 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果缩放图像,要使用的比例因子。可以通过 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否归一化图像。可以通过 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatlist[float], 可选, 默认为 IMAGENET_DEFAULT_MEAN) — 归一化图像时使用的均值。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatlist[float], 可选, 默认为 IMAGENET_DEFAULT_STD) — 归一化图像时使用的标准差。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_std 参数覆盖。

构造 PVT 图像处理器。

preprocess

< >

( 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_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[transformers.utils.generic.TensorType, str, 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 过滤器,例如 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 (floatlist[float], 可选, 默认为 self.image_mean) — 如果 do_normalize 设置为 True,则使用的图像均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 如果 do_normalize 设置为 True,则使用的图像标准差。
  • return_tensors (strTensorType, 可选) — 返回张量的类型。可以是以下之一:
    • 未设置: 返回 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 (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • 未设置: 使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

预处理一张或一批图像。

PvtImageProcessorFast

class transformers.PvtImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )

构造一个快速 Pvt 图像处理器。

preprocess

< >

( 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.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]) — 要预处理的图像。期望单个或批次图像,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请将 do_rescale=False 设置。
  • do_resize (bool, 可选) — 是否调整图像大小。
  • size (dict[str, int], 可选) — 描述模型的最大输入维度。
  • default_to_square (bool, 可选) — 如果尺寸为整数,调整图像大小时是否默认为正方形图像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果调整图像大小,使用的重采样过滤器。可以是枚举类型 PILImageResampling 之一。仅当 do_resize 设置为 True 时有效。
  • do_center_crop (bool, 可选) — 是否对图像进行中心裁剪。
  • crop_size (dict[str, int], 可选) — 应用 center_crop 后输出图像的尺寸。
  • do_rescale (bool, 可选) — 是否重新缩放图像。
  • rescale_factor (Union[int, float, NoneType]) — 如果 do_rescale 设置为 True,则按此重新缩放因子调整图像。
  • do_normalize (bool, 可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], NoneType]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时有效。
  • image_std (Union[float, list[float], NoneType]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, 可选) — 是否将图像转换为 RGB。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果设置为 `pt` 则返回堆叠的张量,否则返回张量列表。
  • data_format (~image_utils.ChannelDimension, 可选) — 输出图像的通道维度格式。仅支持 ChannelDimension.FIRST。为与慢速处理器兼容而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension, NoneType]) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。
  • device (torch.device, 可选) — 处理图像的设备。如果未设置,则从输入图像推断设备。
  • disable_grouping (bool, 可选) — 是否禁用按大小对图像进行分组以单独处理它们而不是批量处理。如果为 None,则如果图像在 CPU 上,则设置为 True,否则设置为 False。此选择基于经验观察,详情见此:https://github.com/huggingface/transformers/pull/38157

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

PvtForImageClassification

class transformers.PvtForImageClassification

< >

( config: PvtConfig )

参数

  • config (PvtConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

Pvt 模型转换器,顶部带有一个图像分类头([CLS] 标记最终隐藏状态顶部的线性层),例如用于 ImageNet。

此模型继承自 PreTrainedModel。请查看超类文档以获取库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。请将其用作常规 PyTorch Module,并参考 PyTorch 文档中与通用用法和行为相关的所有事项。

forward

< >

( 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 or tuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.Tensor, 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • labels (形状为 (batch_size,)torch.LongTensor, 可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

transformers.modeling_outputs.ImageClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.ImageClassifierOutput 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.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=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,再加上每个阶段的输出)形状为 (batch_size, sequence_length, hidden_size)。模型在每个阶段输出的隐藏状态(也称为特征图)。

  • attentions (tuple(torch.FloatTensor), 可选, 当传入 output_attentions=Trueconfig.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, patch_size, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

PvtForImageClassification 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管前向传播的配方需要在此函数中定义,但此后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则静默忽略它们。

示例

>>> from transformers import AutoImageProcessor, PvtForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("Xrenya/pvt-tiny-224")
>>> model = PvtForImageClassification.from_pretrained("Xrenya/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])
...

PvtModel

class transformers.PvtModel

< >

( config: PvtConfig )

参数

  • config (PvtConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

裸 Pvt 模型,输出原始隐藏状态,顶部没有任何特定头部。

此模型继承自 PreTrainedModel。请查看超类文档以获取库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。请将其用作常规 PyTorch Module,并参考 PyTorch 文档中与通用用法和行为相关的所有事项。

forward

< >

( 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.BaseModelOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutput 或一个 torch.FloatTensor 元组(如果传入 return_dict=Falseconfig.return_dict=False),包含取决于配置 (PvtConfig) 和输入的不同元素。

  • last_hidden_state (torch.FloatTensor, 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,再加上每个层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传入 output_attentions=Trueconfig.output_attentions=True 时返回) — torch.FloatTensor 元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

PvtModel 的 forward 方法,覆盖了 __call__ 特殊方法。

尽管前向传播的配方需要在此函数中定义,但此后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则静默忽略它们。

示例

< > 在 GitHub 上更新