聊一聊计算机视觉中常用的注意力机制 附Pytorch代码实现

CNN中的注意力机制综合指南:从理论到Pytorch代码实现 卷积神经网络(CNN)作为深度学习中的一种经典模型,广泛应用于图像处理和计算机视觉任务。然而,传统的CNN在捕捉图像中的重要区域和特征时存在一定的局限性。为了克服这些局限,注意力机制被引入到CNN中,以动态地调整对不同区域和通道的关注程度,从而提升模型的性能和表达能力。在本节中,我们将详细定义CNN中的注意力机制,并阐述其在卷积网络中的作用和实现方式。在卷积神经网络(CNN)中引入注意力机制已经成为提升模型性能的关键技术之一。 阅读详情
AI摘要

本文详细介绍计算机视觉领域中常用的注意力机制,包括SeNet、CBAM、ECA-Net等,并提供了相应的Pytorch代码实现及实验结果。

聊一聊计算机视觉中常用的注意力机制以及Pytorch代码实现

注意力机制(Attention)是深度学习中常用的tricks,可以在模型原有的基础上直接插入,进一步增强你模型的性能。注意力机制起初是作为自然语言处理中的工作Attention Is All You Need被大家所熟知,从而也引发了一系列的XX is All You Need的论文命题,SENET-Squeeze-and-Excitation Networks是注意力机制在计算机视觉中应用的早期工作之一,并获得了2017年imagenet, 同时也是最后一届Imagenet比赛的冠军,后面就又出现了各种各样的注意力机制,应用在计算机视觉的任务中,今天我们就来一起聊一聊计算机视觉中常用的注意力机制以及他们对应的Pytorch代码实现,另外我还使用这些注意力机制做了一些目标检测的实验,实验效果我也一并放在博客中,大家可以一起对自己感兴趣的部分讨论讨论。

新出的手把手教程,感兴趣的兄弟们快去自己动手试试看!

手把手教你使用YOLOV5训练自己的目标检测模型-口罩检测-视频教程_dejahu的博客-优快云博客

这里是我数据集的基本情况,这里我使用的是交通标志检测的数据集

CocoDataset Train dataset with number of images 2226, and instance counts: 
+------------+-------+-----------+-------+-----------+-------+-----------------------------+-------+---------------------+-------+
| category   | count | category  | count | category  | count | category                    | count | category            | count |
+------------+-------+-----------+-------+-----------+-------+-----------------------------+-------+---------------------+-------+
| 0 [red_tl] | 1465  | 1 [arr_s] | 1133  | 2 [arr_l] | 638   | 3 [no_driving_mark_allsort] | 622   | 4 [no_parking_mark] | 1142  |
+------------+-------+-----------+-------+-----------+-------+-----------------------------+-------+---------------------+-------+

baseline选择的是fasterrcnn,实验的结果如下:

 Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.341
 Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.502
 Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.400
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.115
 Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.473
 Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.655
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.417
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.417
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.417
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.156
 Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.570
 Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.726

如果大家遇到论文下载比较慢

推荐使用中科院的 arxiv 镜像: http://xxx.itp.ac.cn, 国内网络能流畅访问
简单直接的方法是, 把要访问 arxiv 链接中的域名从 https://arxiv.org 换成 http://xxx.itp.ac.cn , 比如:

从 https://arxiv.org/abs/1901.07249 改为 http://xxx.itp.ac.cn/abs/1901.07249

1. SeNet: Squeeze-and-Excitation Attention

