Transformers 文档

SegFormer

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2021 年 5 月 31 日在 HF papers 上发布,并于 2021 年 10 月 28 日贡献给 Hugging Face Transformers。

SegFormer

SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers 是一种语义分割模型,它将分层 Transformer 编码器(Mix Transformer,MiT)与轻量级全 MLP 解码器相结合。它避免了位置编码和复杂的解码器,在 ADE20K 和 Cityscapes 等基准测试中实现了最先进的性能。这种简单且轻量级的设计更高效、更具可扩展性。

下图展示了 SegFormer 的架构。

您可以在 NVIDIA 组织下找到所有原始的 SegFormer 检查点。

此模型由 nielsr 贡献。

点击右侧边栏中的 SegFormer 模型,查看如何将 SegFormer 应用于不同视觉任务的更多示例。

下面的示例演示了如何使用 PipelineAutoModel 类进行语义分割。

流水线
自动模型
from transformers import pipeline


pipeline = pipeline(task="image-segmentation", model="nvidia/segformer-b0-finetuned-ade-512-512")
pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")

注意事项

  • SegFormer 适用于任何输入尺寸,它会将输入填充(padding)到可被 config.patch_sizes 整除的大小。

  • 最重要的预处理步骤是随机裁剪并将所有图像填充到相同大小(例如 512x512 或 640x640),然后进行归一化。

  • 某些数据集(如 ADE20k)在标注分割中使用 0 索引作为背景,但其标签中并不包含“背景”类。SegformerForImageProcessor 中的 do_reduce_labels 参数用于将所有标签减去 1。为了确保不对背景类计算损失,它将标注图中的 0 替换为 255,即损失函数的 ignore_index

    其他数据集可能包含背景类和标签,在这种情况下,do_reduce_labels 应设为 False

from transformers import SegformerImageProcessor


processor = SegformerImageProcessor(do_reduce_labels=True)

资源

SegformerConfig

class transformers.SegformerConfig

< >

(参数定义略,均为技术术语,保持原状)

参数

  • 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 (Union[list[int], tuple[int, ...]], 可选, 默认为 (32, 64, 160, 256)) — 模型每个阶段的维度(隐藏大小)。
  • patch_sizes (list[int], 可选, 默认为 [7, 3, 3, 3]) — 每个编码器块前的 Patch 大小。
  • strides (list[int], 可选, 默认为 [4, 2, 2, 2]) — 每个编码器块前的步长。
  • num_attention_heads (Union[list[int], tuple[int, ...]], 可选, 默认为 (1, 2, 5, 8)) — Transformer 解码器中每个注意力层的注意力头数。
  • mlp_ratios (list[int], 可选, 默认为 [4, 4, 4, 4]) — 编码器块中 Mix FFN 的隐藏层大小与输入层大小的比率。
  • 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) — 注意力概率的丢弃比例。
  • classifier_dropout_prob (Union[float, int], 可选, 默认为 0.1) — 分类器的丢弃比例。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态分布初始化器(truncated_normal_initializer)的标准差。
  • drop_path_rate (Union[float, int], 可选, 默认为 0.1) — 用于 Patch 融合的 drop path 比率。
  • layer_norm_eps (float, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon 值。
  • decoder_hidden_size (int, 可选, 默认为 256) — 隐藏表示的维度。
  • semantic_loss_ignore_index (int, 可选, 默认为 255) — 语义分割模型损失函数忽略的索引。
  • reshape_last_stage (bool, 可选, 默认为 True) — 是否重塑最后一个阶段的输出。

这是用于存储 SegformerModel 配置的配置类。它根据指定的参数实例化 Segformer 模型,定义模型架构。使用默认值实例化配置将产生与 ByteDance-Seed/Seed-OSS-36B-Instruct 类似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。阅读 PreTrainedConfig 的文档以获取更多信息。

示例

>>> from transformers import SegformerModel, SegformerConfig

>>> # Initializing a SegFormer nvidia/segformer-b0-finetuned-ade-512-512 style configuration
>>> configuration = SegformerConfig()

>>> # Initializing a model from the nvidia/segformer-b0-finetuned-ade-512-512 style configuration
>>> model = SegformerModel(configuration)

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

SegformerImageProcessor

class transformers.SegformerImageProcessor

< >

( **kwargs: typing_extensions.Unpack[transformers.models.segformer.image_processing_segformer.SegformerImageProcessorKwargs] )

参数

  • do_reduce_labels (bool, kwargs, 可选, 默认为 self.do_reduce_labels) — 是否将分割图的所有标签值减 1。通常用于背景标签为 0 且数据集的某些类中不包含背景本身的场景(例如 ADE20k)。背景标签将被替换为 255。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 列在上方;有关支持的完整参数列表,请参阅 TypedDict 类。

构建一个 SegformerImageProcessor 图像处理器。

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.segformer.image_processing_segformer.SegformerImageProcessorKwargs] ) ~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_reduce_labels (bool, kwargs, 可选, 默认为 self.do_reduce_labels) — 是否将分割图的所有标签值减 1。通常用于背景标签为 0 且数据集的某些类中不包含背景本身的场景(例如 ADE20k)。背景标签将被替换为 255。
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt' 则返回堆叠后的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 列在上方;有关支持的完整参数列表,请参阅 TypedDict 类。

