【ViT 论文笔记】AN IMAGE IS WORTH 16X16 WORDS: TRANSFORMERS FOR IMAGE RECOGNITION AT SCALE

“We show that this reliance on CNNs is not necessary and a pure transformer applied directly to sequences of image patches can perform very well on image classification tasks.” ——完全不依赖CNN

参考:Vision Transformer详解_太阳花的小绿豆的博客-CSDN博客_vision transformer

目录

“INTRODUCTION”

“METHOD”

 embedding层结构

Transformer Encoder详解

​编辑

MLP Head详解

“Inductive bias”

“Hybrid Architecture.”

详细结构

VIT代码

 “HEAD TYPE AND CLASS TOKEN”

“POSITIONAL EMBEDDING”

“3.2 FINE-TUNING AND HIGHER RESOLUTION”

“CONCLUSION”

总结

展望


“INTRODUCTION”

直接将transformer应用于视觉,不做过多的修改

  1. split an image into patches,每个patch是16x16,因此224x224的图片变成14x14的序列
  2. 将每一个patch通过一个fc layer,获得一个linear embedding (将patch看成序列中的单词)
  3. 有监督的训练方式

比resnet弱一点,因为缺少归纳偏置

归纳偏置:

  1. locality:假设相邻的区域有相邻的特征
  2. translation equivariance:平移不变性

“METHOD”

 首先输入图片分为很多 patch,论文中为 16。

  1. 将 patch 输入一个 Linear Projection of Flattened Patches 这个 Embedding 层,就会得到一个个向量,通常就称作 tokens。tokens包含position信息以及图像信息。
  2. 此外还需要加上位置的信息(position embedding),对应着 0~9。
  3. 紧接着在一系列 token 的前面加上加上一个新的 token,叫做class token,学习其他token的信息(类别token,有点像输入给 Transformer Decoder 的 START,就是对应着 * 那个位置)。class token也是其他所有token做全局平均池化,效果一样。
  4. 然后输入到 Transformer Encoder 中,对应着右边的图,将 block 重复堆叠 L 次。Transformer Encoder 有多少个输入就有多少个输出。

 embedding层结构

 对于图像数据而言,其数据格式为[H, W, C]是三维矩阵明显不是Transformer想要的。所以需要先通过一个Embedding层来对数据做个变换。

  1. 如下图所示,首先将一张图片按给定大小分成一堆Patches。以ViT-B/16为例,将输入图片(224x224)按照16x16大小的Patch进行划分,划分后会得到(224/16)^2=196个Patches。
  2. 接着通过线性映射将每个Patch映射到一维向量中,以ViT-B/16为例,每个Patche数据shape为[16, 16, 3]通过映射得到一个长度为768的向量(后面都直接称为token)。[16, 16, 3] -> [768]

在代码实现中,直接通过一个卷积层来实现。 以ViT-B/16为例,直接使用一个卷积核大小为16x16,步距为16,卷积核个数为768的卷积来实现。通过卷积[224, 224, 3] -> [14, 14, 768],然后把H以及W两个维度展平即可[14, 14, 768] -> [196, 768],此时正好变成了一个二维矩阵,正是Transformer想要的。

   3. 在输入Transformer Encoder之前注意需要加上[class]token以及Position Embedding。Cat([1, 768], [196, 768]) -> [197, 768]。Position Embedding采用的是一个可训练的参数(1D Pos. Emb.),是直接叠加在tokens上的(add),所以shape一样。

Transformer Encoder详解

Transformer Encoder其实就是重复堆叠Encoder Block L次,下图是我自己绘制的Encoder Block,主要由以下几部分组成:

  1. Layer Norm,这种Normalization方法主要是针对NLP领域提出的,这里是对每个token进行Norm处理。
  2. Multi-Head Attention
  3. Dropout/DropPath,在原论文的代码中是直接使用的Dropout层,在但rwightman实现的代码中使用的是DropPath(stochastic depth),可能后者会更好一点。
  4. MLP Block,就是全连接+GELU激活函数+Dropout组成也非常简单,需要注意的是第一个全连接层会把输入节点个数翻4倍[197, 768] -> [197, 3072],第二个全连接层会还原回原节点个数[197, 3072] -> [197, 768]

MLP Head详解

