CV中的注意力机制(一)——SENet(通道注意力)

SENet

实现步骤

  1. 对输入进来的特征层进行全局平均池化
  2. 然后进行两次全连接,第一次全连接神经元个数较少第二次全连接神经元个数和输入特征层相同
  3. 在完成两次全连接后,再取一次Sigmoid将值固定到0-1之间,此时获得了输入特征层每一个通道的权值(0-1之间)
  4. 获得的权值乘上原输入特征层即可。

流程图示

在这里插入图片描述

结合ResNet网络实战

左图为原始的residual模块,右图为加入SE的residual模块
左图为原始的residual模块,右图为加入SE的residual模块。

测试

uhhh,自己的本子是3070的,就不在ImageNet1k上做测试了,还是在ImageNet-mini浅试一下吧。先放出来最终的效果:在这里插入图片描述
从图中很明显的可以看出来,加入了SE模块后的ResNet大大降低了错误率,加入SE模块后,计算量会增大很多,这也是为什么虽然SE模块能提高准确率,但是没有被广泛应用的最大的原因。废话不多说,上代码,注释就免了。。。。。我还是相信各位大佬的实力的。

SE模块
import torch
import torch.nn as nn


class se_block(nn.Module):
    def __init__(self, channels, ratio=16):
        super(se_block, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Sequential(
            nn.Linear(channels, channels // ratio, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(channels // ratio, channels, bias=False),
            nn.Sigmoid()
        )

    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)
模型代码
import torch
import torch.nn as nn
from module.se_module import se_block


class SEBottleneck(nn.Module):
    expansion = 4
    def __init__(self, in_planes, out_planes, stride=(1, 1),
                 downsample=None, reduction=16):
        super(SEBottleneck, self).__init__()
        self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=(1, 1), bias=False)
        self.bn1 = nn.BatchNorm2d(out_planes)
        self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=(3, 3), stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_planes)
        self.conv3 = nn.Conv2d(out_planes, out_planes * 4, kernel_size=(1, 1), bias=False)
        self.bn3 = nn.BatchNorm2d(out_planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.se = se_block(out_planes * 4, ratio=reduction)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)
        out = self.se(out)

        if self.downsample is not None:
            residual = self.downsample(x)
        out += residual
        out = self.relu(out)
        return out


class ResNet(nn.Module):

    def __init__(self, block, blocks_num, num_classes=1000, include_top=True):
        super(ResNet, self).__init__()
        self.include_top = include_top
        self.in_channel = 64
        self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=(7, 7), stride=(2, 2),
                               padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(self.in_channel)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, blocks_num[0])
        self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
        self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
        self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
        if self.include_top:
            self.avgpool = nn.AdaptiveAvgPool2d((1, 1))  # output size = (1, 1)
            self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, channel, block_num, stride=(1, 1)):
        downsample = None
        if stride != 1 or self.in_channel != channel * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.in_channel, channel * block.expansion, kernel_size=(1, 1),
                          stride=stride, bias=False),
                nn.BatchNorm2d(channel * block.expansion))

        layers = []
        layers.append(block(self.in_channel,
                            channel,
                            downsample=downsample,
                            stride=stride))
        self.in_channel = channel * block.expansion

        for _ in range(1, block_num):
            layers.append(block(self.in_channel,
                                channel))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        if self.include_top:
            x = self.avgpool(x)
            x = torch.flatten(x, 1)
            x = self.fc(x)

        return x

def se_resnet50(num_classes=1000, include_top=True):
    return ResNet(SEBottleneck, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top)

训练及测试
import os
import torch
import numpy as np
import torch.nn as nn
from tqdm import tqdm
import torch.optim as optim
import matplotlib.pylab as plt
from module.se_resnet import se_resnet50
from module.resnet import resnet50
from data import _main

def main():
    device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    print('Using {} device for train.'.format(device))
    train_num, train_loader, val_num, val_loader = _main()
    weights_path = r'seresnet50-60a8950a85b2b.pkl'
    model = se_resnet50(num_classes=100)
    #
    # weights_path = r'resnet50-0676ba61.pth'
    # model = resnet50(num_classes=100)

    pre_weights = torch.load(weights_path, map_location=device)
    pre_dict = {k: v for k, v in pre_weights.items() if model.state_dict()[k].numel() == v.numel()}
    missing_keys, unexpected_keys = model.load_state_dict(pre_dict, strict=False)
    model.to(device)
    loss_function = nn.CrossEntropyLoss()
    params =[p for p in model.parameters() if p.requires_grad]
    # optimizer = optim.SGD(params, lr=0.3, momentum=0.9, weight_decay=1e-4)
    optimizer = optim.Adam(params, lr=2e-4)
    epochs = 40
    save_path = 'se_resnet50.pkl'
    # save_path = 'resnet50.pth'
    best_acc = 0.0
    train_steps = len(train_loader)

    for epoch in range(epochs):
        model.train()
        running_loss = 0.0
        train_bar = tqdm(train_loader)
        for step, data in enumerate(train_bar):
            images, labels = data
            optimizer.zero_grad()
            outputs = model(images.to(device))
            loss = loss_function(outputs, labels.to(device))
            loss.backward()
            optimizer.step()

            running_loss += loss.item()

            train_bar.desc = 'train epoch[{}/{}] loss:{:.3f}'.format(epoch + 1, epochs, loss)
        loss_list.append(running_loss / train_steps)
        model.eval()
        acc = 0.0
        with torch.no_grad():
            val_bar = tqdm(val_loader)
            for val_data in val_bar:
                val_images, val_labels = val_data
                outputs = model(val_images.to(device))
                _, predice_y = torch.max(outputs, dim=1)
                acc += torch.eq(predice_y, val_labels.to(device)).sum().item()
            val_acc = acc / val_num
            print('[epoch %d] training loss:%.3f val_accuracy:%.3f'
                  % (epoch + 1, running_loss / train_steps, val_acc))
            if val_acc > best_acc:
                best_acc = val_acc
                torch.save(model.state_dict(), save_path)

    print('Finished Training!')
    print('Best accuracy is {}'.format(best_acc))
    
if __name__ == '__main__':
    main()

欢迎转载与提问!!!!!!!!

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值