MobileNet原理+手寫python代碼實(shí)現(xiàn)MobileNet

最近看到一個(gè)巨牛的人工智能教程,分享一下給大家。教程不僅是零基礎(chǔ),通俗易懂,而且非常風(fēng)趣幽默,像看小說(shuō)一樣!覺得太牛了,所以分享給大家。平時(shí)碎片時(shí)間可以當(dāng)小說(shuō)看,【點(diǎn)這里可以去膜拜一下大神的“小說(shuō)”】。

MobileNet是針對(duì)移動(dòng)端優(yōu)化的卷積,所以當(dāng)需要壓縮模型時(shí),可以考慮使用MobileNet替換卷積。下面我們開始學(xué)習(xí)MobileNet原理,并且先通過(guò)Tensorflow函數(shù)接口實(shí)現(xiàn)MobileNet,再手寫python代碼實(shí)現(xiàn)MobileNet。

轉(zhuǎn)載請(qǐng)注明出處:【huachao1001的簡(jiǎn)書:http://www.itdecent.cn/p/7bef96816f7d】

1 對(duì)比普通卷積和MobileNet原理

MobileNet是用于替換普通卷積,相比普通卷積,MobileNet參數(shù)更少,計(jì)算速度更快。我們先看一下輸入為(h=12,w=12,c=4),卷積為3*3,輸出為(h=12,w=12,c=2)前向計(jì)算中,普通卷積的參數(shù)量、乘法計(jì)算次數(shù)。普通卷積如下圖所示:


普通卷積

從上圖可以很簡(jiǎn)單的計(jì)算到,普通卷積參數(shù)總數(shù)為72個(gè),需要做10368次乘法計(jì)算。

相比普通卷積,MobileNet采用的方法是,將卷積分解為2個(gè)操作:depthwise和pointwise。pointwise比較容易理解,就是普通的卷積核為11的卷積。depthwise采用的方法不是普通卷積方式,我們知道,對(duì)于輸入通道數(shù)為4的feature map在計(jì)算卷積時(shí),輸出的每個(gè)通道都需要對(duì)應(yīng)4個(gè)33卷積核參數(shù)。這一步是最主要的耗時(shí),為了提升計(jì)算速度,MobileNet把每個(gè)輸入feature map對(duì)應(yīng)一個(gè)33卷積核,輸出通道數(shù)不變,即為4。而真正對(duì)通道數(shù)做改變的是在pointwise,也就是11的卷積。

注意:上面面論述針對(duì)的是輸入為(h=12,w=12,c=4),卷積為3*3,輸出為(h=12,w=12,c=2) 這種情況舉例說(shuō)明。

下面圖很清晰的理解mobilenet原理:

mobilenet

從上圖可以很簡(jiǎn)單的計(jì)算到,普通卷積參數(shù)總數(shù)為44個(gè),需要做6336次乘法計(jì)算??梢钥吹剑琺obilenet的參數(shù)和乘法計(jì)算次數(shù)明顯比普通卷積要小。這還僅僅是我列舉的簡(jiǎn)單例子,在實(shí)際網(wǎng)絡(luò)中,幾十層的網(wǎng)絡(luò)很常見,feature map也是遠(yuǎn)遠(yuǎn)大于12124。根據(jù)我的經(jīng)驗(yàn),普通100M的網(wǎng)絡(luò)模型,將所有卷積替換成mobilenet后,能降到20M以下,計(jì)算速度更是不在一個(gè)量級(jí)。

2 Tensorflow中使用MobileNet

在Tensorflow中,有depthwise對(duì)應(yīng)的函數(shù)接口,直接調(diào)用就可以了。由于pointwise就是普通的卷積核大小為1*1的卷積,而卷積的原理,我們?cè)?a target="_blank">《Tensorflow卷積實(shí)現(xiàn)原理+手寫python代碼實(shí)現(xiàn)卷積》一文中已經(jīng)講的很清楚了。所以我們只要關(guān)注depthwise即可。
在Tensorflow中,depthwise操作接口是:

tf.nn.depthwise_conv2d(
    input,
    filter,
    strides,
    padding,
    rate=None,
    name=None,
    data_format=None
)

假設(shè)我們的輸入和卷積核如下:

 #輸入,shape=[c,h,w]=[2,5,5]
input_data=[
              [[1,0,1,2,1],
               [0,2,1,0,1],
               [1,1,0,2,0],
               [2,2,1,1,0],
               [2,0,1,2,0]],

               [[2,0,2,1,1],
                [0,1,0,0,2],
                [1,0,0,2,1],
                [1,1,2,1,0],
                [1,0,1,1,1]],

            ]
#卷積核,shape=[in_c,k,k]=[2,3,3]
weights_data=[ 
               [[ 1, 0, 1],
                [-1, 1, 0],
                [ 0,-1, 0]],
               [[-1, 0, 1],
                [ 0, 0, 1],
                [ 1, 1, 1]] 
             ]

下面我們貼上完整調(diào)用depthwise的代碼:

import tensorflow as tf
def get_shape(tensor):
    [s1,s2,s3]= tensor.get_shape() 
    s1=int(s1)
    s2=int(s2)
    s3=int(s3)
    return s1,s2,s3
def chw2hwc(chw_tensor): 
    [c,h,w]=get_shape(chw_tensor) 
    cols=[]

    for i in range(c):
        #每個(gè)通道里面的二維數(shù)組轉(zhuǎn)為[w*h,1]即1列 
        line = tf.reshape(chw_tensor[i],[h*w,1])
        cols.append(line)

    #橫向連接,即將所有豎直數(shù)組橫向排列連接
    input = tf.concat(cols,1)#[w*h,c]
    #[w*h,c]-->[h,w,c]
    input = tf.reshape(input,[h,w,c])
    return input

