Transformers 文档

大迁移(BiT)

大迁移 (BiT)

概述

BiT模型由Alexander Kolesnikov、Lucas Beyer、Xiaohua Zhai、Joan Puigcerver、Jessica Yung、Sylvain Gelly和Neil Houlsby在Big Transfer (BiT): General Visual Representation Learning中提出。 BiT是一种简单的方法,用于扩展类似ResNet架构(特别是ResNetv2)的预训练。该方法在迁移学习方面带来了显著的改进。

论文的摘要如下:

预训练表示的转移在训练深度神经网络用于视觉任务时,提高了样本效率并简化了超参数调优。我们重新审视了在大规模监督数据集上进行预训练并在目标任务上微调模型的范式。我们扩大了预训练的规模,并提出了一个我们称之为大转移(BiT)的简单方法。通过结合一些精心选择的组件,并使用简单的启发式方法进行转移,我们在超过20个数据集上实现了强大的性能。BiT在令人惊讶的广泛数据范围内表现良好——从每类1个样本到总共1M个样本。BiT在ILSVRC-2012上达到了87.5%的top-1准确率,在CIFAR-10上达到了99.4%,在19个任务的视觉任务适应基准(VTAB)上达到了76.3%。在小数据集上,BiT在每类10个样本的情况下在ILSVRC-2012上达到了76.8%,在每类10个样本的情况下在CIFAR-10上达到了97.0%。我们对导致高转移性能的主要组件进行了详细分析。

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

使用提示

  • BiT 模型在架构上等同于 ResNetv2,除了以下几点:1) 所有的批量归一化层都被替换为 组归一化, 2) 卷积层使用了 权重标准化。作者展示了这两者的结合对于大批量训练非常有用,并且对迁移学习有显著影响。

资源

一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用BiT。

Image Classification

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

BitConfig

transformers.BitConfig

< >

( num_channels = 3 embedding_size = 64 hidden_sizes = [256, 512, 1024, 2048] depths = [3, 4, 6, 3] layer_type = 'preactivation' hidden_act = 'relu' global_padding = None num_groups = 32 drop_path_rate = 0.0 embedding_dynamic_padding = False output_stride = 32 width_factor = 1 out_features = None out_indices = None **kwargs )

参数

  • num_channels (int, optional, defaults to 3) — 输入通道的数量。
  • embedding_size (int, optional, defaults to 64) — 嵌入层的维度(隐藏大小)。
  • hidden_sizes (List[int], optional, defaults to [256, 512, 1024, 2048]) — 每个阶段的维度(隐藏大小)。
  • depths (List[int], 可选, 默认为 [3, 4, 6, 3]) — 每个阶段的深度(层数)。
  • layer_type (str, 可选, 默认为 "preactivation") — 要使用的层,可以是 "preactivation""bottleneck".
  • hidden_act (str, 可选, 默认为 "relu") — 每个块中的非线性激活函数。如果是字符串,支持 "gelu", "relu", "selu""gelu_new"
  • global_padding (str, 可选) — 用于卷积层的填充策略。可以是 "valid""same"None
  • num_groups (int, 可选, 默认为 32) — 用于 BitGroupNormActivation 层的组数。
  • drop_path_rate (float, optional, defaults to 0.0) — 随机深度的丢弃路径率。
  • embedding_dynamic_padding (bool, optional, defaults to False) — 是否使用动态填充为嵌入层。
  • output_stride (int, optional, 默认为 32) — 模型的输出步长。
  • width_factor (int, optional, 默认为 1) — 模型的宽度因子。
  • out_features (List[str], 可选) — 如果用作骨干网络,输出特征的列表。可以是"stem""stage1""stage2"等。 (取决于模型有多少个阶段)。如果未设置且out_indices已设置,将默认为相应的阶段。如果未设置且out_indices也未设置,将默认为最后一个阶段。必须与stage_names属性中定义的顺序相同。
  • out_indices (List[int], 可选) — 如果用作骨干网络,输出特征的索引列表。可以是0、1、2等(取决于模型有多少个阶段)。如果未设置且out_features已设置,将默认为相应的阶段。 如果未设置且out_features也未设置,将默认为最后一个阶段。必须与stage_names属性中定义的顺序相同。

这是用于存储BitModel配置的配置类。它用于根据指定的参数实例化一个BiT模型,定义模型架构。使用默认值实例化配置将产生与BiT google/bit-50架构类似的配置。

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

示例:

>>> from transformers import BitConfig, BitModel

