Transformers documentation

DPT

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2021-03-24 在 HF papers 上发布,并于 2022-03-28 贡献至 Hugging Face Transformers。

DPT

FlashAttention SDPA

概述

DPT 模型由 René Ranftl、Alexey Bochkovskiy 和 Vladlen Koltun 在 Vision Transformers for Dense Prediction 中提出。 DPT 是一种利用 Vision Transformer (ViT) 作为骨干网络,用于语义分割和深度估计等密集预测任务的模型。

该论文的摘要如下:

我们提出了稠密视觉 Transformer(dense vision transformers),这是一种以视觉 Transformer 取代卷积网络作为稠密预测任务骨干网络的架构。我们将视觉 Transformer 各个阶段的 token 组装成不同分辨率的类图像表示,并通过卷积解码器逐步将其融合为全分辨率的预测结果。Transformer 骨干网络在恒定且相对较高的分辨率下处理表示,并且在每个阶段都具有全局感受野。这些特性使得稠密视觉 Transformer 相较于全卷积网络,能够提供更细粒度且全局一致性更强的预测。我们的实验表明,该架构在稠密预测任务上带来了显著提升,尤其是在拥有大量训练数据的情况下。在单目深度估计任务中,与最先进的全卷积网络相比,我们观察到相对性能最高提升了 28%。当应用于语义分割时,稠密视觉 Transformer 在 ADE20K 数据集上以 49.02% 的 mIoU 刷新了最先进水平。我们进一步表明,该架构可以在 NYUv2、KITTI 和 Pascal Context 等较小的数据集上进行微调,并在这些数据集上同样刷新了最先进水平。

drawing DPT architecture. Taken from the original paper.

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

使用技巧

DPT 与 AutoBackbone 类兼容。这使得您可以使用 DPT 框架搭配库中可用的各种计算机视觉骨干网络,例如 VitDetBackbone 或 Dinov2Backbone。创建方式如下:

from transformers import Dinov2Config, DPTConfig, DPTForDepthEstimation


# initialize with a Transformer-based backbone such as DINOv2
# in that case, we also specify `reshape_hidden_states=False` to get feature maps of shape (batch_size, num_channels, height, width)
backbone_config = Dinov2Config.from_pretrained("facebook/dinov2-base", out_features=["stage1", "stage2", "stage3", "stage4"], reshape_hidden_states=False)

config = DPTConfig(backbone_config=backbone_config)
model = DPTForDepthEstimation(config=config)

资源

一份来自 Hugging Face 官方和社区(以 🌎 标识)的资源列表,帮助你快速上手 DPT。

如果您有兴趣提交资源以收录在此处,请随时发起 Pull Request,我们将对其进行审核!理想情况下,该资源应展示一些新内容,而不是重复现有资源。

DPTConfig

class transformers.DPTConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 768num_hidden_layers: None | int = 12num_attention_heads: int | None = 12intermediate_size: int | None = 3072hidden_act: str = 'gelu'hidden_dropout_prob: float | int | None = 0.0attention_probs_dropout_prob: float | int | None = 0.0initializer_range: float = 0.02layer_norm_eps: float | None = 1e-12image_size: int | list[int] | tuple[int, int] | None = 384patch_size: int | list[int] | tuple[int, int] | None = 16num_channels: int | None = 3is_hybrid: bool = Falseqkv_bias: bool | None = Truebackbone_out_indices: list[int] | tuple[int, ...] | None = (2, 5, 8, 11)readout_type: typing.Literal['ignore', 'add', 'project'] = 'project'reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5)neck_hidden_sizes: list[int] | tuple[int, ...] = (96, 192, 384, 768)fusion_hidden_size: int = 256head_in_index: int = -1use_batch_norm_in_fusion_residual: bool | None = Falseuse_bias_in_fusion_residual: bool | None = Noneadd_projection: bool = Falseuse_auxiliary_head: bool | None = Trueauxiliary_loss_weight: float = 0.4semantic_loss_ignore_index: int = 255semantic_classifier_dropout: float | int = 0.1backbone_featmap_shape: list[int] | tuple[int, ...] | None = (1, 1024, 24, 24)neck_ignore_stages: list[int] | tuple[int, ...] = (0, 1)backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonepooler_output_size: int | None = Nonepooler_act: str = 'tanh' )

