Transformers 文档
Big Transfer (BiT)
并获得增强的文档体验
开始使用
Big Transfer (BiT)
概览
BiT 模型在 Big Transfer (BiT): General Visual Representation Learning 中被提出,作者是 Alexander Kolesnikov、Lucas Beyer、Xiaohua Zhai、Joan Puigcerver、Jessica Yung、Sylvain Gelly、Neil Houlsby。BiT 是一个简单的配方,用于扩大 ResNet 类架构(特别是 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 在每个类别 10 个示例的 ILSVRC-2012 上达到了 76.8%,在每个类别 10 个示例的 CIFAR-10 上达到了 97.0%。我们对导致高迁移性能的主要组件进行了详细分析。
使用技巧
- BiT 模型在架构上等同于 ResNetv2,除了:1) 所有批归一化层都被 组归一化 替换,2) 权重标准化 用于卷积层。作者表明,两者的结合对于使用大批量大小进行训练很有用,并且对迁移学习有显著影响。
资源
官方 Hugging Face 和社区 (🌎 表示) 资源列表,可帮助您开始使用 BiT。
- BitForImageClassification 由此示例脚本和笔记本支持。
- 另请参阅:图像分类任务指南
如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核!资源最好展示一些新的内容,而不是重复现有资源。
BitConfig
class 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
, 可选, 默认为 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
, optional, defaults to 0.0) — 随机深度的 drop path 比率。 - embedding_dynamic_padding (
bool
, optional, defaults toFalse
) — 是否对嵌入层使用动态填充。 - output_stride (
int
, optional, defaults to 32) — 模型的输出步幅。 - width_factor (
int
, optional, defaults to 1) — 模型的宽度因子。 - out_features (
List[str]
, optional) — 如果用作 backbone,则输出的特征列表。可以是"stem"
、"stage1"
、"stage2"
等(取决于模型有多少个阶段)。如果未设置且设置了out_indices
,则默认为相应的阶段。如果未设置且out_indices
也未设置,则默认为最后一个阶段。必须与stage_names
属性中定义的顺序相同。 - out_indices (
List[int]
, optional) — 如果用作 backbone,则输出的特征索引列表。可以是 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
< source >( do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BICUBIC: 3> 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
, optional, defaults toTrue
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可以被preprocess
方法中的do_resize
覆盖。 - size (
Dict[str, int]
optional, defaults to{"shortest_edge" -- 224}
): 调整大小后图像的尺寸。图像的最短边将调整为 size[“shortest_edge”],最长边将调整为保持输入宽高比。可以被preprocess
方法中的size
覆盖。 - resample (
PILImageResampling
, optional, defaults toPILImageResampling.BICUBIC
) — 如果调整图像大小,则使用的重采样过滤器。可以被preprocess
方法中的resample
覆盖。 - do_center_crop (
bool
, optional, defaults toTrue
) — 是否将图像中心裁剪为指定的crop_size
。可以被preprocess
方法中的do_center_crop
覆盖。 - crop_size (
Dict[str, int]
optional, defaults to 224) — 应用center_crop
后输出图像的尺寸。可以被preprocess
方法中的crop_size
覆盖。 - do_rescale (
bool
, optional, defaults toTrue
) — 是否通过指定的比例rescale_factor
重新缩放图像。可以被preprocess
方法中的do_rescale
覆盖。 - rescale_factor (
int
orfloat
, optional, defaults to1/255
) — 如果重新缩放图像,则使用的缩放因子。可以被preprocess
方法中的rescale_factor
覆盖。 - do_normalize — 是否对图像进行归一化。可以被
preprocess
方法中的do_normalize
覆盖。 - image_mean (
float
orList[float]
, optional, defaults toOPENAI_CLIP_MEAN
) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,其长度是图像中通道数的长度。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
orList[float]
, optional, defaults toOPENAI_CLIP_MEAN
) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,其长度是图像中通道数的长度。可以被preprocess
方法中的image_std
参数覆盖。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, optional, defaults toTrue
) — 是否将图像转换为 RGB 格式。
构建 BiT 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['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] = <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
, optional, defaults toself.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, optional, defaults toself.size
) — 调整大小后图像的尺寸。图像的最短边将调整为 size[“shortest_edge”],最长边将调整为保持输入宽高比。 - resample (
int
, optional, defaults toself.resample
) — 如果调整图像大小,则使用的重采样过滤器。这可以是枚举PILImageResampling
之一。仅当do_resize
设置为True
时才有效。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, optional, defaults toself.crop_size
) — 中心裁剪的大小。仅当do_center_crop
设置为True
时才有效。 - do_rescale (
bool
, optional, defaults toself.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
, 可选) — 返回张量的类型。可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- 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
class transformers.BitModel
< source >( config )
参数
- config (BitConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
裸 BiT 模型,输出原始特征,顶部没有任何特定的头部。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解所有与常规用法和行为相关的事项。
forward
< 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, height, width)
的torch.FloatTensor
) — 像素值。像素值可以使用 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 (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (形状为
(batch_size, hidden_size)
的torch.FloatTensor
) — 在空间维度上进行池化操作后的最后一层隐藏状态。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组 (每个层的输出一个,如果模型具有嵌入层,则还包括嵌入层的输出),形状为(batch_size, num_channels, height, width)
。模型在每一层输出处的隐藏状态,加上可选的初始嵌入输出。
BitModel
的前向方法,覆盖了 __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
class transformers.BitForImageClassification
< source >( config )
参数
- config (BitConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
BiT 模型,顶部带有一个图像分类头 (池化特征顶部的线性层),例如用于 ImageNet。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解所有与常规用法和行为相关的事项。
forward
< 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, height, width)
的torch.FloatTensor
) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参阅 BitImageProcessor.call()。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是纯元组。 - labels (形状为
(batch_size,)
的torch.LongTensor
, 可选) — 用于计算图像分类/回归损失的标签。索引应在[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 (形状为
(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
时返回) —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