Transformers documentation

ResNet

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

该模型于 2015-12-10 在 HF papers 上发表,并于 2022-03-14 贡献给 Hugging Face Transformers。

ResNet

概述

ResNet 模型由 Kaiming He、Xiangyu Zhang、Shaoqing Ren 和 Jian Sun 在 Deep Residual Learning for Image Recognition 中提出。我们的实现遵循了 Nvidia 所做的小改动,即在 bottleneck 的 3x3 卷积中应用 stride=2 进行下采样,而不是在第一个 1x1 卷积中。这通常被称为 “ResNet v1.5”。

ResNet 引入了残差连接,使得训练具有前所未见层数(多达 1000 层)的网络成为可能。ResNet 赢得了 2015 年 ILSVRC & COCO 竞赛,这是深度计算机视觉领域的一个重要里程碑。

该论文的摘要如下:

更深的神经网络更难训练。我们提出了一种残差学习框架,以简化比以往使用的网络深得多的网络的训练过程。我们显式地将各层重新表述为相对于层输入学习残差函数,而不是学习无参考的函数。我们提供了全面的实证证据,表明这些残差网络更容易优化,并且可以从显著增加的深度中获益并提升精度。在 ImageNet 数据集上,我们评估了深度高达 152 层的残差网络——比 VGG 网络深 8 倍,但复杂度仍然更低。这些残差网络的集成在 ImageNet 测试集上实现了 3.57% 的错误率。这一结果在 ILSVRC 2015 分类任务中获得了第一名。我们还对 CIFAR-10 上 100 层和 1000 层的情况进行了分析。 表示的深度对于许多视觉识别任务至关重要。仅凭借我们极深的表示,我们在 COCO 目标检测数据集上获得了 28% 的相对提升。深度残差网络是我们参加 ILSVRC & COCO 2015 竞赛的基础,在这些竞赛中,我们还获得了 ImageNet 检测、ImageNet 定位、COCO 检测和 COCO 分割任务的第一名。

下图展示了 ResNet 的架构。摘自原始论文。

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

资源

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

Image Classification

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

ResNetConfig

class transformers.ResNetConfig

< >

( 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 = Nonenum_channels: int = 3embedding_size: int = 64hidden_sizes: list[int] | tuple[int, ...] | None = (256, 512, 1024, 2048)depths: list[int] | tuple[int, ...] | None = (3, 4, 6, 3)layer_type: str = 'bottleneck'hidden_act: str = 'relu'downsample_in_first_stage: bool = Falsedownsample_in_bottleneck: bool = False )

参数

  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • embedding_size (int,可选,默认为 64) — 嵌入和隐藏状态的维度。
  • hidden_sizes (Union[list[int], tuple[int, ...]],可选,默认为 (256, 512, 1024, 2048)) — 模型每个阶段的维度(隐藏层大小)。
  • depths (Union[list[int], tuple[int, ...]],可选,默认为 (3, 4, 6, 3)) — Transformer 中每一层的深度。
  • layer_type (str,可选,默认为 "bottleneck") — 要使用的层类型,可以是 "basic"(用于较小的模型,如 resnet-18 或 resnet-34)或 "bottleneck"(用于较大的模型,如 resnet-50 及以上)。
  • hidden_act (str,可选,默认为 relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • downsample_in_first_stage(bool,可选,默认为 False)— 如果为 True,第一阶段将使用 stride 为 2 的方式对输入进行下采样。
  • downsample_in_bottleneck (bool,可选,默认为 False) — 如果为 True,ResNetBottleNeckLayer 中的第一个 1x1 卷积层将使用 stride 为 2 的方式对输入进行下采样。

这是用于存储 ResNetModel 配置的类。它根据指定的参数实例化 Resnet 模型,并定义模型架构。使用默认值实例化配置将生成与 microsoft/resnet-50 类似的配置。

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

示例:

>>> from transformers import ResNetConfig, ResNetModel

>>> # Initializing a ResNet resnet-50 style configuration
>>> configuration = ResNetConfig()

>>> # Initializing a model (with random weights) from the resnet-50 style configuration
>>> model = ResNetModel(configuration)

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

validate_layer_type

< >

( )

检查 layer_types 是否已正确定义。

ResNetModel

class transformers.ResNetModel

< >

( config: ResNetConfig )

参数

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

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

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

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

forward

< >

( pixel_values: Tensoroutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → BaseModelOutputWithPoolingAndNoAttention or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 ConvNextImageProcessor 获取像素值。有关详细信息,请参阅 ConvNextImageProcessor.call()(processor_class 使用 ConvNextImageProcessor 处理图像)。
  • output_hidden_states (bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的 hidden_states。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。

返回值

BaseModelOutputWithPoolingAndNoAttention 或 tuple(torch.Tensor)

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

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

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

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

  • pooler_output(形状为 (batch_size, hidden_size) 的 torch.Tensor)— 在空间维度上执行池化操作后的最后一层隐藏状态。

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

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

示例:

ResNetForImageClassification

class transformers.ResNetForImageClassification

< >

( config: ResNetConfig )

参数

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

带有图像分类头的 ResNet 模型(在池化特征之上添加一个线性层),例如用于 ImageNet。

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

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

forward

< >

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

参数

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

返回值

ImageClassifierOutputWithNoAttention 或 tuple(torch.Tensor)

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

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

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

  • loss (torch.Tensor,形状为 (1,),可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。
  • logits(形状为 (batch_size, config.num_labels) 的 torch.Tensor)— 分类(或当 config.num_labels==1 时为回归)得分(SoftMax 之前)。
  • hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个阶段输出的一个张量),形状为 (batch_size, num_channels, height, width)。模型在每个阶段输出处的隐藏状态(也称为特征图)。

示例:

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/resnet-50")
>>> model = ResNetForImageClassification.from_pretrained("microsoft/resnet-50")

>>> 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])
...
Update on GitHub