def hwc2chw(hwc_tensor):
    [h,w,c]=get_shape(hwc_tensor) 
    cs=[] 
    for i in range(c): 
        #[h,w]-->[1,h,w] 
        channel=tf.expand_dims(hwc_tensor[:,:,i],0)
        cs.append(channel)
    #[1,h,w]...[1,h,w]---->[c,h,w]
    input = tf.concat(cs,0)#[c,h,w]
    return input
def tf_depthwise(input,weights ):
    depthwise=tf.nn.depthwise_conv2d( input, weights, [1, 1, 1, 1], padding='SAME' ) 
    return depthwise
def main(): 
    const_input = tf.constant(input_data , tf.float32)
    const_weights = tf.constant(weights_data , tf.float32 ) 
    input = tf.Variable(const_input,name="input")
    #[2,5,5]------>[5,5,2]
    input=chw2hwc(input)
    #[5,5,2]------>[1,5,5,2]
    input=tf.expand_dims(input,0) 
    weights = tf.Variable(const_weights,name="weights")
    #[2,3,3]-->[3,3,2]
    weights=chw2hwc(weights)
    #[3,3,2]-->[3,3,2,1]
    weights=tf.expand_dims(weights,3) 
    print(weights.get_shape().as_list())

    #[b,h,w,c]
    conv=tf_depthwise(input,weights )
    rs=hwc2chw(conv[0]) 

    init=tf.global_variables_initializer()
    sess=tf.Session()
    sess.run(init)
    conv_val = sess.run(rs)

    print(conv_val) 


if __name__=='__main__':
    main()

打印結(jié)果如下:

[[[ 1. -3.  0.  1. -2.]
  [-1.  3.  1. -1.  3.]
  [ 1. -1.  0.  3. -2.]
  [ 1.  1.  1. -2.  1.]
  [ 4.  1.  4.  2. -1.]]

 [[ 1.  3.  2.  3.  2.]
  [ 2.  1.  3.  4.  2.]
  [ 3.  4.  5.  6.  1.]
  [ 2.  3.  5.  4.  0.]
  [ 1.  2.  1. -1. -1.]]]

我們通過(guò)一個(gè)動(dòng)畫演示計(jì)算過(guò)程:
[圖片上傳失敗...(image-f2e073-1530334796526)]

3 手寫python代碼實(shí)現(xiàn)depthwise

import numpy as np
input_data=[
              [[1,0,1,2,1],
               [0,2,1,0,1],
               [1,1,0,2,0],
               [2,2,1,1,0],
               [2,0,1,2,0]],

               [[2,0,2,1,1],
                [0,1,0,0,2],
                [1,0,0,2,1],
                [1,1,2,1,0],
                [1,0,1,1,1]] 
            ]
weights_data=[ 
               [[ 1, 0, 1],
                [-1, 1, 0],
                [ 0,-1, 0]],
               [[-1, 0, 1],
                [ 0, 0, 1],
                [ 1, 1, 1]] 

           ]

#fm:[h,w]
#kernel:[k,k]
#return rs:[h,w] 
def compute_conv(fm,kernel):
    [h,w]=fm.shape
    [k,_]=kernel.shape 
    r=int(k/2)
    #定義邊界填充0后的map
    padding_fm=np.zeros([h+2,w+2],np.float32)
    #保存計(jì)算結(jié)果
    rs=np.zeros([h,w],np.float32)
    #將輸入在指定該區(qū)域賦值,即除了4個(gè)邊界后,剩下的區(qū)域
    padding_fm[1:h+1,1:w+1]=fm 
    #對(duì)每個(gè)點(diǎn)為中心的區(qū)域遍歷
    for i in range(1,h+1):
        for j in range(1,w+1): 
            #取出當(dāng)前點(diǎn)為中心的k*k區(qū)域
            roi=padding_fm[i-r:i+r+1,j-r:j+r+1]
            #計(jì)算當(dāng)前點(diǎn)的卷積,對(duì)k*k個(gè)點(diǎn)點(diǎn)乘后求和
            rs[i-1][j-1]=np.sum(roi*kernel)

    return rs

def my_depthwise(chw_input,chw_weights):
    [c,_,_]=chw_input.shape
    [_,k,_]=chw_weights.shape
    #outputs=np.zeros([h,w],np.float32)
    outputs=[] #注意跟conv的區(qū)別
    #對(duì)每個(gè)feature map遍歷,從而對(duì)每個(gè)feature map進(jìn)行卷積
    for i in range(c):
        #feature map==>[h,w]
        f_map=chw_input[i]
        #kernel ==>[k,k]
        w=chw_weights[i]
         
        rs =compute_conv(f_map,w)
        #outputs=outputs+rs   
        outputs.append(rs) #注意跟conv的區(qū)別
    return np.array( outputs)

def main():  

    #shape=[c,h,w]
    input = np.asarray(input_data,np.float32)
    #shape=[in_c,k,k]
    weights =  np.asarray(weights_data,np.float32) 
    rs=my_depthwise(input,weights) 
    print(rs) 


if __name__=='__main__':
    main() 

同樣,注釋寫的很清楚,不再解釋代碼。運(yùn)行結(jié)果如下:

[[[ 1. -3.  0.  1. -2.]
  [-1.  3.  1. -1.  3.]
  [ 1. -1.  0.  3. -2.]
  [ 1.  1.  1. -2.  1.]
  [ 4.  1.  4.  2. -1.]]

 [[ 1.  3.  2.  3.  2.]
  [ 2.  1.  3.  4.  2.]
  [ 3.  4.  5.  6.  1.]
  [ 2.  3.  5.  4.  0.]
  [ 1.  2.  1. -1. -1.]]]

可以看到,跟tensorflow的結(jié)果是一模一樣。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容