Transformers 文档

GLPN

GLPN

这是一个最近引入的模型,因此API尚未经过广泛测试。未来可能会有一些错误或轻微的破坏性更改需要修复。如果您发现任何异常,请提交一个Github Issue

概述

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与轻量级解码器,用于单目深度估计。所提出的解码器在性能上优于之前提出的解码器,且计算复杂度显著降低。

论文的摘要如下:

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

drawing Summary of the approach. Taken from the original paper.

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

资源

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

GLPNConfig

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, optional, 默认为 3) — 输入通道的数量。
  • num_encoder_blocks (int, optional, 默认为 4) — 编码器块的数量(即 Mix Transformer 编码器中的阶段数)。
  • depths (List[int], optional, 默认为 [2, 2, 2, 2]) — 每个编码器块中的层数。
  • sr_ratios (List[int], 可选, 默认为 [8, 4, 2, 1]) — 每个编码器块中的序列缩减比率。
  • hidden_sizes (List[int], optional, 默认为 [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, 默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, optional, 默认为 0.0) — 注意力概率的丢弃比例。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • drop_path_rate (float, optional, 默认为 0.1) — 用于 Transformer 编码器块中的随机深度的丢弃概率。
  • layer_norm_eps (float, optional, defaults to 1e-06) — 层归一化层使用的epsilon值。
  • decoder_hidden_size (int, optional, defaults to 64) — 解码器的维度。
  • max_depth (int, optional, 默认为 10) — 解码器的最大深度。
  • head_in_index (int, optional, 默认为 -1) — 用于头部的特征索引。

这是用于存储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

GLPNFeatureExtractor

transformers.GLPNFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

预处理一张图像或一批图像。

GLPNImageProcessor

transformers.GLPNImageProcessor

< >

( do_resize: bool = True size_divisor: int = 32 resample = do_rescale: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否调整图像的(高度,宽度)尺寸,将其四舍五入到最接近的size_divisor的倍数。可以在preprocess中通过do_resize覆盖此设置。
  • size_divisor (int, 可选, 默认为 32) — 当 do_resizeTrue 时,图像会被调整大小,使其高度和宽度向下舍入到最接近的 size_divisor 的倍数。可以在 preprocess 中通过 size_divisor 覆盖此设置。
  • resample (PIL.Image 重采样过滤器, 可选, 默认为 Resampling.BILINEAR) — 如果调整图像大小,则使用的重采样过滤器。可以在 preprocess 中通过 resample 覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否应用缩放因子(使像素值在0到1之间)。可以在preprocess中通过do_rescale覆盖。

构建一个GLPN图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), transformers.utils.generic.TensorType, typing.List[ForwardRef('PIL.Image.Image')], typing.List[transformers.utils.generic.TensorType]] do_resize: typing.Optional[bool] = None size_divisor: typing.Optional[int] = None resample = None do_rescale: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • images (PIL.Image.ImageTensorTypeList[np.ndarray]List[TensorType]) — 要预处理的图像。期望单个或批量的图像,像素值范围为0到255。如果传入的图像像素值在0到1之间,请设置 do_normalize=False.
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整输入大小,使得(高度,宽度)尺寸是 size_divisor 的倍数。
  • size_divisor (int, 可选, 默认为 self.size_divisor) — 当 do_resizeTrue 时,图像会被调整大小,使其高度和宽度向下舍入到最接近的 size_divisor 的倍数。
  • resample (PIL.Image 重采样过滤器, 可选, 默认为 self.resample) — PIL.Image 重采样过滤器,用于调整图像大小,例如 PILImageResampling.BILINEAR。仅在 do_resize 设置为 True 时有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否应用缩放因子(使像素值在0到1之间浮动)。
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • None: 返回一个 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) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • 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)。

预处理给定的图像。

GLPNModel

transformers.GLPNModel

< >

( config )

参数

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

裸的GLPN编码器(Mix-Transformer)输出原始隐藏状态,顶部没有任何特定的头部。 该模型是PyTorch torch.nn.Module 的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( 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 (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。默认情况下,如果您提供了填充,它将被忽略。可以使用 AutoImageProcessor获取像素值。有关详细信息,请参见GLPNImageProcessor.call().
  • 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=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(GLPNConfig)和输入。

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

GLPNModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

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

>>> 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, 512, 15, 20]

GLPN深度估计

transformers.GLPNForDepthEstimation

< >

( config )

参数

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

GLPN模型转换器,顶部带有轻量级深度估计头,例如用于KITTI、NYUv2。 该模型是PyTorch torch.nn.Module的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( pixel_values: FloatTensor labels: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.DepthEstimatorOutputtuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。默认情况下,如果您提供了填充,它将被忽略。可以使用 AutoImageProcessor获取像素值。详情请参见GLPNImageProcessor.call().
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (torch.FloatTensor of shape (batch_size, height, width), optional) — 用于计算损失的真实深度估计图。

返回

transformers.modeling_outputs.DepthEstimatorOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.DepthEstimatorOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(GLPNConfig)和输入。

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

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

  • hidden_states (tuple(torch.FloatTensor)可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, num_channels, height, width)

    模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。

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

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

GLPNForDepthEstimation 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoImageProcessor, GLPNForDepthEstimation
>>> import torch
>>> import numpy as np
>>> 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("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"))
< > Update on GitHub