mobileNet-v1之pytorch實現

       本博文主要是針對mobileNet-v1採用pytorch進行實現,代碼也是參考他人的代碼,具體實現如下:

# -*- coding: utf-8 -*-
"""
Created on Tue May 21 20:41:58 2019

@author: Administrator
"""
import time 
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.models as models
from torch.autograd import Variable


class MobileNet(nn.Module):
    def __init__(self):
        super(MobileNet,self).__init__()
        
        #標準卷積
        def conv_bn(inp,oup,stride):
            return nn.Sequential(
                    nn.Conv2d(inp,oup,3,stride,1,bias = False),
                    nn.BatchNorm2d(oup),
                    nn.ReLU(inplace = True))
        
        #深度卷積
        def conv_dw(inp,oup,stride):
            return nn.Sequential(
                    nn.Conv2d(inp,inp,3,stride,1,groups = inp,bias = False),
                    nn.BatchNorm2d(inp),
                    nn.ReLU(inplace = True),
                    
                    nn.Conv2d(inp,oup,1,1,0,bias = False),
                    nn.BatchNorm2d(oup),
                    nn.ReLU(inplace = True))
            
        #網絡模型聲明
        self.model = nn.Sequential(
                conv_bn(3,32,2),
                conv_dw(32,64,1),
                conv_dw(64,128,2),
                conv_dw(128,128,1),
                conv_dw(128,256,2),
                conv_dw(256,256,1),
                conv_dw(256,512,2),
                conv_dw(512,512,1),
                conv_dw(512,512,1),
                conv_dw(512,512,1),
                conv_dw(512,512,1),
                conv_dw(512,512,1),
                conv_dw(512,1024,2),
                conv_dw(1024,1024,1),
                nn.AvgPool2d(7),)
      
        self.fc = nn.Linear(1024,1000)
    
    #網絡的前向過程    
    def forward(self,x):
        x = self.model(x)
        x = x.view(-1,1024)
        x = self.fc(x)
        return x
    

#速度評估
def speed(model,name):
    t0 = time.time()
    input = torch.rand(1,3,224,224).cpu()
    input = Variable(input,volatile = True)
    t1 = time.time()
    
    model(input)
    t2 = time.time()
    
    model(input)
    t3 = time.time()
    
    print('%10s : %f'%(name,t3 - t2))
    

if __name__ == '__main__':
    
    resnet18 = models.resnet18().cpu()
    alexnet = models.alexnet().cpu()
    vgg16 = models.vgg16().cpu()
    squeezenet = models.squeezenet1_0().cpu()
    mobilenet = MobileNet().cpu()
    
    speed(resnet18,'resnet18')
    speed(alexnet,'alexnet')
    speed(vgg16,'vgg16')
    speed(squeezenet,'squeezenet')
    speed(mobilenet,'mobilenet')

運行結果:

這個運行結果是我的電腦跑出來的結果,若有不當之處,請指教,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章