参数

  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • hidden_act (str,可选,默认为 gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • hidden_dropout_prob (Union[float, int],可选,默认为 0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float,可选,默认为 1e-12) — 层归一化层所使用的 epsilon 值。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 384) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • is_hybrid (bool,可选,默认为 False) — 是否使用混合骨干网络。在加载 DPT-Hybrid 模型时很有用。
  • qkv_bias (bool,可选,默认为 True) — 是否向查询、键和值添加偏置。
  • backbone_out_indices (list[int],可选,默认为 [2, 5, 8, 11]) — 从 backbone 中选取的中间隐藏状态索引。
  • readout_type (str, 可选, 默认为 "project") — 处理 ViT 主干网络中间隐藏状态的读出 token(CLS token)时使用的读出类型。可以是 ["ignore", "add", "project"] 之一。“ignore” 直接忽略 CLS token。“add” 通过相加表示将 CLS token 的信息传递给所有其他 token。“project” 通过将读出与所有其他 token 拼接,然后使用线性层后接 GELU 非线性函数将表示投影回原始特征维度 D,从而将信息传递给其他 token。"ignore", "add", "project"].
    • “ignore” 简单地忽略 CLS token。
    • “add” 通过相加表示的方式,将 CLS token 的信息传递给所有其他 token。
    • “project” 通过将 readout 拼接(concatenating)到所有其他 token 上来向其他 token 传递信息,然后使用一个线性层后接 GELU 非线性激活,将表示投影回原始特征维度 D。
  • reassemble_factors (list[int],可选,默认为 [4, 2, 1, 0.5]) — 重组层的上采样/下采样因子。
  • neck_hidden_sizes (list[str],可选,默认为 [96, 192, 384, 768]) — 用于将主干网络的特征图投影到的隐藏层大小。
  • fusion_hidden_size (int,可选,默认为 256) — 融合前的通道数。
  • head_in_index (int,可选,默认为 -1) — 在 heads 中使用的特征的索引。
  • use_batch_norm_in_fusion_residual (bool,可选,默认为 False) — 是否在融合块的预激活残差单元中使用批归一化。
  • use_bias_in_fusion_residual (bool,可选,默认为 True) — 是否在融合块的前激活残差单元中使用偏置。
  • add_projection (bool,可选,默认为 False) — 是否在深度估计头之前添加投影层。
  • use_auxiliary_head (bool,可选,默认为 True) — 是否在训练期间使用辅助头。
  • auxiliary_loss_weight (float,可选,默认为 0.4) — 辅助头交叉熵损失的权重。
  • semantic_loss_ignore_index (int,可选,默认为 255) — 语义分割模型的损失函数中忽略的索引。
  • semantic_classifier_dropout (float,可选,默认值为 0.1) — 语义分类头的 dropout 比率。
  • backbone_featmap_shape (list[int],可选,默认为 [1, 1024, 24, 24]) — 仅用于 hybrid 嵌入类型。主干网络特征图的形状。
  • neck_ignore_stages (list[int],可选,默认为 [0, 1]) — 仅用于 hybrid 嵌入类型。指定要忽略的读出层阶段。
  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。
  • pooler_output_size (int, 可选) — 池化层的维度。如果为 None,则默认为 hidden_size。
  • pooler_act (str,可选,默认为 "tanh") — 池化器所使用的激活函数。

这是用于存储 DPTModel 配置的类。它根据指定的参数实例化 Dpt 模型,并定义模型架构。使用默认值实例化配置,将得到与 Intel/dpt-large 类似的配置。

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

示例:

>>> from transformers import DPTModel, DPTConfig

>>> # Initializing a DPT dpt-large style configuration
>>> configuration = DPTConfig()

>>> # Initializing a model from the dpt-large style configuration
>>> model = DPTModel(configuration)

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

DPTImageProcessor

class transformers.DPTImageProcessor

< >

