Transformers 文档

DPT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型发布于 2021-03-24,并于 2022-03-28 添加到 Hugging Face Transformers。

DPT

PyTorch 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 架构。取自 原论文

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

使用技巧

DPT 与 AutoBackbone 类兼容。这允许在 DPT 框架中使用库中提供的各种计算机视觉主干网络,例如 VitDetBackboneDinov2Backbone。可以按如下方式创建它

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

< >

( hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 initializer_range = 0.02 layer_norm_eps = 1e-12 image_size = 384 patch_size = 16 num_channels = 3 is_hybrid = False qkv_bias = True backbone_out_indices = [2, 5, 8, 11] readout_type = 'project' reassemble_factors = [4, 2, 1, 0.5] neck_hidden_sizes = [96, 192, 384, 768] fusion_hidden_size = 256 head_in_index = -1 use_batch_norm_in_fusion_residual = False use_bias_in_fusion_residual = None add_projection = False use_auxiliary_head = True auxiliary_loss_weight = 0.4 semantic_loss_ignore_index = 255 semantic_classifier_dropout = 0.1 backbone_featmap_shape = [1, 1024, 24, 24] neck_ignore_stages = [0, 1] backbone_config = None pooler_output_size = None pooler_act = 'tanh' **kwargs )

参数

  • hidden_size (int可选,默认为 768) — 编码器层和池化层(pooler layer)的维度。
  • num_hidden_layers (int可选,默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int可选,默认为 12) — Transformer 编码器中每个注意力层的注意力头数量。
  • intermediate_size (int可选,默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。
  • hidden_act (strfunction可选,默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""selu""gelu_new"
  • hidden_dropout_prob (float可选,默认为 0.0) — 嵌入层、编码器和池化器中所有全连接层的丢弃(dropout)概率。
  • attention_probs_dropout_prob (float可选,默认为 0.0) — 注意力概率的丢弃比例。
  • initializer_range (float可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float可选,默认为 1e-12) — 层归一化(layer normalization)层使用的 epsilon 值。
  • image_size (int可选,默认为 384) — 每张图像的大小(分辨率)。
  • patch_size (int可选,默认为 16) — 每个补丁(patch)的大小(分辨率)。
  • num_channels (int可选,默认为 3) — 输入通道的数量。
  • is_hybrid (bool可选,默认为 False) — 是否使用混合主干网络。在加载 DPT-Hybrid 模型时很有用。
  • qkv_bias (bool可选,默认为 True) — 是否为查询 (queries)、键 (keys) 和值 (values) 添加偏置。
  • backbone_out_indices (list[int]可选,默认为 [2, 5, 8, 11]) — 从主干网络中使用的中间隐藏状态的索引。
  • readout_type (str可选,默认为 "project") — 处理 ViT 主干网络中间隐藏状态的读取 token (CLS token) 时使用的读取类型。可以是 ["ignore", "add", "project"] 之一。

    • “ignore” 简单地忽略 CLS token。
    • “add” 通过将表示相加,将来自 CLS token 的信息传递给所有其他 token。
    • “project” 通过在将表示投影回原始特征维度 D 之前(使用线性层及随后的 GELU 非线性激活),将读取内容拼接到所有其他 token 上来传递信息。
  • reassemble_factors (list[int]可选,默认为 [4, 2, 1, 0.5]) — 重组层(reassemble layers)的上/下采样因子。
  • neck_hidden_sizes (list[str]可选,默认为 [96, 192, 384, 768]) — 用于投影主干网络特征图的隐藏层大小。
  • fusion_hidden_size (int可选,默认为 256) — 融合前的通道数量。
  • head_in_index (int可选,默认为 -1) — 在头部使用的特征索引。
  • use_batch_norm_in_fusion_residual (bool可选,默认为 False) — 是否在融合块的预激活残差单元中使用批量归一化(batch normalization)。
  • 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) — 语义分类头的丢弃比例。
  • backbone_featmap_shape (list[int]可选,默认为 [1, 1024, 24, 24]) — 仅用于 hybrid 嵌入类型。主干网络特征图的形状。
  • neck_ignore_stages (list[int]可选,默认为 [0, 1]) — 仅用于 hybrid 嵌入类型。要忽略的读取层阶段。
  • backbone_config (Union[dict, "PreTrainedConfig"]可选,默认为 BitConfig()) — 主干网络模型的配置。仅在 is_hybridTrue 或你想要利用 AutoBackbone API 时使用。
  • pooler_output_size (int可选) — 池化层的维度。如果为 None,则默认为 hidden_size
  • pooler_act (str可选,默认为 "tanh") — 池化器使用的激活函数。

这是用于存储 DPTModel 配置的配置类。它用于根据指定的参数实例化 DPT 模型,定义模型架构。使用默认值实例化配置将产生与 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

< >

( do_resize: bool = True size: dict[str, int] | None = None resample: Resampling = <Resampling.BICUBIC: 3> keep_aspect_ratio: bool = False ensure_multiple_of: int = 1 do_rescale: bool = True rescale_factor: int | float = 0.00392156862745098 do_normalize: bool = True image_mean: float | list[float] | None = None image_std: float | list[float] | None = None do_pad: bool = False size_divisor: int | None = None do_reduce_labels: bool = False **kwargs )

参数

  • do_resize (bool可选,默认为 True) — 是否调整图像的(高度,宽度)尺寸。可以被 preprocess 中的 do_resize 覆盖。
  • size (dict[str, int]可选,默认为 {"height": 384, "width": 384}): 调整大小后的图像尺寸。可以被 preprocess 中的 size 覆盖。
  • resample (PILImageResampling可选,默认为 Resampling.BICUBIC) — 定义调整图像大小时使用的重采样过滤器。可以被 preprocess 中的 resample 覆盖。
  • keep_aspect_ratio (bool, 可选, 默认为 False) — 如果为 True,图像将调整为保持纵横比的最大可能尺寸。可以在 preprocess 中通过 keep_aspect_ratio 参数覆盖。
  • ensure_multiple_of (int, 可选, 默认为 1) — 如果 do_resizeTrue,图像将调整为该值的倍数尺寸。可以在 preprocess 中通过 ensure_multiple_of 参数覆盖。
  • 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_STANDARD_MEAN) — 归一化图像时使用的均值。这是一个浮点数或长度等于图像通道数的浮点数列表。可以在 preprocess 方法中通过 image_mean 参数覆盖。
  • image_std (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 归一化图像时使用的标准差。这是一个浮点数或长度等于图像通道数的浮点数列表。可以在 preprocess 方法中通过 image_std 参数覆盖。
  • do_pad (bool, 可选, 默认为 False) — 是否应用中心填充。这是在 DINOv2 论文中引入的,该论文将该模型与 DPT 结合使用。
  • size_divisor (int, 可选) — 如果 do_padTrue,则将图像尺寸填充为该值的倍数。这是在 DINOv2 论文中引入的,该论文将该模型与 DPT 结合使用。
  • do_reduce_labels (bool, 可选, 默认为 False) — 是否将语义分割图的所有标签值减 1。通常用于将 0 作为背景且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。可以在 preprocess 方法中通过 do_reduce_labels 参数覆盖。

构造一个 DPT 图像处理器。

preprocess

< >

( 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 do_resize: bool | None = None size: int | None = None keep_aspect_ratio: bool | None = None ensure_multiple_of: int | None = None resample: PIL.Image.Resampling | None = None do_rescale: bool | None = None rescale_factor: float | None = None do_normalize: bool | None = None image_mean: float | list[float] | None = None image_std: float | list[float] | None = None do_pad: bool | None = None size_divisor: int | None = None do_reduce_labels: bool | None = None return_tensors: str | transformers.utils.generic.TensorType | None = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: str | transformers.image_utils.ChannelDimension | None = None )

参数

  • images (ImageInput) — 待预处理的图像。期望是单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • segmentation_maps (ImageInput, 可选) — 待预处理的分割图。
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像尺寸。
  • size (dict[str, int], 可选, 默认为 self.size) — 调整尺寸后的图像大小。如果 keep_aspect_ratioTrue,图像将调整为保持纵横比的最大可能尺寸。如果设置了 ensure_multiple_of,图像将调整为该值的倍数尺寸。
  • keep_aspect_ratio (bool, 可选, 默认为 self.keep_aspect_ratio) — 是否保持图像的纵横比。如果为 False,图像将调整为 (size, size)。如果为 True,图像将调整以保持纵横比,并且尺寸将为最大可能值。
  • ensure_multiple_of (int, 可选, 默认为 self.ensure_multiple_of) — 确保图像尺寸是该值的倍数。
  • resample (int, 可选, 默认为 self.resample) — 调整图像尺寸时使用的重采样滤镜。这可以是枚举 PILImageResampling 之一。仅在 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) — 图像均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 图像标准差。
  • do_reduce_labels (bool, 可选, 默认为 self.do_reduce_labels) — 是否将语义分割图的所有标签值减 1。通常用于将 0 作为背景且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • 未设置:返回 np.ndarray 列表。
    • TensorType.PYTORCH'pt':返回 torch.Tensor 类型的 batch。
    • TensorType.NUMPY'np':返回 np.ndarray 类型的 batch。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST:(通道数, 高度, 宽度) 格式的图像。
    • ChannelDimension.LAST:(高度, 宽度, 通道数) 格式的图像。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:(通道数, 高度, 宽度) 格式的图像。
    • "channels_last"ChannelDimension.LAST:(高度, 宽度, 通道数) 格式的图像。
    • "none"ChannelDimension.NONE:(高度, 宽度) 格式的图像。

