Transformers 文档

GLPN

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

此模型于 2022-01-19 发布,并于 2022-03-22 添加到 Hugging Face Transformers。

GLPN

PyTorch

这是一个新近引入的模型,因此 API 尚未经过广泛测试。未来可能会修复一些错误或进行一些小的破坏性更改。如果发现任何异常情况,请提交一个 Github 问题

概述

GLPN 模型由 Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim 在 Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth 中提出。GLPN 结合了 SegFormer 的分层混合 Transformer 和一个轻量级解码器,用于单目深度估计。所提出的解码器在计算复杂度显著降低的情况下,展现出比先前提出的解码器更好的性能。

论文摘要如下:

从单张图像进行深度估计是一项重要的任务,可以应用于计算机视觉的各个领域,并随着卷积神经网络的发展而迅速发展。在本文中,我们提出了一种新颖的单目深度估计结构和训练策略,以进一步提高网络的预测精度。我们部署了一个分层 Transformer 编码器来捕获和传达全局上下文,并设计了一个轻量但功能强大的解码器,在考虑局部连接性的同时生成估计的深度图。通过我们提出的选择性特征融合模块,在多尺度局部特征与全局解码流之间构建连接路径,网络可以整合这两种表示并恢复精细细节。此外,与先前提出的解码器相比,我们提出的解码器在计算复杂度显著降低的情况下表现出更好的性能。此外,我们通过利用深度估计中的一个重要观察来改进特定于深度的增强方法,以增强模型。我们的网络在具有挑战性的深度数据集 NYU Depth V2 上实现了最先进的性能。我们进行了广泛的实验来验证并展示所提出方法的有效性。最后,我们的模型比其他比较模型具有更好的泛化能力和鲁棒性。

drawing 方法的总结。摘自原始论文

此模型由 nielsr 贡献。原始代码可以在这里找到。

资源

一份官方 Hugging Face 和社区(标有 🌎)资源列表,可帮助您开始使用 GLPN。

GLPNConfig

class transformers.GLPNConfig

< >

( num_channels = 3 num_encoder_blocks = 4 depths = [2, 2, 2, 2] sr_ratios = [8, 4, 2, 1] hidden_sizes = [32, 64, 160, 256] patch_sizes = [7, 3, 3, 3] strides = [4, 2, 2, 2] num_attention_heads = [1, 2, 5, 8] mlp_ratios = [4, 4, 4, 4] hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 drop_path_rate = 0.1 layer_norm_eps = 1e-06 decoder_hidden_size = 64 max_depth = 10 head_in_index = -1 **kwargs )

参数

  • num_channels (int, 可选, 默认为 3) — 输入通道数。
  • num_encoder_blocks (int, 可选, 默认为 4) — 每个编码器块(即 Mix Transformer 编码器中的阶段数)的数量。
  • depths (list[int], 可选, 默认为 [2, 2, 2, 2]) — 每个编码器块中的层数。
  • sr_ratios (list[int], 可选, 默认为 [8, 4, 2, 1]) — 每个编码器块中的序列缩减比率。
  • hidden_sizes (list[int], 可选, 默认为 [32, 64, 160, 256]) — 每个编码器块的维度。
  • patch_sizes (list[int], 可选, 默认为 [7, 3, 3, 3]) — 每个编码器块之前的补丁大小。
  • strides (list[int], 可选, 默认为 [4, 2, 2, 2]) — 每个编码器块之前的步幅。
  • num_attention_heads (list[int], 可选, 默认为 [1, 2, 5, 8]) — Transformer 编码器中每个块中每个注意力层的注意力头数量。
  • mlp_ratios (list[int], 可选, 默认为 [4, 4, 4, 4]) — 编码器块中 Mix FFNs 的隐藏层大小与输入层大小的比率。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,支持 "gelu""relu""selu""gelu_new"
  • hidden_dropout_prob (float, optional, defaults to 0.0) — The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  • attention_probs_dropout_prob (float, optional, defaults to 0.0) — The dropout ratio for the attention probabilities.
  • initializer_range (float, optional, defaults to 0.02) — The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  • drop_path_rate (float, optional, defaults to 0.1) — The dropout probability for stochastic depth, used in the blocks of the Transformer encoder.
  • layer_norm_eps (float, optional, defaults to 1e-06) — The epsilon used by the layer normalization layers.
  • decoder_hidden_size (int, optional, defaults to 64) — The dimension of the decoder.
  • max_depth (int, optional, defaults to 10) — The maximum depth of the decoder.
  • head_in_index (int, optional, defaults to -1) — The index of the features to use in the head.

这是用于存储 GLPNModel 配置的配置类。它用于根据指定的参数实例化 GLPN 模型,定义模型架构。使用默认值实例化配置将产生一个类似于 GLPN vinvino02/glpn-kitti 架构的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。

示例

>>> from transformers import GLPNModel, GLPNConfig

>>> # Initializing a GLPN vinvino02/glpn-kitti style configuration
>>> configuration = GLPNConfig()

>>> # Initializing a model from the vinvino02/glpn-kitti style configuration
>>> model = GLPNModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

GLPNImageProcessor

class transformers.GLPNImageProcessor

< >

( do_resize: bool = True size_divisor: int = 32 resample = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: float | None = 0.00392156862745098 **kwargs )

