Transformers documentation

UPerNet

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2018-07-26 在 HF papers 上发表,并于 2023-01-16 贡献至 Hugging Face Transformers。

UPerNet

概述

UPerNet 模型由 Tete Xiao、Yingcheng Liu、Bolei Zhou、Yuning Jiang 和 Jian Sun 在 Unified Perceptual Parsing for Scene Understanding 中提出。UPerNet 是一个通用框架,能够利用 ConvNeXt 或 Swin 等任意视觉骨干网络,有效地从图像中分割出广泛的概念。

该论文的摘要如下:

人类在多个层面上感知视觉世界:我们能够轻松地对场景进行分类并检测其中的物体,同时还能识别物体的纹理和表面,以及它们不同的组成部分。本文研究了一项名为统一感知解析(Unified Perceptual Parsing)的新任务,该任务要求机器视觉系统从给定图像中识别尽可能多的视觉概念。我们开发了一个名为 UPerNet 的多任务框架以及一种训练策略,以从异构的图像标注中学习。我们在统一感知解析任务上对该框架进行了基准测试,结果表明它能够有效地从图像中分割出广泛的概念。训练好的网络还被进一步应用于发现自然场景中的视觉知识。

drawing UPerNet framework. Taken from the original paper.

该模型由 nielsr 贡献。原始代码基于 OpenMMLab 的 mmsegmentation,在此处。

使用示例

UPerNet 是一个用于语义分割的通用框架。它可以与任意视觉骨干网络配合使用,例如:

from transformers import SwinConfig, UperNetConfig, UperNetForSemanticSegmentation


backbone_config = SwinConfig(out_features=["stage1", "stage2", "stage3", "stage4"])

config = UperNetConfig(backbone_config=backbone_config)
model = UperNetForSemanticSegmentation(config)

若要使用其他视觉骨干网络,例如 ConvNeXt,只需使用相应的骨干网络实例化模型即可:

from transformers import ConvNextConfig, UperNetConfig, UperNetForSemanticSegmentation


backbone_config = ConvNextConfig(out_features=["stage1", "stage2", "stage3", "stage4"])

config = UperNetConfig(backbone_config=backbone_config)
model = UperNetForSemanticSegmentation(config)

请注意,这将随机初始化模型的所有权重。

资源

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

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

UperNetConfig

class transformers.UperNetConfig

< >

( 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 = Nonebackbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonehidden_size: int = 512initializer_range: float = 0.02pool_scales: list[int] | tuple[int, ...] = (1, 2, 3, 6)use_auxiliary_head: bool = Trueauxiliary_loss_weight: float = 0.4auxiliary_in_channels: int | None = Noneauxiliary_channels: int = 256auxiliary_num_convs: int = 1auxiliary_concat_input: bool = Falseloss_ignore_index: int = 255 )

参数

  • backbone_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 主干模型的配置。
  • hidden_size (int,可选,默认为 512) — 隐藏表示的维度。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • pool_scales (tuple[int],可选,默认为 [1, 2, 3, 6]) — 应用于最后一个特征图的 Pooling Pyramid Module 中使用的池化比例。
  • use_auxiliary_head (bool,可选,默认为 True) — 是否在训练期间使用辅助头。
  • auxiliary_loss_weight (float,可选,默认为 0.4) — 辅助头交叉熵损失的权重。
  • auxiliary_in_channels (int,可选,默认为 256) — 辅助头中的输入通道数。
  • auxiliary_channels (int,可选,默认为 256) — 辅助头中使用的通道数。
  • auxiliary_num_convs (int,可选,默认为 1) — 辅助头中使用的卷积层数量。
  • auxiliary_concat_input (bool,可选,默认为 False) — 是否将辅助头的输出与输入拼接,然后再送入分类层。
  • loss_ignore_index (int,可选,默认为 255) — 损失函数中忽略的索引。

这是用于存储 UpernetModel 配置的类。它根据指定的参数实例化 Upernet 模型,并定义模型架构。使用默认值实例化配置将得到与 openmmlab/upernet-convnext-tiny 类似的配置。

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

示例:

>>> from transformers import UperNetConfig, UperNetForSemanticSegmentation

>>> # Initializing a configuration
>>> configuration = UperNetConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = UperNetForSemanticSegmentation(configuration)

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

UperNetForSemanticSegmentation

class transformers.UperNetForSemanticSegmentation

< >

( config: UperNetConfig )

参数

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

利用任意视觉骨干网络的 UperNet 框架,例如用于 ADE20k、CityScapes。

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonelabels: typing.Optional[torch.Tensor] = Nonereturn_dict: bool | None = None**kwargs ) → SemanticSegmenterOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 对应输入图像的张量。像素值可通过 SegformerImageProcessor 获取。有关详细信息,请参阅 SegformerImageProcessor.call()(processor_class 使用 SegformerImageProcessor 处理图像)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的 attentions。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • labels(形状为 (batch_size, height, width) 的 torch.LongTensor,可选) — 用于计算损失的语义分割真值图。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

SemanticSegmenterOutput 或 tuple(torch.Tensor)

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

UperNetForSemanticSegmentation 的 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, UperNetForSemanticSegmentation
>>> from PIL import Image
>>> from huggingface_hub import hf_hub_download

>>> image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny")
>>> model = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny")

>>> filepath = hf_hub_download(
...     repo_id="hf-internal-testing/fixtures_ade20k", filename="ADE_val_00000001.jpg", repo_type="dataset"
... )
>>> image = Image.open(filepath).convert("RGB")

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

>>> outputs = model(**inputs)

>>> logits = outputs.logits  # shape (batch_size, num_labels, height, width)
>>> list(logits.shape)
[1, 150, 512, 512]
Update on GitHub