大迁移 (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%。我们对导致高转移性能的主要组件进行了详细分析。
使用提示
- BiT 模型在架构上等同于 ResNetv2,除了以下几点:1) 所有的批量归一化层都被替换为 组归一化, 2) 卷积层使用了 权重标准化。作者展示了这两者的结合对于大批量训练非常有用,并且对迁移学习有显著影响。
资源
一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用BiT。
- BitForImageClassification 由这个 示例脚本 和 笔记本 支持。
- 另请参阅:图像分类任务指南
如果您有兴趣提交资源以包含在此处,请随时打开一个 Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
BitConfig
类 transformers.BitConfig
< source >( 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 toFalse
) — 是否使用动态填充为嵌入层。 - 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
< source >( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling =
参数
- 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 (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,则使用的缩放因子。可以在preprocess
方法中被rescale_factor
覆盖。 - do_normalize —
是否对图像进行归一化。可以在
preprocess
方法中通过do_normalize
进行覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为OPENAI_CLIP_MEAN
) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,长度为图像中的通道数。可以通过preprocess
方法中的image_mean
参数进行覆盖。 - image_std (
float
或List[float]
, 可选, 默认为OPENAI_CLIP_MEAN
) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或与图像通道数长度相同的浮点数列表。可以在preprocess
方法中通过image_std
参数覆盖。 可以在preprocess
方法中通过image_std
参数覆盖。 - do_convert_rgb (
bool
, optional, defaults toTrue
) — 是否将图像转换为RGB.
构建一个BiT图像处理器。
预处理
< source >( 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] =
参数
- 图像 (
ImageInput
) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置do_rescale=False
. - do_resize (
bool
, optional, defaults toself.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 toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 中心裁剪的大小。仅在do_center_crop
设置为True
时有效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否对图像进行重新缩放. - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化处理。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。仅在do_normalize
设置为True
时有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。仅在do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为RGB. - return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
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 (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理一张图像或一批图像。
BitModel
类 transformers.BitModel
< source >( config )
参数
- config (BitConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的BiT模型输出原始特征,没有任何特定的头部。 这个模型是PyTorch torch.nn.Module 的子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( pixel_values: Tensor output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 tuple(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.BaseModelOutputWithPoolingAndNoAttention
或 tuple(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
< source >( config )
参数
- config (BitConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
BiT模型,顶部带有图像分类头(在池化特征之上的线性层),例如用于ImageNet。
该模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( 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.ImageClassifierOutputWithNoAttention 或 tuple(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.ImageClassifierOutputWithNoAttention 或 tuple(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