预处理一张或一批图像。

DPTImageProcessorFast

class transformers.DPTImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.dpt.image_processing_dpt.DPTImageProcessorKwargs] )

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

preprocess

< >

( 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: typing_extensions.Unpack[transformers.models.dpt.image_processing_dpt.DPTImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list, list, list]) — 待预处理的图像。期望是单张或一批像素值在 0 到 255 之间的图像。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • segmentation_maps (ImageInput, 可选) — 待预处理的分割图。
  • 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_rescale 设置为 True,用于重新缩放图像的比例因子。
  • do_normalize (bool | None.do_normalize) — 是否归一化图像。
  • image_mean (float | list[float] | tuple[float, ...] | None.image_mean) — 归一化时使用的图像均值。仅在 do_normalize 设置为 True 时有效。
  • image_std (float | list[float] | tuple[float, ...] | None.image_std) — 归一化时使用的图像标准差。仅在 do_normalize 设置为 True 时有效。
  • do_pad (bool | None.do_pad) — 是否填充图像。填充会执行至 batch 中的最大尺寸,或者每张图像固定为正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 图像填充的目标尺寸,格式为 {"height": int, "width" int}。必须大于预处理提供的任何图像尺寸。如果未提供 pad_size,图像将填充至 batch 中的最大高度和宽度。仅在 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:(通道数, 高度, 宽度) 格式的图像。
    • "channels_last"ChannelDimension.LAST:(高度, 宽度, 通道数) 格式的图像。
    • "none"ChannelDimension.NONE:(高度, 宽度) 格式的图像。
  • device (Annotated[Union[str, torch.device, NoneType], None]) — 处理图像的设备。如果未设置,则从输入图像中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None]) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool | None.disable_grouping) — 是否禁用按尺寸对图像进行分组,以便逐个处理图像而不是 batch 处理。如果为 None,若图像在 CPU 上,将设置为 True,否则为 False。此选择基于经验观察,详情见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int | None.image_seq_length) — 输入中每张图像所使用的图像 token 数量。为向后兼容而添加,但在未来的模型中,这应被设置为处理器的一个属性。
  • ensure_multiple_of (int, 可选, 默认为 1) — 如果 do_resizeTrue,图像将调整为该值的倍数尺寸。可以在 preprocess 中通过 ensure_multiple_of 参数覆盖。
  • size_divisor (<class 'int'>.size_divisor) — 确保高度和宽度都能被该值整除。
  • keep_aspect_ratio (bool, 可选, 默认为 False) — 如果为 True,图像将调整为保持纵横比的最大可能尺寸。可以在 preprocess 中通过 keep_aspect_ratio 参数覆盖。
  • do_reduce_labels (bool, 可选, 默认为 self.do_reduce_labels) — 是否将语义分割图的所有标签值减 1。通常用于将 0 作为背景且背景本身不包含在数据集所有类别中的数据集(例如 ADE20k)。背景标签将被替换为 255。

