Transformers 文档

GLPN

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

GLPN

PyTorch

这是一个最近引入的模型,因此 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 和一个轻量级解码器,用于单目深度估计。 所提出的解码器比先前提出的解码器表现出更好的性能,且计算复杂度明显更低。

论文摘要如下:

从单张图像进行深度估计是一项重要的任务,可以应用于计算机视觉的各个领域,并且随着卷积神经网络的发展而迅速发展。在本文中,我们提出了一种新颖的结构和训练策略,用于单目深度估计,以进一步提高网络的预测精度。我们部署了一个分层 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] ) — 每个编码器块之前的 patch 大小。
  • strides (List[int], 可选, 默认为 [4, 2, 2, 2]) — 每个编码器块之前的步幅 (Stride)。
  • num_attention_heads (List[int], 可选, 默认为 [1, 2, 5, 8]) — Transformer 编码器每个块中,每个注意力层的注意力头数。
  • mlp_ratios (List[int], 可选, 默认为 [4, 4, 4, 4]) — 编码器块中 Mix FFN 的隐藏层大小与输入层大小之比。
  • 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.1) — 随机深度 (stochastic depth) 的 dropout 概率,用于 Transformer 编码器的块中。
  • layer_norm_eps (float, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon 值。
  • decoder_hidden_size (int, 可选, 默认为 64) — 解码器的维度。
  • max_depth (int, 可选, 默认为 10) — 解码器的最大深度。
  • head_in_index (int, 可选, 默认为 -1) — 在 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

GLPNFeatureExtractor

class transformers.GLPNFeatureExtractor

< >

( *args **kwargs )

__call__

< >

( images **kwargs )

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

GLPNImageProcessor

class transformers.GLPNImageProcessor

< >

( do_resize: bool = True size_divisor: int = 32 resample = <Resampling.BILINEAR: 2> 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 图像处理器。

preprocess

< >

( 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 = <ChannelDimension.FIRST: 'channels_first'> 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, 可选, 默认为 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

class transformers.GLPNModel

< >

( config )

参数

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

裸 GLPN 编码器 (Mix-Transformer) 输出原始隐藏状态,顶部没有任何特定的头部。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 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 (torch.FloatTensor,形状为 (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.BaseModelOutputtorch.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 forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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]

GLPNForDepthEstimation

class transformers.GLPNForDepthEstimation

< >

( config )

参数

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

带有轻量级深度估计头的 GLPN 模型转换器,例如用于 KITTI,NYUv2。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( 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,形状为 (batch_size, num_channels, height, width)) — 像素值。如果您提供填充,默认情况下将忽略填充。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 GLPNImageProcessor.call()
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 有关更多详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
  • labels (torch.FloatTensor,形状为 (batch_size, height, width), 可选) — 用于计算损失的地面真实深度估计图。

返回值

transformers.modeling_outputs.DepthEstimatorOutputtuple(torch.FloatTensor)

transformers.modeling_outputs.DepthEstimatorOutputtorch.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=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组(如果模型有嵌入层,则为嵌入输出提供一个,加上每一层的输出提供一个),形状为 (batch_size, num_channels, height, width)

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

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

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

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

尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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"))
< > 在 GitHub 上更新