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-like 架构(特别是 ResNetv2)的预训练。该方法显著改进了迁移学习。
论文摘要如下:
预训练表示的迁移提高了样本效率,并简化了用于视觉的深度神经网络训练时的超参数调整。我们重新审视了在大规模监督数据集上进行预训练并在目标任务上对模型进行微调的范式。我们扩展了预训练,并提出了一种我们称之为 Big Transfer (BiT) 的简单方案。通过结合一些精心选择的组件,并使用简单的启发式方法进行迁移,我们在 20 多个数据集上取得了强大的性能。BiT 在令人惊讶的广泛数据范围内表现良好——从每个类别 1 个示例到总共 100 万个示例。BiT 在 ILSVRC-2012 上实现了 87.5% 的 Top-1 准确率,在 CIFAR-10 上实现了 99.4% 的准确率,在 19 个任务的 Visual Task Adaptation Benchmark (VTAB) 上实现了 76.3% 的准确率。在小型数据集上,BiT 在 ILSVRC-2012 上以每个类别 10 个示例实现了 76.8% 的准确率,在 CIFAR-10 上以每个类别 10 个示例实现了 97.0% 的准确率。我们对导致高迁移性能的主要组件进行了详细分析。
使用技巧
- BiT 模型在架构上等同于 ResNetv2,除了:1) 所有批量归一化层都被 组归一化 取代,2) 卷积层使用 权重标准化。作者表明,两者的结合对于使用大批量进行训练很有用,并且对迁移学习有显著影响。
资源
Hugging Face 官方和社区(由 🌎 指示)资源列表,可帮助您开始使用 BiT。
- BitForImageClassification 由此 示例脚本 和 notebook 支持。
- 另请参阅:图像分类任务指南
如果您有兴趣在此处提交资源,请随时开启 Pull Request,我们将对其进行审查!该资源最好能展示一些新内容,而不是重复现有资源。
BitConfig
class 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
, 可选, 默认为 3) — 输入通道数。 - embedding_size (
int
, 可选, 默认为 64) — 嵌入层的维度(隐藏大小)。 - hidden_sizes (
list[int]
, 可选, 默认为[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
, 可选, 默认为 0.0) — 随机深度路径的丢弃率。 - embedding_dynamic_padding (
bool
, 可选, 默认为False
) — 是否对嵌入层使用动态填充。 - output_stride (
int
, 可选, 默认为 32) — 模型的输出步幅。 - width_factor (
int
, 可选, 默认为 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
class transformers.BitImageProcessor
< 源 >( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BICUBIC: 3> do_center_crop: bool = True crop_size: typing.Optional[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, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_rgb: bool = True **kwargs )
参数
- do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可在preprocess
方法中由do_resize
覆盖。 - size (
dict[str, int]
可选, 默认为{"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]
可选, 默认为 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
, 可选, 默认为True
) — 是否将图像转换为 RGB。
构建一个 BiT 图像处理器。
预处理
< 源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[int] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_rgb: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )
参数
- images (
ImageInput
) — 要预处理的图像。期望单个或批处理图像的像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
dict[str, int]
, 可选, 默认为self.size
) — 调整大小后的图像尺寸。图像的最短边将调整为 size[“shortest_edge”],最长边将调整为保持输入宽高比。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,使用的重采样过滤器。可以是枚举PILImageResampling
之一。仅当do_resize
设置为True
时有效。 - do_center_crop (
bool
, 可选, 默认为self.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, 可选, 默认为self.crop_size
) — 中心裁剪的尺寸。仅当do_center_crop
设置为True
时有效。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否对图像进行缩放。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则按此缩放因子对图像进行缩放。 - do_normalize (
bool
, 可选, 默认为self.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) 格式。
预处理一张或一批图像。
BitImageProcessorFast
class transformers.BitImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
构造一个快速的 Bit 图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) → <class 'transformers.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
。 - do_resize (
bool
, 可选) — 是否调整图像大小。 - size (
dict[str, int]
, 可选) — 描述模型的最大输入维度。 - default_to_square (
bool
, 可选) — 如果 size 是一个整数,是否默认将图像调整为正方形。 - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — 如果调整图像大小,使用的重采样过滤器。可以是枚举PILImageResampling
之一。仅当do_resize
设置为True
时有效。 - do_center_crop (
bool
, 可选) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, 可选) — 应用center_crop
后输出图像的尺寸。 - do_rescale (
bool
, 可选) — 是否对图像进行缩放。 - rescale_factor (
Union[int, float, NoneType]
) — 如果do_rescale
设置为True
,则按此缩放因子对图像进行缩放。 - do_normalize (
bool
, 可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], NoneType]
) — 用于归一化的图像均值。仅当do_normalize
设置为True
时有效。 - image_std (
Union[float, list[float], NoneType]
) — 用于归一化的图像标准差。仅当do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, 可选) — 是否将图像转换为 RGB。 - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
~image_utils.ChannelDimension
, 可选) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]
) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像为 (num_channels, height, width) 格式。"channels_last"
或ChannelDimension.LAST
:图像为 (height, width, num_channels) 格式。"none"
或ChannelDimension.NONE
:图像为 (height, width) 格式。
- device (
torch.device
, 可选) — 处理图像的设备。如果未设置,则从输入图像推断设备。 - disable_grouping (
bool
, 可选) — 是否禁用按大小对图像进行分组,以单独处理它们而不是批量处理。如果为 None,则如果图像在 CPU 上,将设置为 True,否则为 False。此选择基于经验观察,详细信息请参见:https://github.com/huggingface/transformers/pull/38157
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。
BitModel
class transformers.BitModel
< source >( config )
参数
- config (BitModel) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
裸 Bit 模型,输出原始隐藏状态,顶部没有任何特定头部。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 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 (形状为
(batch_size, num_channels, image_size, image_size)
的torch.Tensor
) — 与输入图像对应的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - 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
时返回) — 形状为(batch_size, num_channels, height, width)
的torch.FloatTensor
元组(一个用于嵌入层的输出(如果模型有嵌入层),加上一个用于每个层的输出)。模型在每个层输出的隐藏状态以及可选的初始嵌入输出。
BitModel
的前向传播方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
BitForImageClassification
class transformers.BitForImageClassification
< source >( config )
参数
- config (BitForImageClassification) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
带有图像分类头部(在池化特征之上是一个线性层)的 BiT 模型,例如用于 ImageNet。
此模型继承自 PreTrainedModel。请查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
此模型也是 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 (形状为
(batch_size, num_channels, image_size, image_size)
的torch.FloatTensor
, 可选) — 与输入图像对应的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - labels (形状为
(batch_size,)
的torch.LongTensor
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
之间。如果config.num_labels > 1
,则计算分类损失(交叉熵)。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是纯元组。
返回
transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 torch.FloatTensor
的元组(如果传入 return_dict=False
或 config.return_dict=False
),包含根据配置(BitConfig)和输入的不同元素。
- 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)
, 可选, 当传入output_hidden_states=True
或config.output_hidden_states=True
时返回) — 形状为(batch_size, num_channels, height, width)
的torch.FloatTensor
元组(一个用于嵌入层的输出(如果模型有嵌入层),加上一个用于每个阶段的输出)。模型的隐藏状态(也称为特征图)在每个阶段的输出处。
BitForImageClassification
的前向传播方法,覆盖了 __call__
特殊方法。
尽管前向传播的配方需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, BitForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> 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])
...