Transformers documentation
Swin Transformer
该模型于 2021-03-25 在 HF papers 上发表,并于 2022-01-21 贡献给 Hugging Face Transformers。
Swin Transformer
Swin Transformer 是一种层级式视觉 Transformer。图像以块(patch)为单位进行处理,并采用窗口自注意力机制来捕获局部信息。这些窗口在图像上进行移位,以实现跨窗口的连接,从而更高效地捕获全局信息。这种结合移位窗口的层级式方法使 Swin Transformer 能够以不同的尺度有效处理图像,并实现相对于图像大小的线性计算复杂度,使其成为图像分类和物体检测等多种视觉任务的通用骨干网络。
您可以在 Microsoft 组织下找到所有官方的 Swin Transformer 检查点。
点击右侧边栏中的 Swin Transformer 模型,以查看更多将 Swin Transformer 应用于不同图像任务的示例。
下面的示例演示了如何使用 Pipeline 或 AutoModel 类对图像进行分类。
from transformers import pipeline
pipeline = pipeline(
task="image-classification",
model="microsoft/swin-tiny-patch4-window7-224",
device=0
)
pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")import requests
import torch
from PIL import Image
from transformers import AutoImageProcessor, AutoModelForImageClassification
image_processor = AutoImageProcessor.from_pretrained(
"microsoft/swin-tiny-patch4-window7-224",
use_fast=True,
)
model = AutoModelForImageClassification.from_pretrained(
"microsoft/swin-tiny-patch4-window7-224",
device_map="auto"
)
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(image, return_tensors="pt").to(model.device)
with torch.no_grad():
logits = model(**inputs).logits
predicted_class_id = logits.argmax(dim=-1).item()
class_labels = model.config.id2label
predicted_class_label = class_labels[predicted_class_id]
print(f"The predicted class label is: {predicted_class_label}")备注
- Swin 可以对任何高度和宽度均可被
32整除的输入进行填充。 - Swin 可以作为backbone使用。当
output_hidden_states = True时,它会同时输出hidden_states和reshaped_hidden_states。其中,reshaped_hidden_states的形状为(batch, num_channels, height, width),而不是(batch_size, sequence_length, num_channels)。
SwinConfig
class transformers.SwinConfig
< source >( 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 = Noneimage_size: int | list[int] | tuple[int, int] = 224patch_size: int | list[int] | tuple[int, int] = 4num_channels: int = 3embed_dim: int = 96depths: list[int] | tuple[int, ...] = (2, 2, 6, 2)num_heads: list[int] | tuple[int, ...] = (3, 6, 12, 24)window_size: int = 7mlp_ratio: float | int = 4.0qkv_bias: bool = Truehidden_dropout_prob: float | int = 0.0attention_probs_dropout_prob: float | int = 0.0drop_path_rate: float | int = 0.1hidden_act: str = 'gelu'use_absolute_embeddings: bool = Falseinitializer_range: float = 0.02layer_norm_eps: float = 1e-05encoder_stride: int = 32_out_features: list[str] | None = None_out_indices: list[int] | None = None )
参数
- image_size (
Union[int, list[int], tuple[int, int]],可选,默认为224) — 每张图片的尺寸(分辨率)。 - patch_size (
Union[int, list[int], tuple[int, int]],可选,默认为4) — 每个 patch 的大小(分辨率)。 - num_channels (
int,可选,默认为3) — 输入通道的数量。 - embed_dim (
int,可选,默认为96) — 嵌入和隐藏状态的维度。 - depths (
list(int),可选,默认为[2, 2, 6, 2]) — Transformer 编码器中每一层的深度。 - num_heads (
list(int),可选,默认为[3, 6, 12, 24]) — Transformer 编码器每一层中的注意力头数量。 - window_size (
int,可选,默认为 7) — 窗口大小。 - mlp_ratio (
Union[float, int],可选,默认为4.0) — MLP 隐藏层维度与嵌入维度的比值。 - qkv_bias (
bool,可选,默认为True) — 是否向查询、键和值添加偏置。 - hidden_dropout_prob (
Union[float, int],可选,默认为0.0) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
Union[float, int],可选,默认为0.0) — 注意力概率的 dropout 比率。 - drop_path_rate (
Union[float, int],可选,默认为0.1) — 用于 patch 融合的 drop path 比率。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - use_absolute_embeddings (
bool,可选,默认为False) — 是否使用绝对位置嵌入。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float,可选,默认为1e-05) — 层归一化层所使用的 epsilon 值。 - encoder_stride (
int,可选,默认为 32) — 在掩码图像建模的解码器头部中,用于提升空间分辨率的倍数因子。
这是用于存储 SwinModel 配置的类。它根据指定的参数实例化 Swin 模型,并定义模型架构。使用默认值实例化配置,将得到与 microsoft/swin-tiny-patch4-window7-224 类似的配置。
配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PreTrainedConfig 的文档。
示例:
>>> from transformers import SwinConfig, SwinModel
>>> # Initializing a Swin microsoft/swin-tiny-patch4-window7-224 style configuration
>>> configuration = SwinConfig()
>>> # Initializing a model (with random weights) from the microsoft/swin-tiny-patch4-window7-224 style configuration
>>> model = SwinModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.configSwinModel
类 transformers.SwinModel
< source >( config: SwinConfigadd_pooling_layer = Trueuse_mask_token = False )
参数
- config (SwinConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
- add_pooling_layer (
bool,可选,默认为True) — 是否应用池化层。 - use_mask_token (
bool,可选,默认为False) — 是否在嵌入层中创建并应用掩码标记。
输出原始隐藏状态且顶部未添加任何特定头部的裸 Swin 模型。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonebool_masked_pos: typing.Optional[torch.BoolTensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SwinModelOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 ViTImageProcessor 获取像素值。有关详细信息,请参阅 ViTImageProcessor.call()(processor_class使用 ViTImageProcessor 处理图像)。 - bool_masked_pos(形状为
(batch_size, num_patches)的torch.BoolTensor,可选)— 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。 - interpolate_pos_encoding (
bool,可选,默认为False) — 是否对预训练的位置编码进行插值。
返回值
SwinModelOutput 或 tuple(torch.Tensor)
SwinModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(SwinConfig)和输入。
SwinModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选)— 模型最后一层输出的隐藏状态序列。pooler_output(形状为
(batch_size, hidden_size)的torch.Tensor,可选,在传入add_pooling_layer=True时返回) — 最后一层隐藏状态的均值池化。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple[torch.Tensor, ...],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
reshaped_hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层输出以及每个阶段的输出各一个),形状为(batch_size, hidden_size, height, width)。模型在每一层输出处的隐藏状态,以及重塑为包含空间维度的初始嵌入输出。
SwinForMaskedImageModeling
class transformers.SwinForMaskedImageModeling
< source >( config: SwinConfig )
参数
- config (SwinConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
在 SimMIM 中提出的,在 Swin 模型顶部添加解码器以实现掩码图像建模。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonebool_masked_pos: typing.Optional[torch.BoolTensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SwinMaskedImageModelingOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 ViTImageProcessor 获取像素值。有关详细信息,请参阅 ViTImageProcessor.call()(processor_class使用 ViTImageProcessor 处理图像)。 - bool_masked_pos(形状为
(batch_size, num_patches)的torch.BoolTensor)— 布尔掩码位置。指示哪些 patch 被掩码(1),哪些未被掩码(0)。 - interpolate_pos_encoding (
bool,可选,默认为False) — 是否对预训练的位置编码进行插值。
返回值
SwinMaskedImageModelingOutput 或 tuple(torch.Tensor)
SwinMaskedImageModelingOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(SwinConfig)和输入。
SwinForMaskedImageModeling 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供bool_masked_pos时返回) — 掩码图像建模 (MLM) 损失。重建(形状为
(batch_size, num_channels, height, width)的torch.Tensor)— 重建的像素值。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple[torch.Tensor, ...],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
reshaped_hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层输出以及每个阶段的输出各一个),形状为(batch_size, hidden_size, height, width)。模型在每一层输出处的隐藏状态,以及重塑为包含空间维度的初始嵌入输出。
示例:
>>> from transformers import AutoImageProcessor, SwinForMaskedImageModeling
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
... image = Image.open(BytesIO(response.read()))
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swin-base-simmim-window6-192")
>>> model = SwinForMaskedImageModeling.from_pretrained("microsoft/swin-base-simmim-window6-192")
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
>>> # create random boolean mask of shape (batch_size, num_patches)
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
>>> list(reconstructed_pixel_values.shape)
[1, 3, 192, 192]SwinForImageClassification
class transformers.SwinForImageClassification
< source >( config: SwinConfig )
参数
- config (SwinConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Swin 模型,顶部带有图像分类头(在 [CLS] token 的最终隐藏状态之上添加一个线性层),例如用于 ImageNet。
请注意,通过在模型的前向传播中将
interpolate_pos_encoding设置为True,可以对 Swin 进行微调,使其处理比训练时更高分辨率的图像。这会将预训练的位置嵌入插值到更高分辨率。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.LongTensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → SwinImageClassifierOutput or tuple(torch.Tensor)
参数
- pixel_values (
torch.Tensor,形状为(batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 ViTImageProcessor 获取像素值。有关详细信息,请参阅 ViTImageProcessor.call()(processor_class使用 ViTImageProcessor 处理图像)。 - labels(形状为
(batch_size,)的torch.LongTensor,可选)— 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。如果config.num_labels == 1,则计算回归损失(均方损失);如果config.num_labels > 1,则计算分类损失(交叉熵)。 - interpolate_pos_encoding (
bool,可选,默认为False) — 是否对预训练的位置编码进行插值。
返回值
SwinImageClassifierOutput 或 tuple(torch.Tensor)
SwinImageClassifierOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(SwinConfig)和输入。
SwinForImageClassification 的 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, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple[torch.Tensor, ...],可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)。注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。
reshaped_hidden_states (
tuple(torch.Tensor),可选,在传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(包含嵌入层输出以及每个阶段的输出各一个),形状为(batch_size, hidden_size, height, width)。模型在每一层输出处的隐藏状态,以及重塑为包含空间维度的初始嵌入输出。
示例:
>>> from transformers import AutoImageProcessor, SwinForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224")
>>> model = SwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224")
>>> 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])
...