( **kwargs: *<class 'transformers.models.dpt.image_processing_dpt.DPTImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 384, 'width': 384}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 None) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 False) — 是否对图像进行填充。填充方式是将图像填充到批次中的最大尺寸,或填充到每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选,默认为 None) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "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], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ensure_multiple_of (int,kwargs,可选,默认值为 1) — 如果 do_resize 为 True,图像将被调整为该值整数倍的尺寸。可通过 preprocess 中的 ensure_multiple_of 进行覆盖。
  • size_divisor (int, kwargs) — 用于确保高度和宽度都能被整除的数值。
  • keep_aspect_ratio (bool,kwargs,可选,默认为 False) — 如果为 True,图像将被调整为在保持宽高比不变的前提下尽可能大的尺寸。该设置可被 preprocess 中的 keep_aspect_ratio 覆盖。
  • do_reduce_labels (bool,kwargs,可选,默认为 self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。

构建 DPTImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.dpt.image_processing_dpt.DPTImageProcessorKwargs'> ) → ~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。
  • segmentation_maps (ImageInput,可选) — 要预处理的分割图。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "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], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ensure_multiple_of (int,kwargs,可选,默认值为 1) — 如果 do_resize 为 True,图像将被调整为该值整数倍的尺寸。可通过 preprocess 中的 ensure_multiple_of 进行覆盖。
  • size_divisor (int, kwargs) — 用于确保高度和宽度都能被整除的数值。
  • keep_aspect_ratio (bool,kwargs,可选,默认为 False) — 如果为 True,图像将被调整为在保持宽高比不变的前提下尽可能大的尺寸。该设置可被 preprocess 中的 keep_aspect_ratio 覆盖。
  • do_reduce_labels (bool,kwargs,可选,默认为 self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

DPTImageProcessorPil

class transformers.DPTImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.dpt.image_processing_pil_dpt.DPTImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 384, 'width': 384}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 3) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.5, 0.5, 0.5]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 False) — 是否对图像进行填充。填充方式是将图像填充到批次中的最大尺寸,或填充到每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "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], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ensure_multiple_of (int,kwargs,可选,默认值为 1) — 如果 do_resize 为 True,图像将被调整为该值整数倍的尺寸。可通过 preprocess 中的 ensure_multiple_of 进行覆盖。
  • size_divisor (int, kwargs) — 用于确保高度和宽度都能被整除的数值。
  • keep_aspect_ratio (bool,kwargs,可选,默认为 False) — 如果为 True,图像将被调整为在保持宽高比不变的前提下尽可能大的尺寸。该设置可被 preprocess 中的 keep_aspect_ratio 覆盖。
  • do_reduce_labels (bool,kwargs,可选,默认为 self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。

构建 DPTImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None**kwargs: *<class 'transformers.models.dpt.image_processing_pil_dpt.DPTImageProcessorKwargs'> ) → ~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。
  • segmentation_maps (ImageInput,可选) — 要预处理的分割图。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "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], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • ensure_multiple_of (int,kwargs,可选,默认值为 1) — 如果 do_resize 为 True,图像将被调整为该值整数倍的尺寸。可通过 preprocess 中的 ensure_multiple_of 进行覆盖。
  • size_divisor (int, kwargs) — 用于确保高度和宽度都能被整除的数值。
  • keep_aspect_ratio (bool,kwargs,可选,默认为 False) — 如果为 True,图像将被调整为在保持宽高比不变的前提下尽可能大的尺寸。该设置可被 preprocess 中的 keep_aspect_ratio 覆盖。
  • do_reduce_labels (bool,kwargs,可选,默认为 self.do_reduce_labels) — 是否将所有分割掩码的标签值减 1。通常用于 0 表示背景、且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

post_process_semantic_segmentation

< >

( outputstarget_sizes: list[tuple] | None = Nonereturn_segmentation_scores: bool = False ) → list[torch.Tensor] or list[SemanticSegmentationPostProcessorOutput]

参数

  • outputs (DPTForSemanticSegmentation) — 模型的原始输出。
  • target_sizes (list[tuple],可选) — 一个由元组(tuple[int, int])组成的列表,包含批次中每张图片的目标尺寸(高度,宽度)。如果未设置,预测结果将不会被调整大小。
  • return_segmentation_scores (bool,可选,默认为 False) — 是否随分割图一起返回分割分数。当 True 时,返回列表中的每个元素都是一个 SemanticSegmentationPostProcessorOutput,包含字段 segmentation(类别 ID,形状为 (height, width))和 segmentation_scores(形状为 (num_classes, height, width))。

返回值

list[torch.Tensor] 或 list[SemanticSegmentationPostProcessorOutput]