论文地址:https://arxiv.org/abs/1709.01507

  • 网络结构

    对通道做注意力机制,通过全连接层对每个通道进行加权。

    image-20211210153628963

    image-20211210153655899

  • Pytorch代码

    import numpy as np
    import torch
    from torch import nn
    from torch.nn import init
    
    
    class SEAttention(nn.Module):
    
        def __init__(self, channel=512, reduction=16):
            super().__init__()
            self.avg_pool = nn.AdaptiveAvgPool2d(1)
            self.fc = nn.Sequential(
                nn.Linear(channel, channel // reduction, bias=False),
                nn.ReLU(inplace=True),
                nn.Linear(channel // reduction, channel, bias=False),
                nn.Sigmoid()
            )
    
        def init_weights(self):
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    init.kaiming_normal_(m.weight, mode='fan_out')
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
                elif isinstance(m, nn.BatchNorm2d):
                    init.constant_(m.weight, 1)
                    init.constant_(m.bias, 0)
                elif isinstance(m, nn.Linear):
                    init.normal_(m.weight, std=0.001)
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
    
        def forward(self, x):
            b, c, _, _ = x.size()
            y = self.avg_pool(x).view(b, c)
            y = self.fc(y).view(b, c, 1, 1)
            return x * y.expand_as(x)
    
    
    if __name__ == '__main__':
        input = torch.randn(50, 512, 7, 7)
        se = SEAttention(channel=512, reduction=8)
        output = se(input)
        print(output.shape)
    
    
  • 实验结果

     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.338
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.511
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.375
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.126
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.458
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.696
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.411
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.411
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.411
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.163
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.551
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.758
    

2. (有用)CBAM: Convolutional Block Attention Module

论文地址:CBAM: Convolutional Block Attention Module

  • 网络结构

    对通道方向上做注意力机制之后再对空间方向上做注意力机制

    image-20211210154323132

  • Pytorch代码

    import numpy as np
    import torch
    from torch import nn
    from torch.nn import init
    
    
    class ChannelAttention(nn.Module):
        def __init__(self, channel, reduction=16):
            super().__init__()
            self.maxpool = nn.AdaptiveMaxPool2d(1)
            self.avgpool = nn.AdaptiveAvgPool2d(1)
            self.se = nn.Sequential(
                nn.Conv2d(channel, channel // reduction, 1, bias=False),
                nn.ReLU(),
                nn.Conv2d(channel // reduction, channel, 1, bias=False)
            )
            self.sigmoid = nn.Sigmoid()
    
        def forward(self, x):
            max_result = self.maxpool(x)
            avg_result = self.avgpool(x)
            max_out = self.se(max_result)
            avg_out = self.se(avg_result)
            output = self.sigmoid(max_out + avg_out)
            return output
    
    
    class SpatialAttention(nn.Module):
        def __init__(self, kernel_size=7):
            super().__init__()
            self.conv = nn.Conv2d(2, 1, kernel_size=kernel_size, padding=kernel_size // 2)
            self.sigmoid = nn.Sigmoid()
    
        def forward(self, x):
            max_result, _ = torch.max(x, dim=1, keepdim=True)
            avg_result = torch.mean(x, dim=1, keepdim=True)
            result = torch.cat([max_result, avg_result], 1)
            output = self.conv(result)
            output = self.sigmoid(output)
            return output
    
    
    class CBAMBlock(nn.Module):
    
        def __init__(self, channel=512, reduction=16, kernel_size=49):
            super().__init__()
            self.ca = ChannelAttention(channel=channel, reduction=reduction)
            self.sa = SpatialAttention(kernel_size=kernel_size)
    
        def init_weights(self):
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    init.kaiming_normal_(m.weight, mode='fan_out')
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
                elif isinstance(m, nn.BatchNorm2d):
                    init.constant_(m.weight, 1)
                    init.constant_(m.bias, 0)
                elif isinstance(m, nn.Linear):
                    init.normal_(m.weight, std=0.001)
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
    
        def forward(self, x):
            b, c, _, _ = x.size()
            residual = x
            out = x * self.ca(x)
            out = out * self.sa(out)
            return out + residual
    
    
    if __name__ == '__main__':
        input = torch.randn(50, 512, 7, 7)
        kernel_size = input.shape[2]
        cbam = CBAMBlock(channel=512, reduction=16, kernel_size=kernel_size)
        output = cbam(input)
        print(output.shape)
    
    
  • 实验结果

     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.364
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.544
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.425
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.137
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.499
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.674
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.439
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.439
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.439
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.185
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.590
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.755
    

3. BAM: Bottleneck Attention Module

论文地址:https://arxiv.org/pdf/1807.06514.pdf

  • 网络结构

    image-20211217103020590

  • Pytorch代码

    import numpy as np
    import torch
    from torch import nn
    from torch.nn import init
    
    
    class Flatten(nn.Module):
        def forward(self, x):
            return x.view(x.shape[0], -1)
    
    
    class ChannelAttention(nn.Module):
        def __init__(self, channel, reduction=16, num_layers=3):
            super().__init__()
            self.avgpool = nn.AdaptiveAvgPool2d(1)
            gate_channels = [channel]
            gate_channels += [channel // reduction] * num_layers
            gate_channels += [channel]
    
            self.ca = nn.Sequential()
            self.ca.add_module('flatten', Flatten())
            for i in range(len(gate_channels) - 2):
                self.ca.add_module('fc%d' % i, nn.Linear(gate_channels[i], gate_channels[i + 1]))
                self.ca.add_module('bn%d' % i, nn.BatchNorm1d(gate_channels[i + 1]))
                self.ca.add_module('relu%d' % i, nn.ReLU())
            self.ca.add_module('last_fc', nn.Linear(gate_channels[-2], gate_channels[-1]))
    
        def forward(self, x):
            res = self.avgpool(x)
            res = self.ca(res)
            res = res.unsqueeze(-1).unsqueeze(-1).expand_as(x)
            return res
    
    
    class SpatialAttention(nn.Module):
        def __init__(self, channel, reduction=16, num_layers=3, dia_val=2):
            super().__init__()
            self.sa = nn.Sequential()
            self.sa.add_module('conv_reduce1',
                               nn.Conv2d(kernel_size=1, in_channels=channel, out_channels=channel // reduction))
            self.sa.add_module('bn_reduce1', nn.BatchNorm2d(channel // reduction))
            self.sa.add_module('relu_reduce1', nn.ReLU())
            for i in range(num_layers):
                self.sa.add_module('conv_%d' % i, nn.Conv2d(kernel_size=3, in_channels=channel // reduction,
                                                            out_channels=channel // reduction, padding=1, dilation=dia_val))
                self.sa.add_module('bn_%d' % i, nn.BatchNorm2d(channel // reduction))
                self.sa.add_module('relu_%d' % i, nn.ReLU())
            self.sa.add_module('last_conv', nn.Conv2d(channel // reduction, 1, kernel_size=1))
    
        def forward(self, x):
            res = self.sa(x)
            res = res.expand_as(x)
            return res
    
    
    class BAMBlock(nn.Module):
    
        def __init__(self, channel=512, reduction=16, dia_val=2):
            super().__init__()
            self.ca = ChannelAttention(channel=channel, reduction=reduction)
            self.sa = SpatialAttention(channel=channel, reduction=reduction, dia_val=dia_val)
            self.sigmoid = nn.Sigmoid()
    
        def init_weights(self):
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    init.kaiming_normal_(m.weight, mode='fan_out')
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
                elif isinstance(m, nn.BatchNorm2d):
                    init.constant_(m.weight, 1)
                    init.constant_(m.bias, 0)
                elif isinstance(m, nn.Linear):
                    init.normal_(m.weight, std=0.001)
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
    
        def forward(self, x):
            b, c, _, _ = x.size()
            sa_out = self.sa(x)
            ca_out = self.ca(x)
            weight = self.sigmoid(sa_out + ca_out)
            out = (1 + weight) * x
            return out
    
    
    if __name__ == '__main__':
        input = torch.randn(50, 512, 7, 7)
        bam = BAMBlock(channel=512, reduction=16, dia_val=2)
        output = bam(input)
        print(output.shape)
    
  • 实验结果

    无
    

4. (有用)ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks

论文地址:https://arxiv.org/pdf/1910.03151.pdf

  • 网络结构

    image-20211217105517345

  • Pytorch代码

    import numpy as np
    import torch
    from torch import nn
    from torch.nn import init
    from collections import OrderedDict
    
    
    class ECAAttention(nn.Module):
    
        def __init__(self, kernel_size=3):
            super().__init__()
            self.gap = nn.AdaptiveAvgPool2d(1)
            self.conv = nn.Conv1d(1, 1, kernel_size=kernel_size, padding=(kernel_size - 1) // 2)
            self.sigmoid = nn.Sigmoid()
    
        def init_weights(self):
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    init.kaiming_normal_(m.weight, mode='fan_out')
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
                elif isinstance(m, nn.BatchNorm2d):
                    init.constant_(m.weight, 1)
                    init.constant_(m.bias, 0)
                elif isinstance(m, nn.Linear):
                    init.normal_(m.weight, std=0.001)
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
    
        def forward(self, x):
            y = self.gap(x)  # bs,c,1,1
            y = y.squeeze(-1).permute(0, 2, 1)  # bs,1,c
            y = self.conv(y)  # bs,1,c
            y = self.sigmoid(y)  # bs,1,c
            y = y.permute(0, 2, 1).unsqueeze(-1)  # bs,c,1,1
            return x * y.expand_as(x)
    
    
    if __name__ == '__main__':
        input = torch.randn(50, 512, 7, 7)
        eca = ECAAttention(kernel_size=3)
        output = eca(input)
        print(output.shape)
    
  • 实验结果

    2021-12-17 12:18:08,911 - mmdet - INFO - 
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.360
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.545
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.414
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.141
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.489
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.676
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.432
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.432
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.432
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.184
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.576
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.748
    

5. SA-NET: SHUFFLE ATTENTION FOR DEEP CONVOLUTIONAL NEURAL NETWORKS

论文地址:https://arxiv.org/pdf/2102.00240.pdf

  • 网络结构

    image-20211217105138064

  • Pytorch代码

    import numpy as np
    import torch
    from torch import nn
    from torch.nn import init
    from torch.nn.parameter import Parameter
    
    
    class ShuffleAttention(nn.Module):
    
        def __init__(self, channel=512, reduction=16, G=8):
            super().__init__()
            self.G = G
            self.channel = channel
            self.avg_pool = nn.AdaptiveAvgPool2d(1)
            self.gn = nn.GroupNorm(channel // (2 * G), channel // (2 * G))
            self.cweight = Parameter(torch.zeros(1, channel // (2 * G), 1, 1))
            self.cbias = Parameter(torch.ones(1, channel // (2 * G), 1, 1))
            self.sweight = Parameter(torch.zeros(1, channel // (2 * G), 1, 1))
            self.sbias = Parameter(torch.ones(1, channel // (2 * G), 1, 1))
            self.sigmoid = nn.Sigmoid()
    
        def init_weights(self):
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    init.kaiming_normal_(m.weight, mode='fan_out')
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
                elif isinstance(m, nn.BatchNorm2d):
                    init.constant_(m.weight, 1)
                    init.constant_(m.bias, 0)
                elif isinstance(m, nn.Linear):
                    init.normal_(m.weight, std=0.001)
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
    
        @staticmethod
        def channel_shuffle(x, groups):
            b, c, h, w = x.shape
            x = x.reshape(b, groups, -1, h, w)
            x = x.permute(0, 2, 1, 3, 4)
    
            # flatten
            x = x.reshape(b, -1, h, w)
    
            return x
    
        def forward(self, x):
            b, c, h, w = x.size()
            # group into subfeatures
            x = x.view(b * self.G, -1, h, w)  # bs*G,c//G,h,w
    
            # channel_split
            x_0, x_1 = x.chunk(2, dim=1)  # bs*G,c//(2*G),h,w
    
            # channel attention
            x_channel = self.avg_pool(x_0)  # bs*G,c//(2*G),1,1
            x_channel = self.cweight * x_channel + self.cbias  # bs*G,c//(2*G),1,1
            x_channel = x_0 * self.sigmoid(x_channel)
    
            # spatial attention
            x_spatial = self.gn(x_1)  # bs*G,c//(2*G),h,w
            x_spatial = self.sweight * x_spatial + self.sbias  # bs*G,c//(2*G),h,w
            x_spatial = x_1 * self.sigmoid(x_spatial)  # bs*G,c//(2*G),h,w
    
            # concatenate along channel axis
            out = torch.cat([x_channel, x_spatial], dim=1)  # bs*G,c//G,h,w
            out = out.contiguous().view(b, -1, h, w)
    
            # channel shuffle
            out = self.channel_shuffle(out, 2)
            return out
    
    
    if __name__ == '__main__':
        input = torch.randn(50, 512, 7, 7)
        se = ShuffleAttention(channel=512, G=8)
        output = se(input)
        print(output.shape)
    
    
  • 实验结果

     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.350
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.523
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.401
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.123
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.479
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.662
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.424
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.424
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.424
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.160
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.576
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.733
    

6. Polarized Self-Attention: Towards High-quality Pixel-wise Regression

论文地址:https://arxiv.org/abs/2107.00782

  • 网络结构

    image-20211217105853958

  • Pytorch代码

    import numpy as np
    import torch
    from torch import nn
    from torch.nn import init
    
    
    class ParallelPolarizedSelfAttention(nn.Module):
    
        def __init__(self, channel=512):
            super().__init__()
            self.ch_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
            self.ch_wq = nn.Conv2d(channel, 1, kernel_size=(1, 1))
            self.softmax_channel = nn.Softmax(1)
            self.softmax_spatial = nn.Softmax(-1)
            self.ch_wz = nn.Conv2d(channel // 2, channel, kernel_size=(1, 1))
            self.ln = nn.LayerNorm(channel)
            self.sigmoid = nn.Sigmoid()
            self.sp_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
            self.sp_wq = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
            self.agp = nn.AdaptiveAvgPool2d((1, 1))
    
        def forward(self, x):
            b, c, h, w = x.size()
    
            # Channel-only Self-Attention
            channel_wv = self.ch_wv(x)  # bs,c//2,h,w
            channel_wq = self.ch_wq(x)  # bs,1,h,w
            channel_wv = channel_wv.reshape(b, c // 2, -1)  # bs,c//2,h*w
            channel_wq = channel_wq.reshape(b, -1, 1)  # bs,h*w,1
            channel_wq = self.softmax_channel(channel_wq)
            channel_wz = torch.matmul(channel_wv, channel_wq).unsqueeze(-1)  # bs,c//2,1,1
            channel_weight = self.sigmoid(self.ln(self.ch_wz(channel_wz).reshape(b, c, 1).permute(0, 2, 1))).permute(0, 2,
                                                                                                                     1).reshape(
                b, c, 1, 1)  # bs,c,1,1
            channel_out = channel_weight * x
    
            # Spatial-only Self-Attention
            spatial_wv = self.sp_wv(x)  # bs,c//2,h,w
            spatial_wq = self.sp_wq(x)  # bs,c//2,h,w
            spatial_wq = self.agp(spatial_wq)  # bs,c//2,1,1
            spatial_wv = spatial_wv.reshape(b, c // 2, -1)  # bs,c//2,h*w
            spatial_wq = spatial_wq.permute(0, 2, 3, 1).reshape(b, 1, c // 2)  # bs,1,c//2
            spatial_wq = self.softmax_spatial(spatial_wq)
            spatial_wz = torch.matmul(spatial_wq, spatial_wv)  # bs,1,h*w
            spatial_weight = self.sigmoid(spatial_wz.reshape(b, 1, h, w))  # bs,1,h,w
            spatial_out = spatial_weight * x
            out = spatial_out + channel_out
            return out
    
    
    class SequentialPolarizedSelfAttention(nn.Module):
    
        def __init__(self, channel=512):
            super().__init__()
            self.ch_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
            self.ch_wq = nn.Conv2d(channel, 1, kernel_size=(1, 1))
            self.softmax_channel = nn.Softmax(1)
            self.softmax_spatial = nn.Softmax(-1)
            self.ch_wz = nn.Conv2d(channel // 2, channel, kernel_size=(1, 1))
            self.ln = nn.LayerNorm(channel)
            self.sigmoid = nn.Sigmoid()
            self.sp_wv = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
            self.sp_wq = nn.Conv2d(channel, channel // 2, kernel_size=(1, 1))
            self.agp = nn.AdaptiveAvgPool2d((1, 1))
    
        def forward(self, x):
            b, c, h, w = x.size()
    
            # Channel-only Self-Attention
            channel_wv = self.ch_wv(x)  # bs,c//2,h,w
            channel_wq = self.ch_wq(x)  # bs,1,h,w
            channel_wv = channel_wv.reshape(b, c // 2, -1)  # bs,c//2,h*w
            channel_wq = channel_wq.reshape(b, -1, 1)  # bs,h*w,1
            channel_wq = self.softmax_channel(channel_wq)
            channel_wz = torch.matmul(channel_wv, channel_wq).unsqueeze(-1)  # bs,c//2,1,1
            channel_weight = self.sigmoid(self.ln(self.ch_wz(channel_wz).reshape(b, c, 1).permute(0, 2, 1))).permute(0, 2,
                                                                                                                     1).reshape(
                b, c, 1, 1)  # bs,c,1,1
            channel_out = channel_weight * x
    
            # Spatial-only Self-Attention
            spatial_wv = self.sp_wv(channel_out)  # bs,c//2,h,w
            spatial_wq = self.sp_wq(channel_out)  # bs,c//2,h,w
            spatial_wq = self.agp(spatial_wq)  # bs,c//2,1,1
            spatial_wv = spatial_wv.reshape(b, c // 2, -1)  # bs,c//2,h*w
            spatial_wq = spatial_wq.permute(0, 2, 3, 1).reshape(b, 1, c // 2)  # bs,1,c//2
            spatial_wq = self.softmax_spatial(spatial_wq)
            spatial_wz = torch.matmul(spatial_wq, spatial_wv)  # bs,1,h*w
            spatial_weight = self.sigmoid(spatial_wz.reshape(b, 1, h, w))  # bs,1,h,w
            spatial_out = spatial_weight * channel_out
            return spatial_out
    
    
    if __name__ == '__main__':
        input = torch.randn(1, 512, 7, 7)
        psa = SequentialPolarizedSelfAttention(channel=512)
        output = psa(input)
        print(output.shape)
    
    
  • 实验结果

    2021-12-16 20:30:36,981 - mmdet - INFO - 
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.346
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.522
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.385
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.123
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.474
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.676
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.422
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.422
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.422
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.170
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.570
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.743
    

7. Spatial Group-wise Enhance: Improving Semantic Feature Learning in Convolutional Networks

论文地址:https://arxiv.org/pdf/1905.09646.pdf

  • 网络结构

    主要是用在语义分割上,所以在检测上的效果一般,没有带来多少提升

    image-20211217112822310

  • Pytorch代码

    import numpy as np
    import torch
    from torch import nn
    from torch.nn import init
    
    
    class SpatialGroupEnhance(nn.Module):
    
        def __init__(self, groups):
            super().__init__()
            self.groups = groups
            self.avg_pool = nn.AdaptiveAvgPool2d(1)
            self.weight = nn.Parameter(torch.zeros(1, groups, 1, 1))
            self.bias = nn.Parameter(torch.zeros(1, groups, 1, 1))
            self.sig = nn.Sigmoid()
            self.init_weights()
    
        def init_weights(self):
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    init.kaiming_normal_(m.weight, mode='fan_out')
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
                elif isinstance(m, nn.BatchNorm2d):
                    init.constant_(m.weight, 1)
                    init.constant_(m.bias, 0)
                elif isinstance(m, nn.Linear):
                    init.normal_(m.weight, std=0.001)
                    if m.bias is not None:
                        init.constant_(m.bias, 0)
    
        def forward(self, x):
            b, c, h, w = x.shape
            x = x.view(b * self.groups, -1, h, w)  # bs*g,dim//g,h,w
            xn = x * self.avg_pool(x)  # bs*g,dim//g,h,w
            xn = xn.sum(dim=1, keepdim=True)  # bs*g,1,h,w
            t = xn.view(b * self.groups, -1)  # bs*g,h*w
    
            t = t - t.mean(dim=1, keepdim=True)  # bs*g,h*w
            std = t.std(dim=1, keepdim=True) + 1e-5
            t = t / std  # bs*g,h*w
            t = t.view(b, self.groups, h, w)  # bs,g,h*w
    
            t = t * self.weight + self.bias  # bs,g,h*w
            t = t.view(b * self.groups, 1, h, w)  # bs*g,1,h*w
            x = x * self.sig(t)
            x = x.view(b, c, h, w)
    
            return x
    
    
    if __name__ == '__main__':
        input = torch.randn(50, 512, 7, 7)
        sge = SpatialGroupEnhance(groups=8)
        output = sge(input)
        print(output.shape)
    
  • 实验结果

    2021-12-16 21:39:42,785 - mmdet - INFO - 
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.342
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.516
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.381
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.117
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.474
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.652
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.415
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.415
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.415
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.155
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.565
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.718
    

8. Coordinate Attention for Efficient Mobile Network Design

论文地址:https://arxiv.org/abs/2103.02907

  • 网络结构

    主要应用在轻量级网络上,在resnet系列上效果不好。

    image-20211210155718877

  • Pytorch代码

    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    
    
    class h_sigmoid(nn.Module):
        def __init__(self, inplace=True):
            super(h_sigmoid, self).__init__()
            self.relu = nn.ReLU6(inplace=inplace)
    
        def forward(self, x):
            return self.relu(x + 3) / 6
    
    
    class h_swish(nn.Module):
        def __init__(self, inplace=True):
            super(h_swish, self).__init__()
            self.sigmoid = h_sigmoid(inplace=inplace)
    
        def forward(self, x):
            return x * self.sigmoid(x)
    
    
    class CoordAtt(nn.Module):
        def __init__(self, inp, oup, reduction=32):
            super(CoordAtt, self).__init__()
            self.pool_h = nn.AdaptiveAvgPool2d((None, 1))
            self.pool_w = nn.AdaptiveAvgPool2d((1, None))
    
            mip = max(8, inp // reduction)
    
            self.conv1 = nn.Conv2d(inp, mip, kernel_size=1, stride=1, padding=0)
            self.bn1 = nn.BatchNorm2d(mip)
            self.act = h_swish()
    
            self.conv_h = nn.Conv2d(mip, oup, kernel_size=1, stride=1, padding=0)
            self.conv_w = nn.Conv2d(mip, oup, kernel_size=1, stride=1, padding=0)
    
        def forward(self, x):
            identity = x
    
            n, c, h, w = x.size()
            x_h = self.pool_h(x)
            x_w = self.pool_w(x).permute(0, 1, 3, 2)
    
            y = torch.cat([x_h, x_w], dim=2)
            y = self.conv1(y)
            y = self.bn1(y)
            y = self.act(y)
    
            x_h, x_w = torch.split(y, [h, w], dim=2)
            x_w = x_w.permute(0, 1, 3, 2)
    
            a_h = self.conv_h(x_h).sigmoid()
            a_w = self.conv_w(x_w).sigmoid()
    
            out = identity * a_w * a_h
    
            return out
    
    
  • 实验结果

    2021-12-16 19:04:16,776 - mmdet - INFO - 
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.340
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.516
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.386
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.127
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.457
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.632
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.408
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.408
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.408
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.162
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.546
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.716
    

9. Global Attention Mechanism: Retain Information to Enhance Channel-Spatial Interactions

论文地址: https://arxiv.org/abs/2112.05561

  • 网络结构

    计算量特别大,效果一般

  • Pytorch代码

    class GAM_Attention(nn.Module):
        def __init__(self, in_channels, out_channels, rate=4):
            super(GAM_Attention, self).__init__()
    
            self.channel_attention = nn.Sequential(
                nn.Linear(in_channels, int(in_channels / rate)),
                nn.ReLU(inplace=True),
                nn.Linear(int(in_channels / rate), in_channels)
            )
    
            self.spatial_attention = nn.Sequential(
                nn.Conv2d(in_channels, int(in_channels / rate), kernel_size=7, padding=3),
                nn.BatchNorm2d(int(in_channels / rate)),
                nn.ReLU(inplace=True),
                nn.Conv2d(int(in_channels / rate), out_channels, kernel_size=7, padding=3),
                nn.BatchNorm2d(out_channels)
            )
    
        def forward(self, x):
            # print(x)
            b, c, h, w = x.shape
            x_permute = x.permute(0, 2, 3, 1).view(b, -1, c)
            x_att_permute = self.channel_attention(x_permute).view(b, h, w, c)
            x_channel_att = x_att_permute.permute(0, 3, 1, 2)
    
            x = x * x_channel_att
    
            x_spatial_att = self.spatial_attention(x).sigmoid()
            out = x * x_spatial_att
            # print(out)
    
            return out
    
  • 实验结果

    2021-12-16 16:14:20,693 - mmdet - INFO - 
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.350
     Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=1000 ] = 0.530
     Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=1000 ] = 0.399
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.131
     Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.481
     Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.683
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.424
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=300 ] = 0.424
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=1000 ] = 0.424
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=1000 ] = 0.171
     Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=1000 ] = 0.575
     Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=1000 ] = 0.745
    

更多注意力

参考:https://github.com/xmu-xiaoma666/External-Attention-pytorch

另外还有一些用在语义分割上面的结构,这里就不测试了,大家可以自行下去测试

双路注意力机制-DANET

论文标题:Fu_Dual_Attention_Network_for_Scene_Segmentation

论文地址:https://openaccess.thecvf.com/content_CVPR_2019/papers/Fu_Dual_Attention_Network_for_Scene_Segmentation_CVPR_2019_paper.pdf

时间:2019

相当于之前是并行的结构,现在改成了串行的结构然后做特征的concat

image-20211210154740171

image-20211210154829462

位置注意力-CCNET

在上面的danet上改的,主要是解决计算量的问题, 通过十字交叉的结构来解决

论文标题:CCNet: Criss-Cross Attention for Semantic Segmentation

论文地址:https://openaccess.thecvf.com/content_ICCV_2019/papers/Huang_CCNet_Criss-Cross_Attention_for_Semantic_Segmentation_ICCV_2019_paper.pdf

时:2019

image-20211210155141717

找到我

你可以通过这些方式来寻找我。

B站:肆十二-

优快云:肆十二

知乎:肆十二

微博:肆十二-

现在关注以后就是老朋友喽!

image-20211212195912911

AI人工智能领域PyTorch的注意力机制应用 本文旨在为读者提供关于PyTorch中注意力机制的全面指南,从基础概念到高级应用,帮助开发者理解和实现各种注意力机制模型。我们将重点关注自然语言处理领域的应用,但也会涉及计算机视觉等其他AI领域。文章首先介绍注意力机制的基本概念,然后深入探讨其数学原理和PyTorch实现,接着通过实际案例展示应用方法,最后讨论未来发展趋势和挑战。注意力机制(Attention Mechanism): 一种让模型能够动态关注输入数据不同部分的神经网络技术自注意力(Self-Attention) 阅读详情

相关推荐

注意力机制及代码实现

注意力机制是CV深度学习里面常用到的一个小技巧,注意力机制的核心就是让网络去关注到它所需要关注的地方。当我们使用卷积网络去处理图片的时候,我们希望网络去关注应该注意的地方,而不是什么都关注。我们肯定不能自己手动去条件需要注意的地方,这个时候如何让卷积网络去自适应注意重要的位置就变得极为重要了。注意力机制就是实现网络自适应注意通道注意力机制,空间注意力机制,通道空间注意力机制.沿通道方向自适应发现哪些比较重要,然后网络更关注重要的语义特征。自适应发现我们的featuremap哪些区域。...

@bangbang的博客 1427

【Pytorch 学习笔记】def init_weights() 初始化参数

nn.init.constant_() 是 torch.nn 中的用于填充数值的函数,这里用于指定初始化值,还有许多其他函数可用于此。在生成网络 net 时,会指定 net 最初的权重,对于一些预训练好的模型权重,就可以放在这个部分进行加载。在 CNN 中,经常可以看见 init_weights() 函数,它是用来初始化网络参数的。并不是所有的层都能初始化权重的,比如 nn.MaxPool2d(),它是无法初始化的。init_weights(self, m) 中的 m 就是指 net 中的某一层。

zjy_cn的博客 5937

基于Pytorch框架实现的ResNet18中嵌入视觉注意力机制python+源代码+文档说明+数据集

<项目介绍> 运行方式 模型训练: 模型文件一共包含了ResNet18.py,SE-ResNet18.py,ECA-ResNet18.py,CBAM-ResNet18.py,my_attention.py 五个文件,分别代表了ResNet18,嵌入SE模型。嵌入ECA模型,嵌入CBAM模型,以及修改后的SE模型的文件。每个文件均可独立运行,在安装完对应的包之后, - 不懂运行,下载完可以私聊问,可远程教学 该资源内项目源码是个人的毕设,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 --------

【pytorch基础】模型的自定义参数初始化方式

总结 单层网络初始化 直接调用torch.nn.innit里的初始化函数 多层网络初始化 2.1 使用apply和weight_init函数 2.2 在__init__函数使用self.modules()初始化 详细阐述 1. 单层网络 在创建model后直接调用torch.nn.innit里的初始化函数 layer1 = torch.nn.Linear(10,20) torch.nn.init.xavier_uniform_(layer1.weight) torch.nn.init.constan

All_In_gzx_cc的博客 3590

GATE-master_pytorch实现gate_gate_注意力机制_自注意力机制_自编码_

GATE的pytorch实现,图自编码器+注意力机制

半导体关键系统之RMS浅谈

这种系统还要求设备在设备上的配方发生变化时通知工厂主机,并需要与EAP(Equipment Automation Process)联结,旨在实时管控自动化系统所用配方与用户当初的设定是否匹配,从而使得自动化系统所用的配方更加趋于安全。例如,制药行业中的药品生产管理系统(GMP),它对药品的生产过程进行严格控制,包括原材料的采购、生产工艺流程、质量控制等方面。这些系统通常与企业的生产系统集成,能够对产品的配方进行精细化管理,包括配方的设计、试验、验证、生产等环节。

阿拉伯梳子的专栏 6155

教你用PyTorch实现“看图说话”(附代码、学习资源)

作者:FAIZAN SHAIKH翻译:和中华校对:白静本文共2200字,建议阅读10分钟。本文用浅显易懂的方式解释了什么是“看图说话”(Image Captioning)...

数据派THU 6627

金融波动率的“捕手”:GARCH模型,揭秘市场波动的“聚集密码”

摘要: GARCH模型(广义自回归条件异方差)是金融时间序列分析中用于捕捉“波动聚类”现象的核心工具。传统模型(如ARIMA)无法刻画金融数据的时变波动特性,而GARCH通过建模条件方差的动态变化(如$\sigma_t^2 = \omega + \alpha \varepsilon_{t-1}^2 + \beta \sigma_{t-1}^2$),精准预测波动率。Python实战显示,GARCH能有效拟合模拟金融数据的波动聚类,残差无自相关,验证了其优越性。该模型在波动率预测、风险价值(VaR)计算和期权定

u010257409的博客 2054

PyTorch实现注意力机制及使用方法汇总,附30篇attention论文

还记得鼎鼎大名的《Attention is All You Need》吗?不过我们今天要聊的重点不是transformer,而是注意力机制。注意力机制最早应用于计算机视觉领域,后来也逐渐在NLP领域广泛应用,它克服了传统的神经网络的的一些局限,将有限的注意力集中在重点信息上,因而帮我们节省资源,快速获得最有效的信息。同样作为热门研究方向,注意力机制近几年相关的论文数量自然是十分可观,我这次就整理了一系列关于PyTorch 代码实现注意力机制以及使用方法的论文。。有需要的同学看文末领取。

学姐带你玩AI的博客 3181

GX WORKS2通过交换机连接PLC的方法

三菱PLC连接方法的分享

weixin_64927621的博客 3618

Vivado ILA抓不到低频信号?试试Capture Control模式,保姆级配置教程(附PWM调试实例)

本文详细解析了Vivado ILA的Capture Control模式在低频信号捕获中的应用,特别针对PWM调试等场景提供保姆级配置教程。通过条件采样和时间拉伸技术,有效解决传统ILA采样在低频信号调试中的存储深度不足、关键信号丢失等问题,并附赠呼吸灯PWM的完整调试实例,帮助FPGA开发者提升调试效率。

weixin_42549451的博客 349

使用注意力机制来做医学图像分割的解释和Pytorch实现

点击上方“AI公园”,关注公众号,选择加“星标“或“置顶”作者:Léo Fillioux编译:ronghuaiyang导读对两篇近期的使用注意力机制进行分割的文章进行了分析,并给出了简单...

AI公园 9786

Doris副本修复实战:从状态机到手动修复的完整指南

在分布式数据库系统中,多副本机制是实现高可用与数据一致性的核心技术。其原理是通过在不同节点存储数据的多个拷贝,确保部分节点故障时服务仍可继续。这项技术的核心价值在于保障数据可靠性,并支撑在线分析处理(OLAP)等对数据一致性要求高的应用场景。当副本出现损坏、丢失或版本不一致时,系统通常依赖自动修复机制,但在元数据损坏、多副本同时故障等复杂场景下,自动修复可能失效,需要深入理解副本状态机并借助手动工具介入。本文将聚焦Doris数据库,解析Tablet副本状态流转(如BAD、VERSION_ERROR),并详细

weixin_32288959的博客 458

计算机视觉 - Attention机制(附代码)

Attention机制1.Attention简介2.Attention原理3.Attention的不同类型4.CBAM实现(Pytorch) 1.Attention简介 Attention中文意思为注意力,这个机制放到计算机视觉里,类似于给我们看一张美女帅哥的图片,我们第一眼首先关注的地方是这个人的哪里呢😏 你们第一眼看的是哪里呢😏 最早attention机制就应用到计算机视觉中,这里说的机制,其实就是神经网络中一个模块,类似于U-Net加上attention机制的变化。 看出什么变化了吗,其实就是在

weixin_42010722的博客 8438

C++坦克大战源代码

【代码】C++坦克大战源代码。

强国豪,林中霖 2608

大学计算 - NumPy库的矩阵运算 实训答案

本文介绍了三个NumPy矩阵操作的实验练习。第一关练习ndarray类型操作,包括矩阵构造、元素平方和计算、矩阵乘积运算和逆矩阵行列式计算;第二关针对matrix类型,涉及绝对值最大值获取、特定矩阵乘积运算和转置矩阵特征值计算;第三关实现Moore-Penrose伪逆矩阵计算,并与NumPy内置pinv函数结果比较误差。实验涵盖了NumPy核心矩阵操作,展示了从基础运算到高级矩阵分解的应用,帮助掌握科学计算中的矩阵处理技巧。

2403_89314916的博客 309

即插即用 | 超越CBAM,全新注意力机制,GAM表现卓著(附Pytorch实现)

为了提高计算机视觉任务的性能,人们研究了各种注意力机制。然而,以往的方法忽略了保留通道和空间方面的信息以增强跨维度交互的重要性。因此,本文提出了一种通过减少信息弥散和放大全局交互表示来提高深度神经网络性能的全局注意力机制。本文引入了3D-permutation 与多层感知器的通道注意力和卷积空间注意力子模块。在CIFAR-100和ImageNet-1K上对所提出的图像分类机制的评估表明,本文的方法稳定地优于最近的几个

机器学习社区 1万+

2023华为OD机试真题B卷 Python 实现【最长的元音子串长度】

定义当一个字符串只有元音字母(a,e,i,o,u,A,E,I,O,U)组成,称为元音字符串,现给定一个字符串,请找出其中最长的元音字符串,并返回其长度,如果找不到请返回0, 字符串中任意一个连续字符组成的子序列称为该字符串的子串

MISAYAONE的博客 900

计算机视觉中的注意力:PyTorch中实现MultiHead和CBAM

自从Transformer在“注意力就是你所需要的”的工作中被引入以来,在自然语言处理领域已经发生了一个转变,即用基于注意力的网络取代循环神经网络(RNN)。在当前的文献中,已经有很多很棒的文章描述了这种方法。下面是我在评论中发现的两个最好的:带注释的Transformer和Transformer的可视化解释。 然而,在研究了如何在计算机视觉中实现注意力(建议阅读:Understanding attention Modules, CBAM, Papers with code - attention, Sel

deephub 6193

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Pytorch 实现注意力机制

import math import torch import torch.nn as nn import os def file_name_walk(file_dir): for root, dirs, files in os.walk(file_dir): # print("root", root) # 当前目录路径 print("dirs"...

JasonYUJX的博客 7068

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

论文--计算机视觉中的注意力机制

计算机视觉中用到的注意力机制模块

有问题请直接说问题就好 4418

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

神经网络 || 注意力机制的Pytorch代码实现

文章目录1 注意力机制的诞生2 介绍SeNet模型及Pytorch代码实现 1 注意力机制的诞生 注意力机制,起初是作为自然语言处理中的工作为大家熟知,文章Attention is all you need详细介绍了“什么是注意力机制”,有兴趣的小伙伴可以下载原文看看。 SeNet-Squeeze-and-Excitation Networks是注意力机制在计算机视觉中应用的早期工作之一,并获得了2017年的imagenet,也就是最后一届imagenet比赛的冠军。 2 介绍SeNet模型及Pyt

#仙女不扎马尾#的博客 1356

17 篇注意力机制 PyTorch 实现!

PyTorch实现各种注意力机制。注意力(Attention)机制最早在计算机视觉中应用,后来又在 NLP 领域发扬光大,该机制将有限的注意力集中在重点信息上,从而节省资源,快速获得最有效...

weixin_40920183的博客 1321

pytorch代码实现注意力机制之EMA

注意力机制之EMA

DM_zx的博客 2万+

计算机视觉的应用21-基于含有注意力机制的CoAtNet模型的图像分类任务实现,利用pytorch搭建模型

大家好,我是微学AI,今天我给大家介绍一下计算机视觉的应用21-基于注意力机制CoAtNet模型的图像分类任务实现,加载数据进行模型训练。本文我们将详细介绍CoAtNet模型的原理,并通过一个基于PyTorch框架的实例,展示如何加载数据,训练含有注意力机制的CoAtNet模型,从操作上理解该模型。

微学AI的博客 2270

【即学即用】ECANet通道注意力机制实战解析(附PyTorch实现)

本文深入解析了ECANet通道注意力机制的核心原理与实战应用。通过对比SENet,重点阐述了其利用自适应一维卷积实现高效局部跨通道交互的精妙设计,并提供了可直接复用的PyTorch实现代码。该模块能即插即用地嵌入ResNet、MobileNet等主流网络,在几乎不增加参数量的情况下有效提升模型性能,适用于分类、检测与分割等多种计算机视觉任务。

weixin_29091837的博客 369
上一篇: 【大作业-05】手把手教你使用YOLOV5训练自己的目标检测模型-口罩检测-视频教程
下一篇: 【大作业-06】教你用300行Python代码实现一个人脸识别系统
肆十二
肆十二 优质创作者: 人工智能技术领域 优质创作者: 人工智能技术领域
博客等级 码龄9年 2万+粉丝 241原创
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肆十二

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值