返回

<class 'transformers.image_processing_base.BatchFeature'>

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

post_process_semantic_segmentation

< >

( outputs target_sizes: list[tuple] | None = None ) semantic_segmentation

参数

  • outputs (DPTForSemanticSegmentation) — 模型的原始输出。
  • target_sizes (list[Tuple],长度为 batch_size, 可选) — 包含每个预测结果请求的最终尺寸 (高度, 宽度) 的元组列表。如果未设置,则不会调整预测结果的尺寸。

返回

语义分割

list[torch.Tensor] of length batch_size, where each item is a semantic segmentation map of shape (height, width) corresponding to the target_sizes entry (if target_sizes is specified). Each entry of each torch.Tensor correspond to a semantic class id.

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

后处理深度估计

< >

( outputs: DepthEstimatorOutput target_sizes: transformers.utils.generic.TensorType | list[tuple[int, int]] | None = None ) List[Dict[str, TensorType]]

参数

  • outputs (DepthEstimatorOutput) — 模型的原始输出。
  • target_sizes (TensorTypeList[Tuple[int, int]]可选) — 形状为 (batch_size, 2) 的张量或包含批次中每张图像目标尺寸(高度, 宽度)的元组列表(Tuple[int, int])。如果保持为 None,则不会调整预测结果的大小。