>>> # Initializing a BiT bit-50 style configuration
>>> configuration = BitConfig()

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

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

BitImageProcessor

transformers.BitImageProcessor

< >

( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = do_center_crop: bool = True crop_size: typing.Dict[str, int] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的(高度,宽度)尺寸调整为指定的 size。可以在 preprocess 方法中被 do_resize 覆盖。
  • size (Dict[str, int] optional, defaults to {"shortest_edge" -- 224}): 调整后图像的大小。图像的最短边将调整为size[“shortest_edge”],最长边将调整以保持输入的宽高比。可以在preprocess方法中通过size覆盖此设置。
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BICUBIC) — 如果调整图像大小,则使用的重采样过滤器。可以在 preprocess 方法中通过 resample 覆盖。
  • do_center_crop (bool, 可选, 默认为 True) — 是否将图像中心裁剪到指定的 crop_size。可以在 preprocess 方法中通过 do_center_crop 覆盖此设置。
  • crop_size (Dict[str, int] optional, defaults to 224) — 应用center_crop后输出图像的大小。可以在preprocess方法中通过crop_size覆盖此设置。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 rescale_factor 重新缩放图像。可以在 preprocess 方法中被 do_rescale 覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以在 preprocess 方法中被 rescale_factor 覆盖。
  • do_normalize — 是否对图像进行归一化。可以在 preprocess 方法中通过 do_normalize 进行覆盖。
  • image_mean (floatList[float], 可选, 默认为 OPENAI_CLIP_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,长度为图像中的通道数。可以通过 preprocess 方法中的 image_mean 参数进行覆盖。
  • image_std (floatList[float], 可选, 默认为 OPENAI_CLIP_MEAN) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以在 preprocess 方法中通过 image_std 参数覆盖。 可以在 preprocess 方法中通过 image_std 参数覆盖。
  • do_convert_rgb (bool, optional, defaults to True) — 是否将图像转换为RGB.

构建一个BiT图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('torch.Tensor')]] do_resize: bool = None size: typing.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: int = None do_rescale: bool = None rescale_factor: float = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None do_convert_rgb: bool = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • 图像 (ImageInput) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置 do_rescale=False.
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小.
  • size (Dict[str, int], 可选, 默认为 self.size) — 调整大小后的图像尺寸。图像的最短边将调整为size[“shortest_edge”],最长边将调整以保持输入的宽高比。
  • resample (int, 可选, 默认为 self.resample) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举 PILImageResampling 中的一个。只有在 do_resize 设置为 True 时才会生效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否对图像进行中心裁剪。
  • crop_size (Dict[str, int], 可选, 默认为 self.crop_size) — 中心裁剪的大小。仅在 do_center_crop 设置为 True 时有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否对图像进行重新缩放.
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的重新缩放因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否对图像进行归一化处理。
  • image_mean (floatList[float], 可选, 默认为 self.image_mean) — 用于归一化的图像均值。仅在 do_normalize 设置为 True 时有效。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 用于归一化的图像标准差。仅在 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将图像转换为RGB.
  • return_tensors (strTensorType, 可选) — 返回的张量类型。可以是以下之一:
    • 未设置:返回一个 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回一个类型为 tf.Tensor 的批次。
    • TensorType.PYTORCH'pt':返回一个类型为 torch.Tensor 的批次。
    • TensorType.NUMPY'np':返回一个类型为 np.ndarray 的批次。
    • TensorType.JAX'jax':返回一个类型为 jax.numpy.ndarray 的批次。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST: 图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE: 图像格式为 (height, width)。

预处理一张图像或一批图像。

BitModel

transformers.BitModel

< >

( config )

参数

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

裸的BiT模型输出原始特征,没有任何特定的头部。 这个模型是PyTorch torch.nn.Module 的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( pixel_values: Tensor output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见BitImageProcessor.call()
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(BitConfig)和输入。

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

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

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, num_channels, height, width)

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

BitModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/bit-50")
>>> model = BitModel.from_pretrained("google/bit-50")

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

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

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 2048, 7, 7]

BitForImageClassification

transformers.BitForImageClassification

< >

( config )

参数

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

BiT模型,顶部带有图像分类头(在池化特征之上的线性层),例如用于ImageNet。

该模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见BitImageProcessor.call()
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算图像分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

一个 transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(BitConfig)和输入。

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

BitForImageClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("google/bit-50")
>>> model = BitForImageClassification.from_pretrained("google/bit-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])
tiger cat
< > Update on GitHub