返回

~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 (SegformerForSemanticSegmentation) — 模型的原始输出。
  • target_sizes (长度为 batch_sizelist[Tuple], 可选) — 对应每个预测请求的最终尺寸(高度,宽度)的元组列表。如果未设置,则不会调整预测结果的大小。

返回

语义分割

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.

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

SegformerImageProcessorPil

class transformers.SegformerImageProcessorPil

< >

( **kwargs: typing_extensions.Unpack[transformers.models.segformer.image_processing_pil_segformer.SegformerImageProcessorKwargs] )

用于 Segformer 的 PIL 后端,支持 reduce_label。

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.segformer.image_processing_pil_segformer.SegformerImageProcessorKwargs] ) ~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_reduce_labels (bool, kwargs, 可选, 默认为 self.do_reduce_labels) — 是否将分割图的所有标签值减 1。通常用于背景标签为 0 且数据集的某些类中不包含背景本身的场景(例如 ADE20k)。背景标签将被替换为 255。
  • return_tensors (strTensorType, 可选) — 如果设置为 'pt' 则返回堆叠后的张量,否则返回张量列表。
  • **kwargs (ImagesKwargs, 可选) — 额外的图像预处理选项。模型特定的 kwargs 列在上方;有关支持的完整参数列表,请参阅 TypedDict 类。

返回

~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 (SegformerForSemanticSegmentation) — 模型的原始输出。
  • target_sizes (长度为 batch_sizelist[Tuple], 可选) — 对应每个预测请求的最终尺寸(高度,宽度)的元组列表。如果未设置,则不会调整预测结果的大小。

返回

语义分割

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.

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

SegformerModel

class transformers.SegformerModel

< >

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

基础 Segformer 模型,输出原始隐藏状态,顶部没有任何特定的头部。

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

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

forward

< >

( pixel_values: FloatTensor **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) BaseModelOutputtuple(torch.FloatTensor)

参数

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

返回

BaseModelOutput 或 tuple(torch.FloatTensor)

一个 BaseModelOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),根据配置(SegformerConfig)和输入包含各种元素。

SegformerModel 的前向传播方法,覆盖了 __call__ 特殊方法。

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

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

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

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

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

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

示例

SegformerDecodeHead

class transformers.SegformerDecodeHead

< >

( config )

forward

< >

( encoder_hidden_states: FloatTensor **kwargs )

SegformerForImageClassification

class transformers.SegformerForImageClassification

< >

( 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] )

参数

SegFormer 模型转换器,顶部带有图像分类头(最终隐藏状态之上的线性层),例如用于 ImageNet。

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

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

forward

< >

( pixel_values: torch.FloatTensor | None = None labels: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) SegFormerImageClassifierOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor可选) — 对应于输入图像的张量。像素值可以使用 SegformerImageProcessor 获取。详细信息请参阅 SegformerImageProcessor.__call__()processor_class 使用 SegformerImageProcessor 处理图像)。
  • labels (形状为 (batch_size,)torch.LongTensor可选) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方误差损失);如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。

返回

SegFormerImageClassifierOutputtuple(torch.FloatTensor)

一个 SegFormerImageClassifierOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),根据配置(SegformerConfig)和输入包含各种元素。

SegformerForImageClassification 的前向传播方法,覆盖了 __call__ 特殊方法。

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

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

  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。

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

示例

>>> from transformers import AutoImageProcessor, SegformerForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("ByteDance-Seed/Seed-OSS-36B-Instruct")
>>> model = SegformerForImageClassification.from_pretrained("ByteDance-Seed/Seed-OSS-36B-Instruct")

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

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...

SegformerForSemanticSegmentation

class transformers.SegformerForSemanticSegmentation

< >

( 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] )

参数

SegFormer 模型转换器,顶部带有全 MLP 解码头,例如用于 ADE20k, CityScapes。

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

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

forward

< >

( pixel_values: FloatTensor labels: torch.LongTensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) SemanticSegmenterOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 SegformerImageProcessor 获取。详细信息请参阅 SegformerImageProcessor.__call__()processor_class 使用 SegformerImageProcessor 处理图像)。
  • labels (形状为 (batch_size, height, width)torch.LongTensor可选) — 用于计算损失的地面真值语义分割图。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels > 1,则计算分类损失(交叉熵损失)。

返回

SemanticSegmenterOutputtuple(torch.FloatTensor)

一个 SemanticSegmenterOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=Falseconfig.return_dict=False),根据配置(SegformerConfig)和输入包含各种元素。

SegformerForSemanticSegmentation 的前向传播方法,覆盖了 __call__ 特殊方法。

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

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

示例

>>> from transformers import AutoImageProcessor, SegformerForSemanticSegmentation
>>> from PIL import Image
>>> import httpx
>>> from io import BytesIO

>>> image_processor = AutoImageProcessor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
>>> model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits  # shape (batch_size, num_labels, height/4, width/4)
>>> list(logits.shape)
[1, 150, 128, 128]
在 GitHub 上更新

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