ViT结构

Vision Transformer

图像输入尺寸为 [ N , C , H , W ] [N, C, H, W] [N,C,H,W] C C C通常为3,为了构建为 T r a n s f o r m e r Transformer Transformer需要的输入,将输入图像切分为 p h ∗ p w ∗ C p_h * p_w * C phpwC尺寸的 n n n个小图块,合计切出 h ∗ w h*w hw个小图块。

# reshape and flatten
[N, C, H, W] => [N, h*w, p_h * p_w * C] => [N, h*w, dim] # h = H // p_h, w = W // p_w, input flattened feature to nn.Linear, map into dim dimenstion.
# concat cls_tokens and add positional embedding
cls_token = nn.Parameter(torch.randn(1, 1, dim))
cls_token = repeat(cls_token, '() n d -> b n d', b=b)
pose_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim)
[N, n, dim] => [N, n + 1, dim] => [N, n + 1, dim] # n = h * w, cls_tokens -> positional embedding.

经过 n n n e n c o d i n g    l a y e r s encoding\; layers encodinglayers构建成的 T r a n s f o r m e r Transformer Transformer提取特征后,输入到 M L P    h e a d MLP\; head MLPhead 模块

[N, n + 1, dim] => [N, num_classes]

T r a n s f o r m e r Transformer Transformer e n c o d i n g    l a y e r encoding\; layer encodinglayer模块的结构如下:

encoding layer = MSA + MLP
MSA: Multi-headed Self-Attention
MLP: Multi-Layer Perceptron

ViT结构_第1张图片
注意力模块如下:
ViT结构_第2张图片

多层注意力由多个单一的注意力模块提取信息后,concat到一起。
ViT结构_第3张图片

你可能感兴趣的:(python,深度学习)