当 return_segmentation_scores=False(默认值)时,返回一个长度为 batch_size 的列表,其中每个元素都是形状为 (height, width) 的分割图,包含类别 ID。当 return_segmentation_scores=True 时,返回一个 SemanticSegmentationPostProcessorOutput 列表,包含字段 segmentation(类别 ID,形状为 (height, width))和 segmentation_scores(形状为 (num_classes, height, width))。在这两种情况下,(height, width) 对应于目标尺寸(如果指定了 target_sizes)。

将 DPTForSemanticSegmentation 的输出转换为语义分割图。

post_process_depth_estimation

< >

( outputs: DepthEstimatorOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None )

将 DepthEstimatorOutput 的原始输出转换为最终的深度预测结果。

DPTModel

class transformers.DPTModel

< >

( config: DPTConfigadd_pooling_layer: bool = True )

参数

  • config (DPTConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
  • add_pooling_layer (bool,可选,默认为 True) — 是否添加池化层

未添加任何特定头部的裸 Dpt 模型,直接输出原始隐藏状态。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensor**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPoolingAndIntermediateActivations or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 DPTImageProcessor 获取像素值。有关详细信息,请参阅 DPTImageProcessor.call()(processor_class 使用 DPTImageProcessor 处理图像)。

返回值

BaseModelOutputWithPoolingAndIntermediateActivations 或 tuple(torch.Tensor)

BaseModelOutputWithPoolingAndIntermediateActivations 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(DPTConfig)和输入而定的各种元素。

DPTModel 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

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

  • pooler_output (torch.Tensor,形状为 (batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过用于辅助预训练任务的层进一步处理后得到。例如,对于 BERT 系列模型,这返回的是分类 token 经过线性层和 tanh 激活函数处理后的结果。线性层的权重在预训练期间通过下一句预测(分类)目标进行训练。

  • hidden_states (tuple[torch.Tensor, ...],可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, sequence_length, hidden_size)。

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

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

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

  • intermediate_activations (tuple(torch.Tensor),可选) — 可用于计算模型各层隐藏状态的中间激活值。

示例:

DPTForDepthEstimation

class transformers.DPTForDepthEstimation

< >

( config: DPTConfig )

参数

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

带有深度估计头(由 3 个卷积层组成)的 DPT 模型,例如用于 KITTI、NYUv2。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensorlabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → DepthEstimatorOutput or tuple(torch.Tensor)

参数

  • 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, height, width) 的 torch.LongTensor,可选) — 用于计算损失的真实深度估计图。

返回值

DepthEstimatorOutput 或 tuple(torch.Tensor)

一个 DepthEstimatorOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(None)和输入。

DPTForDepthEstimation 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

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

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

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为 (batch_size, num_channels, height, width)。

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

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

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

示例:

>>> from transformers import AutoImageProcessor, DPTForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> from huggingface_hub.utils 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("Intel/dpt-large")
>>> model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")

>>> # 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"))

DPTForSemanticSegmentation

class transformers.DPTForSemanticSegmentation

< >

( config: DPTConfig )

参数

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

带有语义分割头的 Dpt 模型,例如用于 ADE20K、CityScapes。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SemanticSegmenterOutput or tuple(torch.Tensor)

参数

  • 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, height, width) 的 torch.LongTensor,可选) — 用于计算损失的语义分割真值图。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回值

SemanticSegmenterOutput 或 tuple(torch.Tensor)

一个 SemanticSegmenterOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(None)和输入。

DPTForSemanticSegmentation 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

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

  • logits(形状为 (batch_size, config.num_labels, logits_height, logits_width) 的 torch.Tensor)— 每个像素的分类分数。

    返回的 logits 的大小不一定与作为输入传入的 pixel_values 相同。这样做的目的是避免进行两次插值,从而在用户需要作为后处理将 logits 调整回原始图像大小时损失一些质量。您应始终检查 logits 的形状,并根据需要进行调整。

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, patch_size, hidden_size)。

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

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

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

示例:

>>> from transformers import AutoImageProcessor, DPTForSemanticSegmentation
>>> from PIL import Image
>>> from huggingface_hub.utils 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("Intel/dpt-large-ade")
>>> model = DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade")

>>> inputs = image_processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)
>>> logits = outputs.logits
Update on GitHub