这里我们只是需要分类的信息,所以我们只需要提取出[class]token生成的对应结果就行,即[197, 768]中抽取出[class]token对应的[1, 768]。接着我们通过MLP Head得到我们最终的分类结果。MLP Head原论文中说在训练ImageNet21K时是由Linear+tanh激活函数+Linear组成。但是迁移到ImageNet1K上或者你自己的数据上时,只用一个Linear即可。

“Inductive bias”

“In ViT, only MLP layers are local and translationally equivariant, while the self-attention layers are global.” [1]

“Hybrid Architecture.”

“In this hybrid model, the patch embedding projection E (Eq. 1) is applied to patches extracted from a CNN feature map. As a special case, the patches can have spatial size 1x1, which means that the input sequence is obtained by simply flattening the spatial dimensions of the feature map and projecting to the Transformer dimension. The classification input embedding and position embeddings are added as described above.” [2]

224X224->CNN->14X14->transformer

详细结构

 

VIT代码

 “HEAD TYPE AND CLASS TOKEN”

“Comparison of class-token and global average pooling classifiers. Both work similarly well, but require different learning-rates.
----
类标记和全局平均池化分类器的比较。两者工作都很好,但需要不同的学习率。” [3]

“POSITIONAL EMBEDDING”

“1-dimensional positional embedding: Considering the inputs as a sequence of patches in the raster order (default across all other experiments in this paper).” [4]

“3.2 FINE-TUNING AND HIGHER RESOLUTION”

“The Vision Transformer can handle arbitrary sequence lengths (up to memory constraints), however, the pre-trained position embeddings may no longer be meaningful.” [5] Vision Transformer可以处理任意序列长度的(直至内存约束),但是,预训练的位置嵌入可能不再有意义。

“We therefore perform 2D interpolation of the pre-trained position embeddings, according to their location in the original image.” [6] 因此,我们根据它们在原始图像中的位置,对预训练的位置嵌入进行2D插值。

“CONCLUSION”

总结

“We have explored the direct application of Transformers to image recognition.” [7] 我们探索了Transformers在图像识别中的直接应用。

“we interpret an image as a sequence of patches and process it by a standard Transformer encoder as used in NLP.” [8] 我们将一幅图像解释为一系列补丁,并使用NLP中使用的标准Transformer编码器对其进行处理。

展望

1. “One is to apply ViT to other computer vision tasks, such as detection and segmentation.” [9] 一种是将ViT应用于其他计算机视觉任务,如检测和分割。

2. “Another challenge is to continue exploring selfsupervised pre-training methods.” [10] 另一个挑战是继续探索自我监督的预训练方法。

论文An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale》由谷歌团队发表于ICLR 2021,主要介绍了Vision Transformer (ViT) 的设计与性能。以下是关于该论文的一些重要引用: ### 关键概念概述 - **图像分割为Patch序列**:为了使Transformer能够处理图像数据,论文提出将图像划分为固定大小的块(patches)。这些块被线性映射为向量,并附加位置编码以保留空间信息[^2]。 - **减少归纳偏差**:相比于传统卷积神经网络(CNN),ViT通过直接处理图像patch序列的方式显著减少了图像特定的归纳偏差。这意味着模型更加灵活,能够在不同类型的图像任务中表现出更强的泛化能力[^3]。 - **预训练的重要性**:研究发现,在大规模数据集上进行预训练对于提升ViT的表现至关重要。即使是在较小的数据集上微调时,经过充分预训练的ViT也能达到甚至超过现有最佳卷积网络的效果[^4]。 - **计算效率高**:尽管Transformer架构通常被认为计算成本较高,但实验表明,当应用于适当规模的任务时,ViT所需的计算资源实际上低于许多先进的CNN模型。 ### 技术细节说明 下面是一段简单的Python代码实现如何将一张图片转换成适合输入给ViT模型的形式: ```python import numpy as np def split_image_into_patches(image, patch_size=16): height, width, channels = image.shape patches = [] for y in range(0, height, patch_size): for x in range(0, width, patch_size): patch = image[y:y+patch_size, x:x+patch_size] if patch.shape[:2] == (patch_size, patch_size): # Ensure full-sized patches only. patches.append(patch.flatten()) return np.array(patches) # Example usage with a dummy RGB image of size 224x224 pixels and 3 color channels. dummy_image = np.random.rand(224, 224, 3) image_patches = split_image_into_patches(dummy_image) print(f"Number of Patches Generated: {len(image_patches)}") ``` 此函数会把任意尺寸的RGB图像切割成一系列形状相同的补丁,准备作为后续嵌入层的输入源材料之一。 --- ####
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值