返回

List[Dict[str, TensorType]]

包含张量的字典列表,表示处理后的深度预测结果。

DepthEstimatorOutput 的原始输出转换为最终的深度预测和深度 PIL 图像。仅支持 PyTorch。

DPTModel

class transformers.DPTModel

< >

( config: DPTConfig add_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: FloatTensor output_hidden_states: bool | None = None **kwargs ) transformers.models.dpt.modeling_dpt.BaseModelOutputWithPoolingAndIntermediateActivationstuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 DPTImageProcessorFast 获取。有关详情,请参阅 DPTImageProcessorFast.call()processor_class 使用 DPTImageProcessorFast 处理图像)。
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详情,请参阅返回张量下的 hidden_states

返回

transformers.models.dpt.modeling_dpt.BaseModelOutputWithPoolingAndIntermediateActivationstuple(torch.FloatTensor)

一个 transformers.models.dpt.modeling_dpt.BaseModelOutputWithPoolingAndIntermediateActivationstorch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False 时),包含根据配置(DPTConfig)和输入而异的各种元素。

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

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

  • hidden_states (tuple[torch.FloatTensor, ...] | None.hidden_states, 当传入 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 每个层的输出)。

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

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

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

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

DPTModel 的前向传播方法,重写了 __call__ 特殊方法。

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

示例

DPTForDepthEstimation

class transformers.DPTForDepthEstimation

< >

( 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 (DPTForDepthEstimation) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。

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

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

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

forward

< >

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

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 DPTImageProcessorFast 获取。有关详情,请参阅 DPTImageProcessorFast.call()processor_class 使用 DPTImageProcessorFast 处理图像)。
  • labels (形状为 (batch_size, height, width)torch.LongTensor可选) — 用于计算损失的地面真值(Ground truth)深度估计图。
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详情,请参阅返回张量下的 hidden_states

返回

transformers.modeling_outputs.DepthEstimatorOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.DepthEstimatorOutputtorch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False 时),包含根据配置(DPTConfig)和输入而异的各种元素。

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

DPTForDepthEstimation 的前向传播方法,重写了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoImageProcessor, DPTForDepthEstimation
>>> 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("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: torch.FloatTensor | None = None labels: torch.LongTensor | None = None output_hidden_states: bool | None = None **kwargs ) transformers.modeling_outputs.SemanticSegmenterOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor可选) — 对应于输入图像的张量。像素值可以使用 DPTImageProcessorFast 获取。有关详情,请参阅 DPTImageProcessorFast.call()processor_class 使用 DPTImageProcessorFast 处理图像)。
  • labels (形状为 (batch_size, height, width)torch.LongTensor可选) — 用于计算损失的地面真值语义分割图。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详情,请参阅返回张量下的 hidden_states

返回

transformers.modeling_outputs.SemanticSegmenterOutput or tuple(torch.FloatTensor)

一个 transformers.modeling_outputs.SemanticSegmenterOutputtorch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False 时),包含根据配置(DPTConfig)和输入而异的各种元素。

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

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

    返回的 logits 大小不一定与传入的 pixel_values 相同。这是为了避免在用户需要将 logits 大小调整回原始图像大小时进行两次插值并损失质量。您应该始终检查 logits 形状并根据需要进行调整。

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

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

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

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

DPTForSemanticSegmentation 的前向传播方法,重写了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoImageProcessor, DPTForSemanticSegmentation
>>> 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("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
在 GitHub 上更新

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