参数

  • do_resize (bool, optional, defaults to True) — Whether to resize the image’s (height, width) dimensions, rounding them down to the closest multiple of size_divisor. Can be overridden by do_resize in preprocess.
  • size_divisor (int, optional, defaults to 32) — When do_resize is True, images are resized so their height and width are rounded down to the closest multiple of size_divisor. Can be overridden by size_divisor in preprocess.
  • resample (PIL.Image resampling filter, optional, defaults to Resampling.BILINEAR) — Resampling filter to use if resizing the image. Can be overridden by resample in preprocess.
  • do_rescale (bool, optional, defaults to True) — Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Can be overridden by do_rescale in preprocess.
  • rescale_factor (float, optional, defaults to 1 / 255) — The scaling factor to apply to the pixel values. Can be overridden by rescale_factor in preprocess.

构造一个 GLPN 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), transformers.utils.generic.TensorType, list['PIL.Image.Image'], list[transformers.utils.generic.TensorType]] do_resize: bool | None = None size_divisor: int | None = None resample = None do_rescale: bool | None = None rescale_factor: float | None = None return_tensors: transformers.utils.generic.TensorType | str | None = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: str | transformers.image_utils.ChannelDimension | None = None )

参数

  • images (PIL.Image.Image or TensorType or list[np.ndarray] or list[TensorType]) — Images to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_normalize=False.
  • do_resize (bool, optional, defaults to self.do_resize) — Whether to resize the input such that the (height, width) dimensions are a multiple of size_divisor.
  • size_divisor (int, optional, defaults to self.size_divisor) — When do_resize is True, images are resized so their height and width are rounded down to the closest multiple of size_divisor.
  • resample (PIL.Image resampling filter, optional, defaults to self.resample) — PIL.Image resampling filter to use if resizing the image e.g. PILImageResampling.BILINEAR. Only has an effect if do_resize is set to True.
  • do_rescale (bool, optional, defaults to self.do_rescale) — Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.).
  • return_tensors (str or TensorType, optional) — The type of tensors to return. Can be one of:
    • None: Return a list of np.ndarray.
    • TensorType.PYTORCH or 'pt': Return a batch of type torch.Tensor.
    • TensorType.NUMPY or 'np': Return a batch of type np.ndarray.
  • data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) — The channel dimension format for the output image. Can be one of:
    • ChannelDimension.FIRST: image in (num_channels, height, width) format.
    • ChannelDimension.LAST: image in (height, width, num_channels) format.
  • input_data_format (ChannelDimension or str, optional) — The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:
    • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
    • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
    • "none" or ChannelDimension.NONE: image in (height, width) format.

预处理给定的图像。

GLPNImageProcessorFast

class transformers.GLPNImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.processing_utils.ImagesKwargs] )

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

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.processing_utils.ImagesKwargs] ) <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_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_rescaleTrue,则用于缩放图像的缩放因子。
  • do_normalize (bool | None.do_normalize) — 是否进行归一化。
  • image_mean (float | list[float] | tuple[float, ...] | None.image_mean) — 用于归一化的图像均值。仅在设置了 do_normalizeTrue 时生效。
  • image_std (float | list[float] | tuple[float, ...] | None.image_std) — 用于归一化的图像标准差。仅在设置了 do_normalizeTrue 时生效。
  • 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 张量。

GLPNModel

class transformers.GLPNModel

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

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

裸露的 Glpn 模型输出原始隐藏状态,顶部没有特定的头。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: FloatTensor output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size)) — 输入图像对应的张量。像素值可以通过 GLPNImageProcessorFast 获取。有关详细信息,请参阅 GLPNImageProcessorFast.call()processor_class 使用 GLPNImageProcessorFast 来处理图像)。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。更多细节请参见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。更多细节请参见返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通元组。

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutput 或一个 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置 (GLPNConfig) 和输入而变化的各种元素。

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

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

GLPNForDepthEstimation

class transformers.GLPNForDepthEstimation

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

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

GLPN 模型转换器,顶部带有一个轻量级的深度估计头,例如用于 KITTI、NYUv2。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: FloatTensor labels: torch.FloatTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.DepthEstimatorOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size)) — 输入图像对应的张量。像素值可以通过 GLPNImageProcessorFast 获取。有关详细信息,请参阅 GLPNImageProcessorFast.call()processor_class 使用 GLPNImageProcessorFast 来处理图像)。
  • labels (torch.FloatTensor of shape (batch_size, height, width), optional) — 用于计算损失的地面真实深度估计图。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。更多细节请参见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。更多细节请参见返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通元组。

返回

transformers.modeling_outputs.DepthEstimatorOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.DepthEstimatorOutput 或一个 torch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置 (GLPNConfig) 和输入而变化的各种元素。

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。

  • predicted_depth (torch.FloatTensor,形状为 (batch_size, height, width)) — 每个像素的预测深度。

  • hidden_states (tuple(torch.FloatTensor), optional, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则包含一个嵌入层输出,加上每层的一个输出),形状为 (batch_size, num_channels, height, width)

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

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

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

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

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoImageProcessor, GLPNForDepthEstimation
>>> import torch
>>> import numpy as np
>>> 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("vinvino02/glpn-kitti")
>>> model = GLPNForDepthEstimation.from_pretrained("vinvino02/glpn-kitti")

>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # interpolate to original size
>>> post_processed_output = image_processor.post_process_depth_estimation(
...     outputs,
...     target_sizes=[(image.height, image.width)],
... )

>>> # visualize the prediction
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
>>> depth = predicted_depth * 255 / predicted_depth.max()
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint8"))
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.