VIT(Vision Transformer)学习(二)- 基础代码学习

理解都加在注释里了

所有代码

一、主体实现代码

#生成一个类
v = ViT(
    image_size = 224,#输入图像大小,宽和高
    patch_size = 16,#每个块的大小,宽和高
    num_classes = 1000,#拉平序列映射的向量长度
    dim = 1024,#维度
    depth = 6,#N,encoder*N
    heads = 16,#多头注意力机制分为多少个头,打到多少个子空间上
    mlp_dim = 2048,#MLP:前馈神经网络(Feed Forward) MLP的维度
    dropout = 0.1,#防止过拟合,https://blog.csdn.net/ningyanggege/article/details/83115811
    emb_dropout = 0.1#embedding层后的dropout
)

img = torch.randn(1, 3, 224, 224)

preds = v(img) # (1, 1000)

二、具体架构代码

class ViT(nn.Module):
    #初始化函数
    def __init__(self, *, image_size, patch_size, num_classes, dim, depth, heads, mlp_dim, pool = 'cls', channels = 3, dim_head = 64, dropout = 0., emb_dropout = 0.):
        super().__init__()
        image_height, image_width = pair(image_size) ## 224*224
        patch_height, patch_width = pair(patch_size)## 16 * 16 

        assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.'

        num_patches = (image_height // patch_height) * (image_width // patch_width)#patch个数 196个patch
        patch_dim = channels * patch_height * patch_width #通道数*高*宽 768
        assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)' #assert A,B 如果A出错则提示B。cls符号做多分类或pooling方式:token输出做池化做多分类 

        self.to_patch_embedding = nn.Sequential(
            Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_height, p2 = patch_width),#Rearrange函数是einops库自带的,作用:改变张量形状
            nn.Linear(patch_dim, dim),#patch_dim到encoder_dim映射 
        )

        self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim))#生成cls和所有对应token对应的位置编码 1,197,1024
        self.cls_token = nn.Parameter(torch.randn(1, 1, dim))#cls token的初始化参数 1,1,1024
        self.dropout = nn.Dropout(emb_dropout)

        self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)#完成输入后,将输入放入Transformer架构

        self.pool = pool
        self.to_latent = nn.Identity() #跳过连接的地方用这个层

        self.mlp_head = nn.Sequential(
            nn.LayerNorm(dim),#对每单个batch进行的归一化
            nn.Linear(dim, num_classes)#映射到类别数
        )

    def forward(self, img):
        x = self.to_patch_embedding(img) ## img 1 3(通道) 224 224  输出形状x : 1 196 1024 
        b, n, _ = x.shape ## 

        cls_tokens = repeat(self.cls_token, '() n d -> b n d', b = b) #1,1,1024
        x = torch.cat((cls_tokens, x), dim=1)#(token emdeding与patch emdeding拼接)1,197,1024
        x += self.pos_embedding[:, :(n + 1)]
        x = self.dropout(x)

        x = self.transformer(x)

        x = x.mean(dim = 1) if self.pool == 'mean' else x[:, 0]#mean:输出做mean池化;cls:取切片第0个元素cls符号

        x = self.to_latent(x)
        return self.mlp_head(x)

三、Transformer实现

class Transformer(nn.Module):
    def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout = 0.):
        super().__init__()
        self.layers = nn.ModuleList([])
        for _ in range(depth):
            #每一个encoder包含两个部分,一个Attention部分是多头注意力机制,一个FeedForward是前馈神经网络部分,preNorm是在之前做Norm
            self.layers.append(nn.ModuleList([
                PreNorm(dim, Attention(dim, heads = heads, dim_head = dim_head, dropout = dropout)),
                PreNorm(dim, FeedForward(dim, mlp_dim, dropout = dropout))
            ]))
    def forward(self, x):
        for attn, ff in self.layers:
            x = attn(x) + x
            x = ff(x) + x
        return x

四、Attention部分理解

class Attention(nn.Module):
    def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):
        super().__init__()
        inner_dim = dim_head *  heads
        project_out = not (heads == 1 and dim_head == dim)

        self.heads = heads
        self.scale = dim_head ** -0.5

        self.attend = nn.Softmax(dim = -1)#将张量的每个元素缩放到(0,1)区间且和为1
        self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)

        self.to_out = nn.Sequential(
            nn.Linear(inner_dim, dim),
            nn.Dropout(dropout)
        ) if project_out else nn.Identity()

    def forward(self, x):
        qkv = self.to_qkv(x).chunk(3, dim = -1)## chunk:对tensor张量分块 x :1(一个图片) 197(196patch+1个cls) 1024(每一个token输入的Input embedding是1024)   qkv最后是一个元组,tuple,长度是3,每个元素形状:1 197 1024
        q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)#把qkv分到多个子空间

        dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale

        attn = self.attend(dots)

        out = torch.matmul(attn, v)
        out = rearrange(out, 'b h n d -> b n (h d)')
        return self.to_out(out)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值