Transformers documentation

骨干网络

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

and get access to the augmented documentation experience

to get started

骨干网络

更高级的计算机视觉任务,例如目标检测或图像分割,会同时使用多个模型来生成预测。分别使用独立的模型作为backbone、neck 和 head。backbone 从输入图像中提取有用的特征并生成特征图,neck 对特征图进行组合和处理,head 则利用这些特征图做出预测。

使用 from_pretrained() 加载骨干网络,并通过 out_indices 参数指定要提取特征图的层(以索引表示)。

from transformers import AutoBackbone

model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,))

本指南介绍了骨干类、来自 timm 库的骨干网络,以及如何使用它们提取特征。

骨干类

有两个骨干类。

  • ~transformers.utils.BackboneMixin 允许你加载 backbone,并包含用于从 config 中提取特征图和索引的函数。
  • ~transformers.utils.BackboneConfigMixin 允许您设置、对齐并验证骨干网络配置中的特征图和索引。

请参阅 Backbone API 文档,以查看哪些模型支持 backbone。

加载 Transformers 骨干网络有两种方式:AutoBackbone 和特定模型的骨干网络类。

AutoBackbone
特定于模型的骨干网络

如果受支持,AutoClass API 会通过 from_pretrained() 自动加载预训练视觉模型作为骨干网络。

将 out_indices 参数设置为你希望获取特征图的目标层。如果你知道该层的名称,也可以使用 out_features。这两个参数可以互换使用,但如果同时使用,请确保它们指向同一层。

当未使用 out_indices 或 out_features 时,backbone 会返回最后一层的特征图。下面的示例代码使用 out_indices=(1,) 来获取第一层的特征图。

from transformers import AutoImageProcessor, AutoBackbone

model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,))

timm 骨干网络

timm 是一个用于训练和推理的视觉模型集合。Transformers 支持将 timm 模型作为骨干网络,通过 TimmBackbone 和 TimmBackboneConfig 类实现。在 backbone 中设置所需的骨干网络检查点,即可创建一个使用 Timm 骨干网络且权重随机初始化的模型。

from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, TimmBackboneConfig

backbone_config = TimmBackboneConfig(backbone="resnet50", out_indices=[-1])
config = MaskFormerConfig(backbone_config=backbone_config)
model = MaskFormerForInstanceSegmentation(config)

您也可以显式调用 TimmBackboneConfig 类来加载并创建一个预训练的 timm 骨干网络。

from transformers import TimmBackboneConfig

backbone_config = TimmBackboneConfig("resnet50")

将骨干网络配置传递给模型配置,并使用该骨干网络实例化模型头 MaskFormerForInstanceSegmentation。

from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation

config = MaskFormerConfig(backbone_config=backbone_config)
model = MaskFormerForInstanceSegmentation(config)

特征提取

Backbone 用于提取图像特征。将图像通过 backbone 即可得到特征图。

加载并预处理图像,然后将其传入骨干网络。以下示例从第一层提取特征图。

from transformers import AutoImageProcessor, AutoBackbone
import torch
from PIL import Image
import requests

model = AutoBackbone.from_pretrained("microsoft/swin-tiny-patch4-window7-224", out_indices=(1,))
processor = AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224")

url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)

inputs = processor(image, return_tensors="pt")
outputs = model(**inputs)

特征存储在输出中的 feature_maps 属性中,并从中访问。

feature_maps = outputs.feature_maps
list(feature_maps[0].shape)
[1, 96, 56, 56]
Update on GitHub