美文网首页
使用pytorch实现简化版MobileNetv1,并训练cif

使用pytorch实现简化版MobileNetv1,并训练cif

作者: 白老包 | 来源:发表于2019-08-19 00:20 被阅读0次

    我认为深度学习用在嵌入式设备上也就两条路,1:让嵌入式设备更强大。2:让算法更精简。第一条路也就是各种加速卡或者专业设计的智能芯片。现在越来越多这种芯片成熟了。第二条路也就是精简(一般称之为压缩)算法的路子。我尝试使用pytorch实现简化版MobileNetv1。为什么是简化版?因为我的GTX1060乞丐版还是不指望能训练完整个imagenet(行文至此我突然发现我的Linux环境还没装cuda,晕),cifar-10的分辨率较小,适合我现在这种快速验证的工作。为什么是MobileNetv1?因为相比其他几个轻量级的网络这个最简单。废话说多了,看一下MobileNetv1的结构和特点把。
    MobileNetv1的结构在论文中介绍的很清楚。如下图所示。

    QQ截图20190817220238.jpg
    结合原文的3.2节,我认为其结构特点如下。
    1.第一层依然为传统的卷积结构
    2.每一层后均使用batchnorm,激活函数均使用ReLU。
    3.全连接层前用了一个平均池化层。
    4.Depthwise Separable convolutions
    Depthwise Separable convolutions 的结构论文中也进行了介绍,如下图所示。
    QQ截图20190817220249.jpg
    因此我认为通过更改一个现有CNN的结构可以很容易得到一个精简MobileNet结构。
    为了对比效果我使用一个简单的两层神经网络作为对比,并根据他进行修改。结构如下
             self.conv1 = nn.Sequential(nn.Conv2d(3, 8, 5),\
                                        nn.BatchNorm2d(8),\
                                        nn.ReLU(),\
                                        nn.MaxPool2d(2, 2))
             self.conv2 = nn.Sequential(nn.Conv2d(8, 16, 5),\
                                        nn.BatchNorm2d(16),\
                                        nn.ReLU(),\
                                        nn.MaxPool2d(2, 2),\
                                        nn.Conv2d(16, 4, 1)) 
             self.fc = nn.Linear(100, 10)
    

    经过测试,其能达到42%的正确率,有点低,不过作为一个cuda忘了装的人来说这个计算量是我的CPU能扛得住的。
    简化为MobileNet,就是把第二层转换为Depthwise Separable convolutions结构。更改后的结构如下

             self.conv1 = nn.Sequential(nn.Conv2d(3, 8, 5),\
                                        nn.BatchNorm2d(8),\
                                        nn.ReLU(),\
                                        nn.MaxPool2d(2, 2))
             self.conv2 = nn.Sequential(nn.Conv2d(8, 8, 5),\
                                        nn.BatchNorm2d(8),\
                                        nn.ReLU(),\
                                        nn.Conv2d(8, 16, 1),\
                                        nn.BatchNorm2d(16),\
                                        nn.ReLU(),\
                                        nn.MaxPool2d(2, 2),\
                                        nn.Conv2d(16, 4, 1)) 
             self.fc = nn.Linear(100, 10)
    

    最后一个平均池化层的效果不太好所以我换成了一个1*1的卷积层。完整代码如下

    # -*- coding: utf-8 -*-
    """
    Created on Sun Aug 18 11:17:30 2019
    
    @author: BHN
    """
    
    import torch
    import torchvision
    import torchvision.transforms as transforms
    
    transform = transforms.Compose(
        [transforms.ToTensor(),
         transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
    
    trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
                                            download=True, transform=transform)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
                                              shuffle=True, num_workers=0)
    
    testset = torchvision.datasets.CIFAR10(root='./data', train=False,
                                           download=True, transform=transform)
    testloader = torch.utils.data.DataLoader(testset, batch_size=4,
                                             shuffle=False, num_workers=0)
    
    classes = ('plane', 'car', 'bird', 'cat',
               'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
    
    import numpy as np
    
    
    import torch.nn as nn
    import torch.nn.functional as F
    
    
    class Net(nn.Module):
    
         def __init__(self):
             super(Net, self).__init__()
    #         self.conv1 = nn.Sequential(nn.Conv2d(3, 8, 5),\
    #                                    nn.BatchNorm2d(8),\
    #                                    nn.ReLU(),\
    #                                    nn.MaxPool2d(2, 2))
    #         self.conv2 = nn.Sequential(nn.Conv2d(8, 16, 5),\
    #                                    nn.BatchNorm2d(16),\
    #                                    nn.ReLU(),\
    #                                    nn.MaxPool2d(2, 2),\
    #                                    nn.Conv2d(16, 4, 1)) 
    #         self.fc = nn.Linear(100, 10)
             
             self.conv1 = nn.Sequential(nn.Conv2d(3, 8, 5),\
                                        nn.BatchNorm2d(8),\
                                        nn.ReLU(),\
                                        nn.MaxPool2d(2, 2))
             self.conv2 = nn.Sequential(nn.Conv2d(8, 8, 5),\
                                        nn.BatchNorm2d(8),\
                                        nn.ReLU(),\
                                        nn.Conv2d(8, 16, 1),\
                                        nn.BatchNorm2d(16),\
                                        nn.ReLU(),\
                                        nn.MaxPool2d(2, 2),\
                                        nn.Conv2d(16, 4, 1)) 
             self.fc = nn.Linear(100, 10)
             
             
         def forward(self, x):
             x = self.conv1(x)
             x = self.conv2(x)
    #         x = self.conv3(x)
    #         x = self.conv4(x)
    #         x = self.conv5(x)
    #         x = self.conv6(x)
             x = x.view(-1, 100)
             x = self.fc(x)
    
             return x
        
        
    net = Net()
    
    import torch.optim as optim
    
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.RMSprop(net.parameters(), lr=0.001, momentum=0.9)
    
    for epoch in range(2):  # loop over the dataset multiple times
    
        running_loss = 0.0
        for i, data in enumerate(trainloader, 0):
            # get the inputs; data is a list of [inputs, labels]
            inputs, labels = data
    
            # zero the parameter gradients
            optimizer.zero_grad()
    
            # forward + backward + optimize
            outputs = net(inputs)
    #        print(outputs.shape)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()
    
            # print statistics
            running_loss += loss.item()
            if i % 2000 == 1999:    # print every 2000 mini-batches
                print('[%d, %5d] loss: %.3f' %
                      (epoch + 1, i + 1, running_loss / 2000))
                running_loss = 0.0
    
    print('Finished Training')
    
    dataiter = iter(testloader)
    images, labels = dataiter.next()
    
    
    outputs = net(images)
    _, predicted = torch.max(outputs, 1)
    
    print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
                                  for j in range(4)))
    
    correct = 0
    total = 0
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            outputs = net(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    
    print('Accuracy of the network on the 10000 test images: %d %%' % (
        100 * correct / total))
    

    正确率达到41%稍有下降,符合论文中在imagenet上的表现。
    根据这个工具可以测出原始模型的flops和参数数量为:866566.0和4950.0。精简MobileNetv1的为729766.0 和3502.0。可以发现有一定程度的减少,如果网络规模更大,将减少更多。
    经过测试传统的网络结构测试所有测试集的时间为8.88390240000001秒:精简MobileNetv1的测试时间为8.6628881秒,相差的不多,比Roof-line模型分析得到的差距要小。所以有时候理论和实际的差距还是有点大的。更详细的代码可以参考这位大神的代码
    总结:
    MobileNet确实能在正确率下降不多的情况下降低计算量和参数量,但是经过实际测试,下降的程度没有理论计算出的值高。

    相关文章

      网友评论

          本文标题:使用pytorch实现简化版MobileNetv1,并训练cif

          本文链接:https://www.haomeiwen.com/subject/yezksctx.html